@heybox/hb-sdk 0.9.6-alpha.11 → 0.9.6-alpha.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +4 -1
- package/THIRD_PARTY_NOTICES.md +472 -48
- package/dist/cli-chunks/{artifact-BW6SD1G6.cjs → artifact-DTqf7LjW.cjs} +6 -5
- package/dist/cli-chunks/{build-B0Id0UTN.cjs → build-BY4DoIBI.cjs} +6 -5
- package/dist/cli-chunks/{create-DVu93Ekp.cjs → create-DG-eZzS2.cjs} +322 -4
- package/dist/cli-chunks/{dev-CeSjpEZQ.cjs → dev-BeSGi9u8.cjs} +20 -16
- package/dist/cli-chunks/{dev-context-CVc_BsWR.cjs → dev-context-7fvQuwt0.cjs} +22 -14
- package/dist/cli-chunks/{doctor-BF9mtkJr.cjs → doctor-DcxJh-U3.cjs} +1 -1
- package/dist/cli-chunks/{games-BKnDCklM.cjs → games-CbQNW3Z3.cjs} +1 -1
- package/dist/cli-chunks/{index-Cgui_8Rk.cjs → index-NJUh9sVX.cjs} +1 -1
- package/dist/cli-chunks/{index-Rp3UMZIO.cjs → index-lnwfzT8S.cjs} +73 -20
- package/dist/cli-chunks/index.esm-CvMA_ppV.cjs +7977 -0
- package/dist/cli-chunks/{index.esm-BK0eVYaM.cjs → index.esm-DOXvj-ZK.cjs} +7 -6
- package/dist/cli-chunks/{login-DpeDN-mt.cjs → login-PYy4XDVv.cjs} +1 -1
- package/dist/cli-chunks/{project-vite-Cg3jYqAJ.cjs → project-vite-Dzd2JLIc.cjs} +1 -1
- package/dist/cli-chunks/{remote-BQ-9rhTb.cjs → remote-r0tXpJh6.cjs} +13 -8
- package/dist/cli-chunks/{runtime-permission-env-BgipCJ0Z.cjs → runtime-permission-env-CN2K4GG7.cjs} +52 -6990
- package/dist/cli-chunks/{skill-D7pd4yPq.cjs → skill-BbrtzJTC.cjs} +2 -2
- package/dist/cli-chunks/{version-DbjRZkb6.cjs → version-SpegXNoR.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-DdLOxwBk.js +228 -0
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-DeuOZXeW.js +6 -0
- package/dist/devtools/browser-dev-host/assets/index-B-2wxdQX.js +567 -0
- package/dist/devtools/browser-dev-host/assets/index-ophYZqpX.css +1 -0
- package/dist/devtools/browser-dev-host/assets/linux-DwJAcUeD.svg +1 -0
- package/dist/devtools/browser-dev-host/index.html +6 -4
- package/dist/index.cjs.js +1030 -155
- package/dist/index.esm.js +1030 -155
- package/dist/miniapp-publish.cjs.js +1071 -130
- package/dist/miniapp-publish.esm.js +1071 -130
- package/dist/protocol.cjs.js +727 -158
- package/dist/protocol.esm.js +711 -159
- package/dist/templates/vanilla-vite-js/README.md.ejs +27 -0
- package/dist/templates/vanilla-vite-js/package.json.ejs +1 -1
- package/dist/templates/vanilla-vite-js/src/user-game-data.js.ejs +1 -0
- package/dist/vite.cjs.js +1076 -133
- package/dist/vite.esm.js +1076 -133
- package/package.json +6 -7
- package/skill/SKILL.md +4 -0
- package/skill/skill.json +5 -5
- package/types/index.d.ts +386 -9
- package/types/miniapp-publish/index.d.ts +18 -2
- package/types/protocol.d.ts +1 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-DVlT56iQ.js +0 -100
- package/dist/devtools/browser-dev-host/assets/desktop-app-launch-BzRxl_MM.js +0 -6
- package/dist/devtools/browser-dev-host/assets/index-CHYEXFEg.css +0 -1
- package/dist/devtools/browser-dev-host/assets/index-DY5ZynQp.js +0 -586
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import{m as Qm,H as wc,aV as Ym,bv as Wm,a2 as Zm,bc as Km,bd as Jm,n as ct,bF as q,b5 as al,l as cl,aH as Xm,e as Ec,aM as eh,ay as th,k as rh,aI as nh,bz as Qr,aT as gn,aS as Vs,aU as ni,aZ as dl,a$ as ih,f as wi,v as oh,al as Ei,Y as Ra,aL as sh,j as Gs,ap as qs,h as ah,b9 as ul,aD as ch,G as dh,aX as ll,S as uh,z as lh,aA as fh,y as mh,b6 as hh,bx as fl,bw as ml,b1 as gh,g as Qs,aC as ph,b as Wt,c as yh}from"./desktop-app-launch-DeuOZXeW.js";function wh(){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 Eh(){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 Bn={device:'[data-preview-target="device"]',screen:'[data-preview-target="screen"]',app:"#device iframe",workbench:'[data-testid="workbench-root"]'},Ic=15e3,Ih=32*1024*1024,_c="data-hb-preview-capture-device",Go="data-hb-preview-capture-ancestor",Ac="data-hb-preview-capture-surface",Dc=64,_h=1024;function Ah(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??Ic;if(!Number.isFinite(n)||n<=0||n>Ic)throw $e("INVALID_CAPTURE_LEASE","截图租约无效");let i;function o(d,u,f){d.attributes.push({element:u,name:f,previous:u.getAttribute(f)}),u.setAttribute(f,d.token)}function s(d){const u=i;if(!u||u.token!==d)return!1;const f=a(u),l=!!u.style?.isConnected;i=void 0,clearTimeout(u.timer),u.removeAbort?.(),u.removeResize?.(),u.observer?.disconnect(),u.style?.remove(),u.bounds?.remove();for(const{element:h,name:m,previous:g}of u.attributes)h.getAttribute(m)===d&&(g===null?h.removeAttribute(m):h.setAttribute(m,g));return u.overlay.remove(),l&&(r.scrollX!==u.scroll.x||r.scrollY!==u.scroll.y)&&r.scrollTo(u.scroll.x,u.scroll.y),f}function a(d){const{viewport:u,target:f,rect:l}=d;if(!f?.isConnected||!l||Date.now()>=d.expiresAt||r.innerWidth!==u.width||r.innerHeight!==u.height||r.devicePixelRatio!==u.devicePixelRatio)return!1;const h=f.getBoundingClientRect();return["left","top","width","height"].every(m=>Math.abs(h[m]-l[m])<.01)}async function c(d,u){if(u?.throwIfAborted(),!Number.isFinite(d.deadlineAt)||Date.now()>=d.deadlineAt)throw $e("PREVIEW_TIMEOUT","截图操作已超时");if(d.scope==="workbench"||!Object.hasOwn(Bn,d.scope))throw $e("INVALID_CAPTURE_SCOPE","设备像素截图仅支持 device、screen 或 app");if(!d.operationId||d.operationId.length>128)throw $e("INVALID_OPERATION","截图操作标识无效");if(!d.previewImage.startsWith("data:image/png;base64,")||d.previewImage.length>Ih)throw $e("INVALID_CAPTURE_IMAGE","共享窗口冻结图无效或过大");if(i)throw $e("PREVIEW_BUSY","已有设备截图正在执行");const f=t.querySelectorAll(Bn.device);if(f.length!==1)throw $e("DEVICE_NOT_UNIQUE","设备画面不唯一或尚未创建");const l=f[0],h=d.scope==="device"?l:t.querySelector(Bn[d.scope]);if(!h||h!==l&&!l.contains(h))throw $e("CAPTURE_TARGET_UNAVAILABLE","截图内容尚未创建");const m=l.getBoundingClientRect();if(!(m.width>0&&m.height>0))throw $e("CAPTURE_TARGET_UNAVAILABLE","设备画面当前不可见");const g=t.createElement("img");g.alt="",g.setAttribute("aria-hidden","true"),g.setAttribute("data-hb-preview-capture-freeze",""),g.style.cssText=`position:fixed;left:0;top:0;width:${r.innerWidth}px;height:${r.innerHeight}px;max-width:none;max-height:none;margin:0;border:0;padding:0;z-index:2147483647;pointer-events:auto;user-select:none;`,g.addEventListener("wheel",j=>j.preventDefault(),{passive:!1}),g.addEventListener("touchmove",j=>j.preventDefault(),{passive:!1});const I=Math.min(Date.now()+n,d.deadlineAt),E={operationId:d.operationId,token:r.crypto.randomUUID(),overlay:g,attributes:[],scroll:{x:r.scrollX,y:r.scrollY},viewport:{width:r.innerWidth,height:r.innerHeight,devicePixelRatio:r.devicePixelRatio},expiresAt:I};i=E,E.timer=setTimeout(()=>s(E.token),Math.max(0,I-Date.now()));const b=()=>s(E.token);u?.addEventListener("abort",b,{once:!0}),E.removeAbort=()=>u?.removeEventListener("abort",b);const y=()=>{const{viewport:j}=E;(r.innerWidth!==j.width||r.innerHeight!==j.height||r.devicePixelRatio!==j.devicePixelRatio)&&s(E.token)};r.addEventListener("resize",y),E.removeResize=()=>r.removeEventListener("resize",y);const v=()=>{if(u?.throwIfAborted(),i!==E||Date.now()>=I)throw $e("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{g.src=d.previewImage,await g.decode(),v();const j=E.token,A=`[${_c}="${j}"]`,D=r.getComputedStyle(l),_=new r.DOMMatrixReadOnly(D.transform==="none"?void 0:D.transform),T=Math.atan2(_.b,_.a),N=l.querySelector(".desktop-window__surface"),x=N?N.offsetWidth:Number.parseFloat(D.width),M=N?N.offsetHeight:Number.parseFloat(D.height),S=D.backgroundColor,O=r.getComputedStyle(t.body).backgroundColor,z=ye=>!ye||ye==="transparent"||ye==="rgba(0, 0, 0, 0)",U=z(S)?z(O)?"#fff":O:S;if(!(x>0&&M>0))throw $e("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");v(),t.body.append(g),o(E,l,_c),N&&o(E,N,Ac);for(let ye=l.parentElement;ye;ye=ye.parentElement)o(E,ye,Go);const L=t.createElement("style");E.style=L;const C=`
|
|
2
|
+
[${Go}="${j}"] {overflow:visible!important;scrollbar-width:none!important;}
|
|
3
|
+
[${Go}="${j}"]::-webkit-scrollbar {display:none!important;}
|
|
4
|
+
[${Ac}="${j}"] {transform:none!important;transition:none!important;}
|
|
5
|
+
`,H=(ye,Oe,Me=0,Re=0)=>`${A} {position:absolute!important;left:${ye}px!important;top:${Oe}px!important;width:${x}px!important;height:${M}px!important;transform:translate(${Me}px,${Re}px) rotate(${T}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${U}!important;}`;L.textContent=C+H(0,0),v(),t.head.append(L);const F=l.getBoundingClientRect(),G=t.querySelector(Bn.app),K=G&&l.contains(G)?G.getBoundingClientRect():void 0,p=K&&K.width>0&&K.height>0?K:void 0,R=p?Math.floor(r.innerWidth-1-(p.left-F.left)):r.innerWidth+64,B=p?Math.floor(r.innerHeight-1-(p.top-F.top)):32,Q=R-F.left,X=B-F.top;v(),L.textContent=C+H(Q,X);const ne=l.getBoundingClientRect();L.textContent=C+H(Q,X,R-ne.left,B-ne.top),v();const ie=h.getBoundingClientRect(),ue=Math.floor(lr(ie.left+r.scrollX)),we=Math.floor(lr(ie.top+r.scrollY)),he={x:ue,y:we,width:Math.ceil(lr(ie.right+r.scrollX))-ue,height:Math.ceil(lr(ie.bottom+r.scrollY))-we};if(!(he.width>0&&he.height>0)||he.x<0||he.y<0)throw $e("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(p&&G){const ye=G.getBoundingClientRect();if(!(ye.left<r.innerWidth&&ye.top<r.innerHeight&&ye.right>0&&ye.bottom>0))throw $e("CAPTURE_LAYOUT_INVALID","无法保持 iframe 的最小绘制区域");const Oe=l.getBoundingClientRect(),Me=Math.floor(lr(Oe.left))-1,Re=Math.floor(lr(Oe.top))-1,je=r.innerWidth-Me,$t=r.innerHeight-Re;if(Me<0||Re<0||je<=0||$t<=0||je>Dc||$t>Dc||je*$t>_h)throw $e("CAPTURE_LAYOUT_INVALID","无法在有界角部保持完整设备绘制,请改用 --scale css");g.style.clipPath=`polygon(0 0,100% 0,100% ${Re}px,${Me}px ${Re}px,${Me}px 100%,0 100%)`,g.setAttribute("data-hb-preview-capture-corner",JSON.stringify({x:Me,y:Re,width:je,height:$t}))}const ge=t.createElement("div");if(ge.setAttribute("aria-hidden","true"),ge.style.cssText=`position:absolute;left:${he.x+he.width+2}px;top:${he.y+he.height+2}px;width:1px;height:1px;pointer-events:none;opacity:0;`,E.bounds=ge,v(),t.body.append(ge),E.target=h,E.rect=ie,await Dh(r,u),v(),!a(E))throw $e("CAPTURE_LAYOUT_INVALID","截图准备期间布局发生变化,请重新截图");E.observer=new r.ResizeObserver(()=>{i===E&&!a(E)&&s(E.token)});for(const{element:ye}of E.attributes)E.observer.observe(ye);return{token:j,clip:he,devicePixelRatio:r.devicePixelRatio,expiresAt:I}}catch(j){throw s(E.token),j}}return{prepare:c,restore:s,cancel:d=>i?.operationId!==d?!1:(s(i.token),!0),dispose:()=>{i&&s(i.token)}}}function Dh(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 $e(e,t){return Object.assign(new Error(t),{name:"PreviewError",code:e})}function lr(e){const t=Math.round(e);return Math.abs(e-t)<.001?t:e}const Ca="user.games.getOverview",Ii="user.data.query",dn="user.data.sync",_i="user.data.file",La="user.dataPermission.request",Ua="user.dataPermission.get",xa="user.dataPermission.set",ja="user.dataPermission.openSettings",za="user.dataPermission.revokeSession",hl=[Ca,Ii,dn,_i,La,Ua,xa,ja,za],Ai="workspaceCards.requestRefresh",Di="auth.getAccountState",bi="auth.login",Mi="user.getFollowStatus",Si="user.requestFollowAuthor",bh="gameSaves.list",Mh="gameSaves.sync",Sh="gameSaves.getFile",Nh="gameSaves.readParsedData",Ni="user.getInfo",Ti="user.revokeAuthorization",vi="user.getSteamGameList",pn="user.showAppreciation",Oi="share.copyLink",ki="share.showShareMenu",Pi="share.screenshot",Ri="share.screenshotLong",nr="viewport.setDisplay",Ci="viewport.getWindowInfo",Li="viewport.setNavigationBarStyle",yn="storage.getStorage",wn="storage.setStorage",Ui="network.request",xi="network.download",ji="network.upload",zi="files.pickFiles",Bi="files.pickDirectory",Hi="files.saveFile",En="file.create",In="file.remove",Fi="file.exists",_n="file.readText",$i="file.writeText",An="file.readBytes",Vi="file.writeBytes",Dn="file.stat",Gi="directory.create",bn="directory.remove",qi="directory.exists",Qi="directory.list",Mn="media.pick",Yi="ui.showToast",Wi="ui.showLoading",Zi="ui.hideLoading",Ki="device.vibrate",Ji="device.setClipboard",Xi="device.executeProtocol",eo="navigation.close",to="navigation.reload",ro="navigation.openAppPage",Nt="cloud.leaderboard.submit",at="cloud.leaderboard.getList",jt="cloud.leaderboard.getCurrentUserEntry",ir="cloud.leaderboard.deleteCurrentUserEntry",It="cloud.leaderboard.getInfo",vr="cloud.storage.getStorage",Or="cloud.storage.setStorage",kr="cloud.storage.removeItem",or="cloud.storage.getKeys",wo="companion.getInfo",Eo="companion.getPreparationStatus",Io="companion.prepare",_o="companion.cancelPreparation",Ao="companion.getActiveSession",Do="companion.launch",bo="companion.session.write",Mo="companion.session.closeStdin",So="companion.session.terminate",No="companion.session.ackOutput",To="companion.openAttachment",vo="companion.showNotification",zt=[...[bh,Mh,Sh,Nh].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),...hl.map(e=>({method:e,module:"userGameData",capability:e,requirement:{kind:"all",permissions:["user_game_data"]},risk:"high"})),{method:Ai,module:"workspaceCards",capability:Ai,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:Di,module:"auth",capability:Di,requirement:{kind:"none"},risk:"low"},{method:bi,module:"auth",capability:bi,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Mi,module:"user",capability:Mi,requirement:{kind:"none"},risk:"low"},{method:Si,module:"user",capability:Si,requirement:{kind:"none"},risk:"high"},{method:Ni,module:"user",capability:Ni,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Ti,module:"user",capability:Ti,requirement:{kind:"none"},risk:"high"},{method:vi,module:"user",capability:vi,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:pn,module:"user",capability:pn,requirement:{kind:"none"},risk:"medium"},{method:Oi,module:"share",capability:Oi,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:ki,module:"share",capability:ki,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Pi,module:"share",capability:Pi,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Ri,module:"share",capability:Ri,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Ci,module:"viewport",capability:Ci,requirement:{kind:"none"},risk:"low"},{method:Li,module:"viewport",capability:Li,requirement:{kind:"none"},risk:"low"},{method:nr,module:"viewport",capability:nr,requirement:{kind:"none"},risk:"low"},{method:yn,module:"storage",capability:yn,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:wn,module:"storage",capability:wn,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Ui,module:"network",capability:Ui,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:xi,module:"network",capability:xi,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:ji,module:"network",capability:ji,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:zi,module:"files",capability:zi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Bi,module:"files",capability:Bi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Hi,module:"files",capability:Hi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:En,module:"file",capability:En,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:In,module:"file",capability:In,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Fi,module:"file",capability:Fi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_n,module:"file",capability:_n,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:$i,module:"file",capability:$i,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:An,module:"file",capability:An,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Vi,module:"file",capability:Vi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dn,module:"file",capability:Dn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Gi,module:"directory",capability:Gi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:bn,module:"directory",capability:bn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:qi,module:"directory",capability:qi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Qi,module:"directory",capability:Qi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mn,module:"media",capability:Mn,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:Yi,module:"ui",capability:Yi,requirement:{kind:"none"},risk:"low"},{method:Wi,module:"ui",capability:Wi,requirement:{kind:"none"},risk:"low"},{method:Zi,module:"ui",capability:Zi,requirement:{kind:"none"},risk:"low"},{method:Ki,module:"device",capability:Ki,requirement:{kind:"none"},risk:"low"},{method:Ji,module:"device",capability:Ji,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Xi,module:"device",capability:Xi,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:eo,module:"navigation",capability:eo,requirement:{kind:"none"},risk:"medium"},{method:to,module:"navigation",capability:to,requirement:{kind:"none"},risk:"medium"},{method:ro,module:"navigation",capability:ro,requirement:{kind:"none"},risk:"medium"},{method:Nt,module:"cloud",capability:Nt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:at,module:"cloud",capability:at,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:jt,module:"cloud",capability:jt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:ir,module:"cloud",capability:ir,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:It,module:"cloud",capability:It,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:vr,module:"cloud",capability:vr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:Or,module:"cloud",capability:Or,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:kr,module:"cloud",capability:kr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:or,module:"cloud",capability:or,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[wo,Eo,Io,_o,Ao,Do,bo,Mo,So,No,To,vo].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],qt="heybox:miniprogram",gl=2,pl="hb_mini_bridge_nonce",yl="sdk.handshake",Hn="runtime.location.probe",Th="sdk.location.report",vh="sdk.csp.violation",wl="operation.progress",Oh="companion.session.output",kh="companion.session.exit",Ph="companion.session.ownershipLost";function Rh(e){return!lt(e)||e.namespace!==qt||e.version!==1&&e.version!==2||!Pe(e.nonce)?!1:e.type==="handshake"?Pe(e.id)&&e.method===yl&&e.error===void 0&&Hh(e.payload):e.type==="request"?Pe(e.id)&&Pe(e.method)&&e.error===void 0:e.type==="response"?Pe(e.id)&&(e.method===void 0||Pe(e.method))&&(e.error===void 0||Fh(e.error)):e.type==="event"?!Pe(e.method)||e.error!==void 0?!1:e.method===wl?e.version===2&&Pe(e.id)&&Bh(e.payload):e.id===void 0||Pe(e.id):e.type==="cancel"?e.version===2&&Pe(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Ba(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function El(e){return lt(e)?e.kind==="sandbox"?rt(e,["kind"]):e.kind==="directory"&&Pe(e.handleId)&&rt(e,["kind","handleId"]):!1}function er(e){return!lt(e)||e.kind!=="file"?!1:Pe(e.handleId)?rt(e,["kind","handleId"]):El(e.root)&&Ba(e.relativePath)&&rt(e,["kind","root","relativePath"])}function Il(e){return!lt(e)||e.kind!=="directory"?!1:Pe(e.handleId)?rt(e,["kind","handleId"]):El(e.root)&&(e.relativePath==="."||Ba(e.relativePath))&&rt(e,["kind","root","relativePath"])}function Ch(e){return lt(e)&&e.kind==="file"&&Pe(e.name)&&$h(e.mode)&&er(e.ref)&&rt(e,["kind","name","mode","ref"])}const _l=20,bc=["type","mimeType","size","width","height","previewUrl","file"];function Lh(e){return e===void 0?!0:!(!lt(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&&(!Vh(e.maxCount,1,_l)||e.source==="camera"&&e.maxCount!==1))}function Al(e){if(!lt(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!rt(e,t?[...bc,"durationMs"]:bc)||!Pe(e.mimeType)||!Ct(e.size)||!Mc(e.width)||!Mc(e.height)||!Pe(e.previewUrl)||!xh(e.file)?!1:t?Ct(e.durationMs):!0}function Uh(e){if(!Array.isArray(e)||e.length<1||e.length>_l)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!Al(e[t]))return!1;return!0}function xh(e){return!Ch(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&Pe(e.ref.handleId)}function Dl(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function jh(e){return!lt(e)||!Ct(e.loaded)||typeof e.lengthComputable!="boolean"||!rt(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Ct(e.total)&&e.loaded<=e.total:e.total===void 0}function zh(e){return lt(e)?e.phase==="downloading"?Ct(e.loaded)&&(e.total===void 0||Ct(e.total)&&e.loaded<=e.total)&&rt(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Ct(e.processed)&&Ct(e.total)&&e.processed<=e.total&&rt(e,["phase","processed","total"]):!1}function Bh(e){return jh(e)||zh(e)}function Hh(e){return lt(e)&&Pe(e.href)&&typeof e.userAgent=="string"&&Pe(e.sdkVersion)}function Fh(e){return lt(e)&&Pe(e.code)&&typeof e.message=="string"}function $h(e){return e==="read"||e==="readwrite"}function Ct(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Mc(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Vh(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function Pe(e){return typeof e=="string"&&e.length>0}function rt(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const bl={ark:"明日方舟",black_myth_wukong:"黑神话悟空",task_bar_hero:"任务栏英雄",phantom_blade_zero:"影之刃零"},Ml=Object.keys(bl),tr=[{key:"game.ark.profile",game:"ark",family:"profile",name:"明日方舟角色与养成资料",disclosureRevision:1,queries:{get:{schema:"ark.profile",version:1}},sync:!1,file:!1},{key:"game.ark.gacha",game:"ark",family:"gacha",name:"明日方舟抽卡记录与分析",disclosureRevision:1,queries:{get:{schema:"ark.gacha-analysis",version:1},list:{schema:"ark.gacha-record-page",version:1,page:{defaultSize:50,maxSize:100}}},sync:!1,file:!1},{key:"game.black_myth_wukong.save_analysis",game:"black_myth_wukong",family:"save_analysis",name:"黑神话悟空存档解析结果",disclosureRevision:1,queries:{get:{schema:"black_myth_wukong.save",version:1}},sync:!0,file:!1},{key:"game.black_myth_wukong.save_files",game:"black_myth_wukong",family:"save_files",name:"黑神话悟空云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.task_bar_hero.save_analysis",game:"task_bar_hero",family:"save_analysis",name:"任务栏英雄存档解析结果",disclosureRevision:1,queries:{get:{schema:"task_bar_hero.save",version:1}},sync:!0,file:!1},{key:"game.task_bar_hero.save_files",game:"task_bar_hero",family:"save_files",name:"任务栏英雄云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.phantom_blade_zero.save_analysis",game:"phantom_blade_zero",family:"save_analysis",name:"影之刃零存档解析结果",disclosureRevision:1,queries:{get:{schema:"phantom_blade_zero.save",version:1}},sync:!0,file:!1},{key:"game.phantom_blade_zero.save_files",game:"phantom_blade_zero",family:"save_files",name:"影之刃零云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0}],Lt=tr.map(e=>e.key),Gh=new Set(Lt),qh=new Set(Ml);function Rt(e){return Gh.has(e)}function Sc(e){return qh.has(e)}function Oo(e){const t=tr.find(i=>i.key===e);if(!t)return;const r=t.queries,n=Object.keys(r);return t.sync&&n.push("sync"),t.file&&n.push("file"),{key:t.key,game:t.game,name:t.name,family:t.family,disclosureRevision:t.disclosureRevision,queries:r,operations:n}}const Qh="同步时,原始存档将上传至小黑盒;向小程序提供原始文件仍需单独许可。",sr=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards","user_game_data"],Ha=[{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:Lt,description:"精确资源声明对象;每项必须填写 1~30 个 Unicode 码点的 purpose,不接受通配符或未开放资源。"}},methods:hl,conditions:["逐项声明资源与用途,读取前需用户许可;未取得许可不查询个人来源。","文件与解析结果分别许可;本次许可仅当前实例有效,持久许可保存在本机。","同步会将原存档上传至小黑盒,向小程序交付原文件仍需 `save_files` 许可。","平台取数不授予小程序 `network` 权限;已交付的数据副本无法撤回。"]}];new Set(sr);const Yh=30;function Wh(e){if(typeof e!="string")throw new Error("purpose 必须是字符串");const t=e.trim(),r=Array.from(t);if(r.length<1||r.length>Yh)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 Sn(e){return Sl(e,!1)}function Zh(e){return Sl(e,!0)}function Sl(e,t){if(!Nc(e))throw new Error("resources 必须是资源声明对象;每项资源必须填写 purpose");const r={};for(const n of Object.keys(e).sort()){const i=e[n];if(!Nc(i)||Object.keys(i).length!==1||!Object.prototype.hasOwnProperty.call(i,"purpose"))throw new Error(`resources.${n} 必须且只能包含 purpose`);let o;try{o=Wh(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 Kh(e){return Lt.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function Nc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nl(e,t,r,n){return JSON.stringify(["user-game-data-purpose-v1",e,t,r,n])}const Jh=new Set(sr);function Xh(e){return Jh.has(e)}function qe(e){if(!Yr(e)||e.schema_version!==1||!Array.isArray(e.entries))return{valid:!1,permissions:{}};if(e.revision!==void 0&&(typeof e.revision!="number"||!Number.isInteger(e.revision)||e.revision<0))return{valid:!1,permissions:{}};const t=new Set,r={};for(const n of e.entries){if(!Yr(n)||typeof n.key!="string"||!n.key.trim())return{valid:!1,permissions:{}};const i=n.key.trim(),o=i==="network.request"?"network":i;if(t.has(o)||n.status!=="enabled"&&n.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(o),!!Xh(o)){if(o==="network"){const s=n.config;if(!Yr(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(o==="user_game_data"){const s=n.config;if(!Yr(s))return{valid:!1,permissions:{}};try{const a=Zh(s.resources);r[o]={key:o,status:n.status,config:{resources:a}}}catch{return{valid:!1,permissions:{}}}continue}if(n.config!==null&&n.config!==void 0&&(!Yr(n.config)||Object.keys(n.config).length>0))return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{}}}}return{valid:!0,permissions:r}}function Yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const ii=["network","companion","appProtocol"];function Tl(e){if(!Wr(e,["schema_version","revision","entries"])||e.schema_version!==1||typeof e.revision!="number"||!Number.isSafeInteger(e.revision)||e.revision<0||!Array.isArray(e.entries)||e.entries.length>ii.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Wr(n,["key","status","config"])||n.status!=="enabled")return{valid:!1};if(typeof n.key!="string"||r.has(n.key))return{valid:!1};if(r.add(n.key),n.key==="network"){if(!Wr(n.config,["useOfficialDomain"])||n.config.useOfficialDomain!==!1)return{valid:!1};t.push({key:"network",status:"enabled",config:{useOfficialDomain:!1}})}else if(n.key==="companion"){if(!Wr(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Wr(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>ii.indexOf(n.key)-ii.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function eg(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 ii)!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 Fa(e){const t=qe(e.runtimePermissions),r=Tl(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of sr)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:Ha.some(a=>a.key===s&&a.access==="declaration")?n[s]={key:s,status:"enabled",config:tg(s,e.declaredPermissions)}:s==="network"&&n.network&&(n.network.config.useOfficialDomain=n.network.status==="enabled"&&n.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(r.valid)for(const s of r.grant.entries)e.declaredPermissions[s.key]?.enabled!==!0||n[s.key]?.status==="enabled"||(n[s.key]=s,i.push(s.key));const o=vl(e.runtimePermissions)&&typeof e.runtimePermissions.revision=="number"&&Number.isSafeInteger(e.runtimePermissions.revision)&&e.runtimePermissions.revision>=0?e.runtimePermissions.revision:void 0;return{runtimePermissions:{schema_version:1,...o===void 0?{}:{revision:o},entries:sr.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function tg(e,t){const r=Ha.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"?Sn(t[e]?.resources):{});return n}function vl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wr(e,t){return vl(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Pr=["identity","profile","steam_account"],rg=/^[a-z][a-z0-9-]{0,31}$/,Ol=["COMPANION_UNSUPPORTED","COMPANION_PREVIEW_UNSUPPORTED","COMPANION_NOT_DECLARED","COMPANION_TARGET_UNSUPPORTED","COMPANION_NOT_PREPARED","COMPANION_PREPARATION_CANCELLED","COMPANION_DOWNLOAD_FAILED","COMPANION_DESCRIPTOR_UNAVAILABLE","COMPANION_ARCHIVE_INVALID","COMPANION_INTEGRITY_FAILED","COMPANION_ENTRYPOINT_INVALID","COMPANION_USER_CANCELLED","COMPANION_ELEVATION_DENIED","COMPANION_OS_BLOCKED","COMPANION_LAUNCH_FAILED","COMPANION_SESSION_VERSION_MISMATCH","COMPANION_SESSION_OWNERSHIP_LOST","COMPANION_SESSION_EXITED","COMPANION_PIPE_CLOSED","COMPANION_OUTPUT_LIMIT","COMPANION_PROCESS_CRASHED","COMPANION_ATTACHMENT_NOT_FOUND","COMPANION_NOTIFICATION_UNAVAILABLE","COMPANION_TERMINATE_FAILED"];var Tc;function Ae(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 un extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(Tc=globalThis).__zod_globalConfig??(Tc.__zod_globalConfig={});const vc=globalThis.__zod_globalConfig;function Vr(e){return e&&Object.assign(vc,e),vc}function ng(e,t){return typeof t=="bigint"?t.toString():t}function ig(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function kl(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 Pl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function og(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sg(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 ag(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const cg={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 on(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 dg(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 Rl(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Fn(e){return typeof e=="string"?e:e?.message}function Rn(e,t,r){const n=e.message?e.message:Fn(e.inst?._zod.def?.error?.(e))??Fn(t?.error?.(e))??Fn(r.customError?.(e))??Fn(r.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}const Cl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ng,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ug=Ae("$ZodError",Cl),ko=Ae("$ZodError",Cl,{Parent:Error}),lg=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 un;if(s.issues.length){const a=new(i?.Err??e)(s.issues.map(c=>Rn(c,o,Vr())));throw Pl(a,i?.callee),a}return s.value},fg=lg(ko),mg=e=>async(t,r,n,i)=>{const o=n?{...n,async:!0}:{async:!0};let s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(i?.Err??e)(s.issues.map(c=>Rn(c,o,Vr())));throw Pl(a,i?.callee),a}return s.value},hg=mg(ko),gg=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 un;return o.issues.length?{success:!1,error:new(e??ug)(o.issues.map(s=>Rn(s,i,Vr())))}:{success:!0,data:o.value}},Ll=gg(ko),pg=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=>Rn(s,i,Vr())))}:{success:!0,data:o.value}},Ul=pg(ko),yg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},wg=/^-?\d+$/,Eg=/^-?\d+(?:\.\d+)?$/,Ig=/^null$/i,Po=Ae("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),xl={number:"number",bigint:"bigint",object:"date"},_g=Ae("$ZodCheckLessThan",(e,t)=>{Po.init(e,t);const r=xl[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ag=Ae("$ZodCheckGreaterThan",(e,t)=>{Po.init(e,t);const r=xl[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Dg=Ae("$ZodCheckNumberFormat",(e,t)=>{Po.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,o]=cg[t.format];e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,a.minimum=i,a.maximum=o,r&&(a.pattern=wg)}),e._zod.check=s=>{const a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),bg=Ae("$ZodCheckStringFormat",(e,t)=>{var r,n;Po.init(e,t),e._zod.onattach.push(i=>{const o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Mg=Ae("$ZodCheckRegex",(e,t)=>{bg.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})}}),Sg={major:4,minor:4,patch:3},ft=Ae("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Sg;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=on(s),u;for(const f of a){if(f._zod.def.when){if(dg(s)||!f._zod.def.when(s))continue}else if(d)continue;const l=s.issues.length,h=f._zod.check(s);if(h instanceof Promise&&c?.async===!1)throw new un;if(u||h instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await h,s.issues.length!==l&&(d||(d=on(s,l)))});else{if(s.issues.length===l)continue;d||(d=on(s,l))}}return u?u.then(()=>s):s},o=(s,a,c)=>{if(on(s))return s.aborted=!0,s;const d=i(a,n,c);if(d instanceof Promise){if(c.async===!1)throw new un;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 un;return c.then(d=>i(d,n,a))}return i(c,n,a)}}Qe(e,"~standard",()=>({validate:i=>{try{const o=Ll(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Ul(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Ng=Ae("$ZodString",(e,t)=>{ft.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??yg(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}}),jl=Ae("$ZodNumber",(e,t)=>{ft.init(e,t),e._zod.pattern=e._zod.bag.pattern??Eg,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}}),Tg=Ae("$ZodNumberFormat",(e,t)=>{Dg.init(e,t),jl.init(e,t)}),vg=Ae("$ZodNull",(e,t)=>{ft.init(e,t),e._zod.pattern=Ig,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}}),Og=Ae("$ZodNever",(e,t)=>{ft.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Pc(e,t,r){e.issues.length&&t.issues.push(...Rl(r,e.issues)),t.value[r]=e.value}const kg=Ae("$ZodArray",(e,t)=>{ft.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const o=[];for(let s=0;s<i.length;s++){const a=i[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(d=>Pc(d,r,s))):Pc(c,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function no(e,t,r,n,i,o){const s=r in n;if(e.issues.length){if(i&&o&&!s)return;t.issues.push(...Rl(r,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?s&&(t.value[r]=void 0):t.value[r]=e.value}function Pg(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=ag(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Rg(e,t,r,n,i,o){const s=[],a=i.keySet,c=i.catchall._zod,d=c.def.type,u=c.optin==="optional",f=c.optout==="optional";for(const l in t){if(l==="__proto__"||a.has(l))continue;if(d==="never"){s.push(l);continue}const h=c.run({value:t[l],issues:[]},n);h instanceof Promise?e.push(h.then(m=>no(m,r,l,t,u,f))):no(h,r,l,t,u,f)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>r):r}const Cg=Ae("$ZodObject",(e,t)=>{if(ft.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=ig(()=>Pg(t));Qe(e._zod,"propValues",()=>{const a=t.shape,c={};for(const d in a){const u=a[d]._zod;if(u.values){c[d]??(c[d]=new Set);for(const f of u.values)c[d].add(f)}}return c});const i=og,o=t.catchall;let s;e._zod.parse=(a,c)=>{s??(s=n.value);const d=a.value;if(!i(d))return a.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),a;a.value={};const u=[],f=s.shape;for(const l of s.keys){const h=f[l],m=h._zod.optin==="optional",g=h._zod.optout==="optional",I=h._zod.run({value:d[l],issues:[]},c);I instanceof Promise?u.push(I.then(E=>no(E,a,l,d,m,g))):no(I,a,l,d,m,g)}return o?Rg(u,d,a,c,n.value,e):u.length?Promise.all(u).then(()=>a):a}});function Rc(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=>!on(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=>Rn(s,n,Vr())))}),t)}const Lg=Ae("$ZodUnion",(e,t)=>{ft.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=>kl(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=>Rc(a,n,e,i)):Rc(s,n,e,i)}}),Ug=Ae("$ZodLiteral",(e,t)=>{if(ft.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?kc(n):n?kc(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,i)=>{const o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}});function Cc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const xg=Ae("$ZodOptional",(e,t)=>{ft.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(`^(${kl(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=>Cc(s,i)):Cc(o,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),jg=Ae("$ZodLazy",(e,t)=>{ft.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 zg(e,t){return new e({type:"string",...it()})}function Bg(e,t){return new e({type:"number",checks:[],...it()})}function Hg(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...it()})}function Fg(e,t){return new e({type:"null",...it()})}function $g(e,t){return new e({type:"never",...it()})}function se(e,t){return new _g({check:"less_than",...it(),value:e,inclusive:!0})}function ae(e,t){return new Ag({check:"greater_than",...it(),value:e,inclusive:!0})}function ce(e,t){return new Mg({check:"string_format",format:"regex",...it(),pattern:e})}Vr({jitless:!0});function Vg(e){if(e.schema_version!==1||!/^[a-f0-9]{32}$/.test(e.session_id)||!Number.isSafeInteger(e.revision)||e.revision<1||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(e.sdk_version)||!e.declared_permissions||typeof e.declared_permissions!="object"||Array.isArray(e.declared_permissions)||!Array.isArray(e.platforms)||e.platforms.some(r=>!["android","ios","ohos","windows","macos","linux"].includes(r))||new Set(e.platforms).size!==e.platforms.length)throw new Error("开发快照无效");const t={};for(const r of sr){const n=e.declared_permissions[r];if(n){if(typeof n.enabled!="boolean")throw new Error("开发权限声明无效");if(r==="network"){t[r]={enabled:n.enabled,useOfficialDomain:n.useOfficialDomain===!0};continue}if(r==="user_game_data"){t[r]={enabled:n.enabled,resources:Sn(n.resources)};continue}t[r]={enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!sr.includes(r)))throw new Error("开发权限声明无效");if(e.companion_manifest_sha256!==void 0&&!/^[a-f0-9]{64}$/.test(e.companion_manifest_sha256))throw new Error("开发产物摘要无效");return JSON.stringify({schema_version:1,session_id:e.session_id,revision:e.revision,sdk_version:e.sdk_version,declared_permissions:t,platforms:[...e.platforms].sort(),...e.companion_manifest_sha256?{companion_manifest_sha256:e.companion_manifest_sha256}:{}})}function Gg(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return Vg(t)===e?t:void 0}catch{return}}const Lc={$defs:{ArkProfile:{type:"object",properties:{uid:{type:"string"},name:{type:"string"},level:{type:"number"},avatar:{$ref:"#/$defs/ArkPlayerAvatar"},characterCount:{type:"number"},totalCharacterCount:{type:"number"},mainStageProgress:{type:"string"},rogueLevel:{type:"number"},campaignFullKillCount:{type:"number"},tag:{type:"string"},observedAt:{anyOf:[{type:"string"},{type:"number"}]},lastOnlineTs:{anyOf:[{type:"string"},{type:"number"}]},registerTs:{anyOf:[{type:"string"},{type:"number"}]},changeTime:{anyOf:[{type:"string"},{type:"number"}]},operators:{type:"array",items:{$ref:"#/$defs/ArkOperator"}}},required:["uid","name","level","characterCount","totalCharacterCount","mainStageProgress","rogueLevel","campaignFullKillCount","tag"],additionalProperties:!1},ArkPlayerAvatar:{type:"object",properties:{url:{type:"string"},type:{type:"string"},id:{type:"string"}},required:["url","type","id"],additionalProperties:!1},ArkOperator:{type:"object",properties:{characterId:{type:"string"},name:{type:"string"},profession:{type:"string"},evolvePhase:{type:"number"},potentialRank:{type:"number"}},required:["characterId","name","profession","evolvePhase","potentialRank"],additionalProperties:!1},ArkGachaAnalysis:{type:"object",properties:{uid:{type:"string"},year:{type:"number"},total:{type:"number"},srCount:{type:"number"},upCount:{type:"number"},missCount:{type:"number"},careerEvaluation:{type:"string"},careerIsLucky:{anyOf:[{const:!1},{const:!0}]},pools:{type:"array",items:{$ref:"#/$defs/ArkGachaPoolStat"}},records:{type:"array",items:{$ref:"#/$defs/ArkGachaAnalysisRecord"}},luckyLottery:{type:"array",items:{type:"number"}}},required:["uid","year","total","srCount","upCount","missCount","careerEvaluation","careerIsLucky","pools","records","luckyLottery"],additionalProperties:!1},ArkGachaPoolStat:{type:"object",properties:{poolId:{type:"string"},totalCost:{type:"number"},ssrCount:{type:"number"},ssrCost:{type:"number"},records:{type:"array",items:{$ref:"#/$defs/ArkGachaAnalysisRecord"}}},required:["poolId","totalCost","ssrCount","ssrCost","records"],additionalProperties:!1},ArkGachaAnalysisRecord:{type:"object",properties:{name:{type:"string"},timestamp:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},diff:{type:"number"},negativeDiff:{type:"number"},tag:{type:"string"},missUp:{anyOf:[{const:!1},{const:!0}]}},required:["name","timestamp","diff","negativeDiff","tag","missUp"],additionalProperties:!1},GachaRecord:{type:"object",properties:{id:{type:"string"},name:{type:"string"},pool:{type:"string"},rarity:{type:"number"},timestamp:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["id","name","pool","rarity","timestamp"],additionalProperties:!1},BlackMythWukongSave:{type:"object",properties:{level:{type:"number"},newGamePlusCount:{type:"number"},gameTotalTime:{type:"number"},playerDeathCount:{type:"number"},totalMoney:{type:"string"},meditationList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},monsterCollectionList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},returnPointList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},activatedWeaponIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},activatedEquipIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},magicArtifactList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},soulSkillIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},huluIdLits:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},wineIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},wineIdPartnerList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},cropIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},recipeIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},wearedWaeponId:{type:"string"},wearedMagicArtifact:{type:"number"},wearedSoulSkill:{type:"number"},wearedHead:{type:"number"},wearedUpware:{type:"number"},wearedArm:{type:"number"},wearedFoot:{type:"number"},wearedHulu:{type:"number"},wearedAccessoryList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},spellQishu:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},spellShenfa:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},spellHaomao:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},spellBianshen:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},bossRushBossgroup:{$ref:"#/$defs/BlackMythWukongBossRushData"},bossRushRefight:{$ref:"#/$defs/BlackMythWukongBossRefightData"}},required:[],additionalProperties:!1},BlackMythWukongBossRushData:{type:"object",properties:{bossGroups:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongBossRushRecord"}}]}},required:[],additionalProperties:!1},BlackMythWukongBossRushRecord:{type:"object",properties:{bossGroupId:{type:"number"},isPassed:{anyOf:[{const:!1},{const:!0}]},bestRecords:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongBattleRecord"}}]},encounterBossIndex:{type:"number"},battleCount:{type:"number"}},required:[],additionalProperties:!1},BlackMythWukongBattleRecord:{type:"object",properties:{battleId:{type:"string"},battleData:{$ref:"#/$defs/BlackMythWukongBattleData"}},required:[],additionalProperties:!1},BlackMythWukongBattleData:{type:"object",properties:{totalTime:{type:"number"},score:{type:"number"},debuffList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},targetId:{type:"number"},archiveTime:{type:"string"},roleBase:{$ref:"#/$defs/BlackMythWukongRoleBase"},battleStyleInfo:{$ref:"#/$defs/BlackMythWukongBattleStyleInfo"},damageInfo:{$ref:"#/$defs/BlackMythWukongDamageInfo"}},required:[],additionalProperties:!1},BlackMythWukongRoleBase:{type:"object",properties:{level:{type:"number"},atk:{type:"number"},hpMax:{type:"number"},staminaMax:{type:"number"},mpMax:{type:"number"}},required:[],additionalProperties:!1},BlackMythWukongBattleStyleInfo:{type:"object",properties:{spellList:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongCast"}}]},fabaoInfo:{$ref:"#/$defs/BlackMythWukongCast"},soulInfo:{$ref:"#/$defs/BlackMythWukongCast"},itemCount:{type:"number"},wineCount:{type:"number"},rollCount:{type:"number"},defuseCount:{type:"number"},fourPeCount:{type:"number"}},required:[],additionalProperties:!1},BlackMythWukongCast:{type:"object",properties:{castId:{type:"number"},castCount:{type:"number"}},required:[],additionalProperties:!1},BlackMythWukongDamageInfo:{type:"object",properties:{totalDamage:{anyOf:[{type:"string"},{type:"number"}]},hightestDamage:{anyOf:[{type:"string"},{type:"number"}]},criticalDmgRate:{type:"number"},totalBeDamaged:{anyOf:[{type:"string"},{type:"number"}]},criticalDmgTotal:{anyOf:[{type:"string"},{type:"number"}]},elemDotDmgTotal:{anyOf:[{type:"string"},{type:"number"}]},elemDotDmgRate:{type:"number"}},required:[],additionalProperties:!1},BlackMythWukongBossRefightData:{type:"object",properties:{bossList:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongBossRefightRecord"}}]}},required:[],additionalProperties:!1},BlackMythWukongBossRefightRecord:{type:"object",properties:{bossId:{type:"number"},passedMaxLevel:{type:"number"},lastChallengeLevel:{type:"number"},bestRecords:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongBattleRecord"}}]},refightStatisticsList:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongRefightStatistic"}}]}},required:[],additionalProperties:!1},BlackMythWukongRefightStatistic:{type:"object",properties:{challengeLevel:{type:"number"},battleCount:{type:"number"}},required:[],additionalProperties:!1},TaskBarHeroSave:{type:"object",properties:{update_time:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},game_version:{type:"string"},account_version:{type:"string"},play_time:{type:"number"},last_saved_time:{type:"string"},common:{$ref:"#/$defs/TaskBarHeroCommon"},summary:{$ref:"#/$defs/TaskBarHeroSummary"},heroes:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroHero"}}]},rune_save_data:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroRune"}}]},pets:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroPet"}}]},attributes:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroAttribute"}}]},inventory_slots:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroItemSlot"}}]},stash_slots:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroItemSlot"}}]},item_instances:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroItemInstance"}}]},values:{$ref:"#/$defs/TaskBarHeroValueSummary"}},required:["update_time","game_version","account_version","play_time","last_saved_time","common","summary","heroes","rune_save_data","pets","attributes","inventory_slots","stash_slots","item_instances","values"],additionalProperties:!1},TaskBarHeroCommon:{type:"object",properties:{max_completed_stage:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},current_stage_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},current_stage_wave:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},arranged_hero_keys:{anyOf:[{type:"null"},{type:"array",items:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}}]},arranged_pet_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["max_completed_stage","current_stage_key","current_stage_wave","arranged_hero_keys","arranged_pet_key"],additionalProperties:!1},TaskBarHeroSummary:{type:"object",properties:{max_hero_level:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},learned_rune_count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},unlocked_hero:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},total_hero:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},item_count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},inventory_slots:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},stash_slots:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["max_hero_level","learned_rune_count","unlocked_hero","total_hero","item_count","inventory_slots","stash_slots"],additionalProperties:!1},TaskBarHeroHero:{type:"object",properties:{hero_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},hero_level:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},is_unlock:{anyOf:[{const:!1},{const:!0}]},hero_exp:{type:"number"},ability_point:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},allocated_hero_ability_point:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},equipped_item_ids:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},equipped_skill_keys:{anyOf:[{type:"null"},{type:"array",items:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}}]},unlocked_attribute_group_keys:{anyOf:[{type:"null"},{type:"array",items:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}}]}},required:["hero_key","hero_level","is_unlock","hero_exp","ability_point","allocated_hero_ability_point","equipped_item_ids","equipped_skill_keys","unlocked_attribute_group_keys"],additionalProperties:!1},TaskBarHeroRune:{type:"object",properties:{rune_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},level:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["rune_key","level"],additionalProperties:!1},TaskBarHeroPet:{type:"object",properties:{pet_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},is_unlock:{anyOf:[{const:!1},{const:!0}]}},required:["pet_key","is_unlock"],additionalProperties:!1},TaskBarHeroAttribute:{type:"object",properties:{key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},level:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["key","level"],additionalProperties:!1},TaskBarHeroItemSlot:{type:"object",properties:{index:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},item_unique_id:{type:"string"},is_unlock:{anyOf:[{const:!1},{const:!0}]},is_unlocked_by_rune:{anyOf:[{const:!1},{const:!0}]}},required:["index","item_unique_id","is_unlock","is_unlocked_by_rune"],additionalProperties:!1},TaskBarHeroItemInstance:{type:"object",properties:{item_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},unique_id:{type:"string"},is_chaotic:{anyOf:[{const:!1},{const:!0}]},is_blocked:{anyOf:[{const:!1},{const:!0}]},is_server_pending_item:{anyOf:[{const:!1},{const:!0}]},enchant_count:{anyOf:[{type:"null"},{type:"array",items:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}}]},enchant_data:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroEnchantData"}}]},item_get_source_type:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},decoration_applied_total_count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},engraving_applied_total_count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},inscription_applied_total_count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["item_key","unique_id","is_chaotic","is_blocked","is_server_pending_item","enchant_count","enchant_data","item_get_source_type","decoration_applied_total_count","engraving_applied_total_count","inscription_applied_total_count"],additionalProperties:!1},TaskBarHeroEnchantData:{type:"object",properties:{stat_mod_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},tier:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},value:{type:"number"},recipe_type:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},mod_type:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},material_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},stat_type:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["stat_mod_key","tier","value","recipe_type","mod_type","material_key","stat_type"],additionalProperties:!1},TaskBarHeroValueSummary:{type:"object",properties:{market_value:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},price_state:{type:"string"},currency:{type:"string"}},required:["market_value","price_state","currency"],additionalProperties:!1},PhantomBladeZeroSave:{type:"object",properties:{defaultSlot:{type:"string"},slots:{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroSaveSlot"}}},required:["defaultSlot","slots"],additionalProperties:!1},PhantomBladeZeroSaveSlot:{type:"object",properties:{slot:{type:"string"},head:{$ref:"#/$defs/PhantomBladeZeroSlotHead"},firstClear:{$ref:"#/$defs/PhantomBladeZeroSlotFirstClear"},progress:{$ref:"#/$defs/PhantomBladeZeroSlotProgress"},combat:{$ref:"#/$defs/PhantomBladeZeroSlotCombat"},achievements:{$ref:"#/$defs/PhantomBladeZeroSlotAchievementSummary"},bosses:{$ref:"#/$defs/PhantomBladeZeroSlotBossSummary"},collectibles:{$ref:"#/$defs/PhantomBladeZeroSlotCollectibles"},quest_details:{anyOf:[{type:"null"},{$ref:"#/$defs/PhantomBladeZeroQuestDetails"}]},inventory_details:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroInventoryItem"}}]},detail:{$ref:"#/$defs/PhantomBladeZeroSlotDetail"}},required:["slot","head","firstClear","progress","combat","achievements","bosses","collectibles","quest_details","inventory_details","detail"],additionalProperties:!1},PhantomBladeZeroSlotHead:{type:"object",properties:{saveTime:{type:"string"},currentLevel:{type:"string"},cycle:{type:"string"},difficulty:{$ref:"#/$defs/PhantomBladeZeroSlotDifficulty"}},required:["saveTime","currentLevel","cycle","difficulty"],additionalProperties:!1},PhantomBladeZeroSlotDifficulty:{type:"object",properties:{raw:{type:"number"},name:{type:"string"}},required:["raw","name"],additionalProperties:!1},PhantomBladeZeroSlotFirstClear:{type:"object",properties:{clearDate:{$ref:"#/$defs/PhantomBladeZeroUnavailableValue"},cycles:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroClearanceRecord"}}]}},required:["clearDate","cycles"],additionalProperties:!1},PhantomBladeZeroUnavailableValue:{type:"object",properties:{value:{type:"null"},reason:{type:"string"}},required:["value","reason"],additionalProperties:!1},PhantomBladeZeroClearanceRecord:{type:"object",properties:{Cycle:{anyOf:[{type:"null"},{type:"number"}]},Ending:{type:"number"},Difficulty:{type:"number"},GameTime:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},Completion:{type:"number"},DiedTimes:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["Ending","Difficulty","GameTime","Completion","DiedTimes"],additionalProperties:!1},PhantomBladeZeroSlotProgress:{type:"object",properties:{playTimeSeconds:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},playTime:{type:"string"},lastLaunch:{$ref:"#/$defs/PhantomBladeZeroUnavailableValue"},narrativePercentage:{type:"number"},chapter:{type:"string"},remainingDays:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["playTimeSeconds","playTime","lastLaunch","narrativePercentage","chapter","remainingDays"],additionalProperties:!1},PhantomBladeZeroSlotCombat:{type:"object",properties:{loadout:{$ref:"#/$defs/PhantomBladeZeroSlotLoadout"},totalDeaths:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},cycleDeaths:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},bossKillTotal:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},currentMainWeapon:{anyOf:[{type:"null"},{$ref:"#/$defs/PhantomBladeZeroNamedItem"}]},mainWeapon:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},currentShaqi:{anyOf:[{type:"null"},{$ref:"#/$defs/PhantomBladeZeroNamedItem"}]},shaqi:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"}},required:["totalDeaths","cycleDeaths","bossKillTotal","mainWeapon","shaqi"],additionalProperties:!1},PhantomBladeZeroSlotLoadout:{type:"object",properties:{states:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroLoadoutState"}}]},main_weapons:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},shaqi_weapons:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},accessory_ids:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},top_medicine:{type:"string"},bottom_medicine:{type:"string"},current_weapon_index:{type:"number"},current_shaqi_weapon_index:{type:"number"}},required:["main_weapons","shaqi_weapons","accessory_ids","top_medicine","bottom_medicine","current_weapon_index","current_shaqi_weapon_index"],additionalProperties:!1},PhantomBladeZeroLoadoutState:{type:"object",properties:{category:{type:"string"},id:{type:"string"},level:{type:"number"},soul_forged:{anyOf:[{const:!1},{const:!0}]},reincarnation_count:{type:"number"}},required:["category","id"],additionalProperties:!1},PhantomBladeZeroNamedItem:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},required:["id","name"],additionalProperties:!1},PhantomBladeZeroCollectionCount:{type:"object",properties:{unknown:{anyOf:[{type:"string"},{type:"number"}]},done:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},total:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["done","total"],additionalProperties:!1},PhantomBladeZeroSlotAchievementSummary:{type:"object",properties:{unlocked:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},total:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},reason:{type:"string"}},required:["unlocked","total","reason"],additionalProperties:!1},PhantomBladeZeroSlotBossSummary:{type:"object",properties:{groups:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroBossGroup"}}]}},required:["groups"],additionalProperties:!1},PhantomBladeZeroBossGroup:{type:"object",properties:{map:{type:"string"},mapName:{type:"string"},count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},bosses:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroBoss"}}]}},required:["map","mapName","count","bosses"],additionalProperties:!1},PhantomBladeZeroBoss:{type:"object",properties:{id:{type:"string"},classPath:{type:"string"},map:{type:"string"},mapName:{type:"string"},encountered:{anyOf:[{const:!1},{const:!0}]},killed:{anyOf:[{const:!1},{const:!0}]},kill:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},attempt:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},bestTimeMs:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},records:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroBossRecord"}}]}},required:["id","classPath","map","mapName","encountered","killed","kill","attempt","bestTimeMs","records"],additionalProperties:!1},PhantomBladeZeroBossRecord:{type:"object",properties:{cycle:{type:"string"},diff:{type:"string"},diffName:{type:"string"},kill:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},attempt:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},bestTimeMs:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["cycle","diff","diffName","kill","attempt","bestTimeMs"],additionalProperties:!1},PhantomBladeZeroSlotCollectibles:{type:"object",properties:{overall:{$ref:"#/$defs/PhantomBladeZeroCollectionSummary"},craneBellCount:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},byBigMap:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroBigMapProgress"}}]},currentChapter:{$ref:"#/$defs/PhantomBladeZeroChapterProgress"}},required:["overall","craneBellCount","byBigMap","currentChapter"],additionalProperties:!1},PhantomBladeZeroCollectionSummary:{type:"object",properties:{bell:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},weapon:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},shaqi:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},accessory:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},medicine:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},challenge:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},hupo:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},heishi:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},flower:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"}},required:["bell","weapon","shaqi","accessory","medicine","challenge","hupo","heishi","flower"],additionalProperties:!1},PhantomBladeZeroBigMapProgress:{type:"object",properties:{unknown:{anyOf:[{type:"string"},{type:"number"}]},mapID:{type:"string"},name:{type:"string"},pct:{type:"number"},done:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},total:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},subMaps:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]}},required:["mapID","name","pct","done","total","subMaps"],additionalProperties:!1},PhantomBladeZeroChapterProgress:{type:"object",properties:{unknown:{anyOf:[{type:"string"},{type:"number"}]},mapID:{type:"string"},pct:{type:"number"},done:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},total:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},reason:{type:"string"}},required:["mapID","pct","done","total","reason"],additionalProperties:!1},PhantomBladeZeroQuestDetails:{type:"object",properties:{CurrentMainQuestPath:{type:"string"},CurrentTutorialQuestPath:{type:"string"},TrackedQuestPath:{type:"string"},TrackedBranchID:{type:"string"},TrackedTaskPointID:{type:"string"},ManualTrackingOptOut:{anyOf:[{const:!1},{const:!0}]},NarrativeSavedQuests:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroQuest"}}]}},required:["CurrentMainQuestPath","CurrentTutorialQuestPath","TrackedQuestPath","TrackedBranchID","TrackedTaskPointID","ManualTrackingOptOut","NarrativeSavedQuests"],additionalProperties:!1},PhantomBladeZeroQuest:{type:"object",properties:{QuestClass:{type:"string"},QuestCompletion:{type:"string"},QuestBranches:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroQuestBranch"}}]},CompletedBranches:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},ReachedStateNames:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]}},required:["QuestClass","QuestCompletion","QuestBranches","CompletedBranches","ReachedStateNames"],additionalProperties:!1},PhantomBladeZeroQuestBranch:{type:"object",properties:{BranchID:{type:"string"},TasksProgress:{anyOf:[{type:"null"},{type:"array",items:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}}]},BranchType:{type:"string"}},required:["BranchID","TasksProgress","BranchType"],additionalProperties:!1},PhantomBladeZeroInventoryItem:{type:"object",properties:{id:{type:"string"},amount:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["id","amount"],additionalProperties:!1},PhantomBladeZeroSlotDetail:{type:"object",properties:{bell:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroBellDetail"}}]},weapon:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroItemDetail"}}]},shaqi:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroItemDetail"}}]},accessory:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroItemDetail"}}]},medicine:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroItemDetail"}}]},challenge:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroChallengeDetail"}}]},hupo:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroWorldItemDetail"}}]},heishi:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroWorldItemDetail"}}]},flower:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroItemDetail"}}]},achievements:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroAchievementDetail"}}]}},required:["bell","weapon","shaqi","accessory","medicine","challenge","hupo","heishi","flower","achievements"],additionalProperties:!1},PhantomBladeZeroBellDetail:{type:"object",properties:{unknown:{anyOf:[{const:!1},{const:!0}]},id:{type:"string"},done:{anyOf:[{const:!1},{const:!0}]},equip:{anyOf:[{const:!1},{const:!0}]}},required:["id","done","equip"],additionalProperties:!1},PhantomBladeZeroItemDetail:{type:"object",properties:{level:{type:"number"},soul_forged:{anyOf:[{const:!1},{const:!0}]},reincarnation_count:{type:"number"},unknown:{anyOf:[{const:!1},{const:!0}]},id:{type:"string"},name:{type:"string"},done:{anyOf:[{const:!1},{const:!0}]},equip:{anyOf:[{const:!1},{const:!0}]},locs:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroLocation"}}]}},required:["id","name","done","equip","locs"],additionalProperties:!1},PhantomBladeZeroLocation:{type:"object",properties:{map:{type:"string"},mapName:{type:"string"},x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["map","mapName","x","y","z"],additionalProperties:!1},PhantomBladeZeroChallengeDetail:{type:"object",properties:{key:{type:"string"},unknown:{anyOf:[{const:!1},{const:!0}]},index:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},guids:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},done:{anyOf:[{const:!1},{const:!0}]},locs:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroLocation"}}]}},required:["index","guids","done","locs"],additionalProperties:!1},PhantomBladeZeroWorldItemDetail:{type:"object",properties:{key:{type:"string"},unknown:{anyOf:[{const:!1},{const:!0}]},id:{type:"string"},saveGuid:{type:"string"},mobDomain:{type:"string"},done:{anyOf:[{const:!1},{const:!0}]},locs:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroLocation"}}]}},required:["id","saveGuid","mobDomain","done","locs"],additionalProperties:!1},PhantomBladeZeroAchievementDetail:{type:"object",properties:{id:{type:"string"},name:{type:"string"},desc:{type:"string"},grade:{type:"string"},hidden:{anyOf:[{const:!1},{const:!0}]},done:{anyOf:[{const:!1},{const:!0}]}},required:["id","name","desc","grade","hidden","done"],additionalProperties:!1},UserGameDataSaveFilePage:{type:"object",properties:{items:{type:"array",items:{$ref:"#/$defs/UserGameDataSaveInfo"}},hasMore:{const:!1}},required:["items","hasMore"],additionalProperties:!1},UserGameDataSaveInfo:{type:"object",properties:{saveId:{type:"string"},createdAt:{type:"string"},files:{type:"array",items:{$ref:"#/$defs/UserGameDataSaveFileInfo"}}},required:["saveId","createdAt","files"],additionalProperties:!1},UserGameDataSaveFileInfo:{type:"object",properties:{fileId:{type:"string"},name:{type:"string"},sizeBytes:{type:"number"},modifiedAt:{type:"string"}},required:["fileId","name","sizeBytes","modifiedAt"],additionalProperties:!1}},contracts:{"ark.profile":{$ref:"#/$defs/ArkProfile"},"ark.gacha-analysis":{$ref:"#/$defs/ArkGachaAnalysis"},"ark.gacha-record-page":{type:"object",properties:{items:{type:"array",items:{$ref:"#/$defs/GachaRecord"}},nextCursor:{type:"string"},hasMore:{anyOf:[{const:!1},{const:!0}]},total:{type:"number"}},required:["items","hasMore"],additionalProperties:!1},"black_myth_wukong.save":{$ref:"#/$defs/BlackMythWukongSave"},"task_bar_hero.save":{$ref:"#/$defs/TaskBarHeroSave"},"phantom_blade_zero.save":{$ref:"#/$defs/PhantomBladeZeroSave"},"save-file-page":{$ref:"#/$defs/UserGameDataSaveFilePage"}}},Dt=Ae("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");ft.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>fg(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Ll(e,r,n),e.parseAsync=async(r,n)=>hg(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Ul(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>sg(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),qg=Ae("ZodMiniString",(e,t)=>{Ng.init(e,t),Dt.init(e,t)});function P(e){return zg(qg)}const zl=Ae("ZodMiniNumber",(e,t)=>{jl.init(e,t),Dt.init(e,t)});function $(e){return Bg(zl)}const Qg=Ae("ZodMiniNumberFormat",(e,t)=>{Tg.init(e,t),zl.init(e,t)});function de(e){return Hg(Qg)}const Yg=Ae("ZodMiniNull",(e,t)=>{vg.init(e,t),Dt.init(e,t)});function te(e){return Fg(Yg)}const Wg=Ae("ZodMiniNever",(e,t)=>{Og.init(e,t),Dt.init(e,t)});function Zg(e){return $g(Wg)}const Kg=Ae("ZodMiniArray",(e,t)=>{kg.init(e,t),Dt.init(e,t)});function J(e,t){return new Kg({type:"array",element:e,...it()})}const Jg=Ae("ZodMiniObject",(e,t)=>{Cg.init(e,t),Dt.init(e,t),Qe(e,"shape",()=>t.shape)});function oe(e,t){return new Jg({type:"object",shape:e,catchall:Zg(),...it()})}const Xg=Ae("ZodMiniUnion",(e,t)=>{Lg.init(e,t),Dt.init(e,t)});function k(e,t){return new Xg({type:"union",options:e,...it()})}const ep=Ae("ZodMiniLiteral",(e,t)=>{Ug.init(e,t),Dt.init(e,t)});function le(e,t){return new ep({type:"literal",values:Array.isArray(e)?e:[e],...it()})}const tp=Ae("ZodMiniOptional",(e,t)=>{xg.init(e,t),Dt.init(e,t)});function V(e){return new tp({type:"optional",innerType:e})}const rp=Ae("ZodMiniLazy",(e,t)=>{jg.init(e,t),Dt.init(e,t)});function Y(e){return new rp({type:"lazy",getter:e})}const W={ArkProfile:oe({uid:P(),name:P(),level:$(),avatar:V(Y(()=>W.ArkPlayerAvatar)),characterCount:$(),totalCharacterCount:$(),mainStageProgress:P(),rogueLevel:$(),campaignFullKillCount:$(),tag:P(),observedAt:V(k([P(),$()])),lastOnlineTs:V(k([P(),$()])),registerTs:V(k([P(),$()])),changeTime:V(k([P(),$()])),operators:V(J(Y(()=>W.ArkOperator)))}),ArkPlayerAvatar:oe({url:P(),type:P(),id:P()}),ArkOperator:oe({characterId:P(),name:P(),profession:P(),evolvePhase:$(),potentialRank:$()}),ArkGachaAnalysis:oe({uid:P(),year:$(),total:$(),srCount:$(),upCount:$(),missCount:$(),careerEvaluation:P(),careerIsLucky:k([le(!1),le(!0)]),pools:J(Y(()=>W.ArkGachaPoolStat)),records:J(Y(()=>W.ArkGachaAnalysisRecord)),luckyLottery:J($())}),ArkGachaPoolStat:oe({poolId:P(),totalCost:$(),ssrCount:$(),ssrCost:$(),records:J(Y(()=>W.ArkGachaAnalysisRecord))}),ArkGachaAnalysisRecord:oe({name:P(),timestamp:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),diff:$(),negativeDiff:$(),tag:P(),missUp:k([le(!1),le(!0)])}),GachaRecord:oe({id:P(),name:P(),pool:P(),rarity:$(),timestamp:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),BlackMythWukongSave:oe({level:V($()),newGamePlusCount:V($()),gameTotalTime:V($()),playerDeathCount:V($()),totalMoney:V(P()),meditationList:V(k([te(),J($())])),monsterCollectionList:V(k([te(),J($())])),returnPointList:V(k([te(),J($())])),activatedWeaponIdList:V(k([te(),J(P())])),activatedEquipIdList:V(k([te(),J($())])),magicArtifactList:V(k([te(),J($())])),soulSkillIdList:V(k([te(),J($())])),huluIdLits:V(k([te(),J($())])),wineIdList:V(k([te(),J($())])),wineIdPartnerList:V(k([te(),J($())])),cropIdList:V(k([te(),J($())])),recipeIdList:V(k([te(),J($())])),wearedWaeponId:V(P()),wearedMagicArtifact:V($()),wearedSoulSkill:V($()),wearedHead:V($()),wearedUpware:V($()),wearedArm:V($()),wearedFoot:V($()),wearedHulu:V($()),wearedAccessoryList:V(k([te(),J($())])),spellQishu:V(k([te(),J($())])),spellShenfa:V(k([te(),J($())])),spellHaomao:V(k([te(),J($())])),spellBianshen:V(k([te(),J($())])),bossRushBossgroup:V(Y(()=>W.BlackMythWukongBossRushData)),bossRushRefight:V(Y(()=>W.BlackMythWukongBossRefightData))}),BlackMythWukongBossRushData:oe({bossGroups:V(k([te(),J(Y(()=>W.BlackMythWukongBossRushRecord))]))}),BlackMythWukongBossRushRecord:oe({bossGroupId:V($()),isPassed:V(k([le(!1),le(!0)])),bestRecords:V(k([te(),J(Y(()=>W.BlackMythWukongBattleRecord))])),encounterBossIndex:V($()),battleCount:V($())}),BlackMythWukongBattleRecord:oe({battleId:V(P()),battleData:V(Y(()=>W.BlackMythWukongBattleData))}),BlackMythWukongBattleData:oe({totalTime:V($()),score:V($()),debuffList:V(k([te(),J($())])),targetId:V($()),archiveTime:V(P()),roleBase:V(Y(()=>W.BlackMythWukongRoleBase)),battleStyleInfo:V(Y(()=>W.BlackMythWukongBattleStyleInfo)),damageInfo:V(Y(()=>W.BlackMythWukongDamageInfo))}),BlackMythWukongRoleBase:oe({level:V($()),atk:V($()),hpMax:V($()),staminaMax:V($()),mpMax:V($())}),BlackMythWukongBattleStyleInfo:oe({spellList:V(k([te(),J(Y(()=>W.BlackMythWukongCast))])),fabaoInfo:V(Y(()=>W.BlackMythWukongCast)),soulInfo:V(Y(()=>W.BlackMythWukongCast)),itemCount:V($()),wineCount:V($()),rollCount:V($()),defuseCount:V($()),fourPeCount:V($())}),BlackMythWukongCast:oe({castId:V($()),castCount:V($())}),BlackMythWukongDamageInfo:oe({totalDamage:V(k([P(),$()])),hightestDamage:V(k([P(),$()])),criticalDmgRate:V($()),totalBeDamaged:V(k([P(),$()])),criticalDmgTotal:V(k([P(),$()])),elemDotDmgTotal:V(k([P(),$()])),elemDotDmgRate:V($())}),BlackMythWukongBossRefightData:oe({bossList:V(k([te(),J(Y(()=>W.BlackMythWukongBossRefightRecord))]))}),BlackMythWukongBossRefightRecord:oe({bossId:V($()),passedMaxLevel:V($()),lastChallengeLevel:V($()),bestRecords:V(k([te(),J(Y(()=>W.BlackMythWukongBattleRecord))])),refightStatisticsList:V(k([te(),J(Y(()=>W.BlackMythWukongRefightStatistic))]))}),BlackMythWukongRefightStatistic:oe({challengeLevel:V($()),battleCount:V($())}),TaskBarHeroSave:oe({update_time:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),game_version:P(),account_version:P(),play_time:$(),last_saved_time:P(),common:Y(()=>W.TaskBarHeroCommon),summary:Y(()=>W.TaskBarHeroSummary),heroes:k([te(),J(Y(()=>W.TaskBarHeroHero))]),rune_save_data:k([te(),J(Y(()=>W.TaskBarHeroRune))]),pets:k([te(),J(Y(()=>W.TaskBarHeroPet))]),attributes:k([te(),J(Y(()=>W.TaskBarHeroAttribute))]),inventory_slots:k([te(),J(Y(()=>W.TaskBarHeroItemSlot))]),stash_slots:k([te(),J(Y(()=>W.TaskBarHeroItemSlot))]),item_instances:k([te(),J(Y(()=>W.TaskBarHeroItemInstance))]),values:Y(()=>W.TaskBarHeroValueSummary)}),TaskBarHeroCommon:oe({max_completed_stage:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_key:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_wave:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),arranged_hero_keys:k([te(),J(k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),arranged_pet_key:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroSummary:oe({max_hero_level:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),learned_rune_count:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unlocked_hero:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total_hero:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_count:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inventory_slots:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stash_slots:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroHero:oe({hero_key:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),hero_level:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:k([le(!1),le(!0)]),hero_exp:$(),ability_point:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),allocated_hero_ability_point:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),equipped_item_ids:k([te(),J(P())]),equipped_skill_keys:k([te(),J(k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),unlocked_attribute_group_keys:k([te(),J(k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))])}),TaskBarHeroRune:oe({rune_key:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroPet:oe({pet_key:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:k([le(!1),le(!0)])}),TaskBarHeroAttribute:oe({key:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroItemSlot:oe({index:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_unique_id:P(),is_unlock:k([le(!1),le(!0)]),is_unlocked_by_rune:k([le(!1),le(!0)])}),TaskBarHeroItemInstance:oe({item_key:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unique_id:P(),is_chaotic:k([le(!1),le(!0)]),is_blocked:k([le(!1),le(!0)]),is_server_pending_item:k([le(!1),le(!0)]),enchant_count:k([te(),J(k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),enchant_data:k([te(),J(Y(()=>W.TaskBarHeroEnchantData))]),item_get_source_type:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),decoration_applied_total_count:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),engraving_applied_total_count:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inscription_applied_total_count:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroEnchantData:oe({stat_mod_key:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),tier:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),value:$(),recipe_type:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),mod_type:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),material_key:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stat_type:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroValueSummary:oe({market_value:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),price_state:P(),currency:P()}),PhantomBladeZeroSave:oe({defaultSlot:P(),slots:J(Y(()=>W.PhantomBladeZeroSaveSlot))}),PhantomBladeZeroSaveSlot:oe({slot:P(),head:Y(()=>W.PhantomBladeZeroSlotHead),firstClear:Y(()=>W.PhantomBladeZeroSlotFirstClear),progress:Y(()=>W.PhantomBladeZeroSlotProgress),combat:Y(()=>W.PhantomBladeZeroSlotCombat),achievements:Y(()=>W.PhantomBladeZeroSlotAchievementSummary),bosses:Y(()=>W.PhantomBladeZeroSlotBossSummary),collectibles:Y(()=>W.PhantomBladeZeroSlotCollectibles),quest_details:k([te(),Y(()=>W.PhantomBladeZeroQuestDetails)]),inventory_details:k([te(),J(Y(()=>W.PhantomBladeZeroInventoryItem))]),detail:Y(()=>W.PhantomBladeZeroSlotDetail)}),PhantomBladeZeroSlotHead:oe({saveTime:P(),currentLevel:P(),cycle:P(),difficulty:Y(()=>W.PhantomBladeZeroSlotDifficulty)}),PhantomBladeZeroSlotDifficulty:oe({raw:$(),name:P()}),PhantomBladeZeroSlotFirstClear:oe({clearDate:Y(()=>W.PhantomBladeZeroUnavailableValue),cycles:k([te(),J(Y(()=>W.PhantomBladeZeroClearanceRecord))])}),PhantomBladeZeroUnavailableValue:oe({value:te(),reason:P()}),PhantomBladeZeroClearanceRecord:oe({Cycle:V(k([te(),$()])),Ending:$(),Difficulty:$(),GameTime:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),Completion:$(),DiedTimes:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotProgress:oe({playTimeSeconds:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),playTime:P(),lastLaunch:Y(()=>W.PhantomBladeZeroUnavailableValue),narrativePercentage:$(),chapter:P(),remainingDays:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCombat:oe({loadout:V(Y(()=>W.PhantomBladeZeroSlotLoadout)),totalDeaths:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),cycleDeaths:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bossKillTotal:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),currentMainWeapon:V(k([te(),Y(()=>W.PhantomBladeZeroNamedItem)])),mainWeapon:Y(()=>W.PhantomBladeZeroCollectionCount),currentShaqi:V(k([te(),Y(()=>W.PhantomBladeZeroNamedItem)])),shaqi:Y(()=>W.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroSlotLoadout:oe({states:V(k([te(),J(Y(()=>W.PhantomBladeZeroLoadoutState))])),main_weapons:k([te(),J(P())]),shaqi_weapons:k([te(),J(P())]),accessory_ids:k([te(),J(P())]),top_medicine:P(),bottom_medicine:P(),current_weapon_index:$(),current_shaqi_weapon_index:$()}),PhantomBladeZeroLoadoutState:oe({category:P(),id:P(),level:V($()),soul_forged:V(k([le(!1),le(!0)])),reincarnation_count:V($())}),PhantomBladeZeroNamedItem:oe({id:P(),name:P()}),PhantomBladeZeroCollectionCount:oe({unknown:V(k([P(),$()])),done:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotAchievementSummary:oe({unlocked:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:P()}),PhantomBladeZeroSlotBossSummary:oe({groups:k([te(),J(Y(()=>W.PhantomBladeZeroBossGroup))])}),PhantomBladeZeroBossGroup:oe({map:P(),mapName:P(),count:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bosses:k([te(),J(Y(()=>W.PhantomBladeZeroBoss))])}),PhantomBladeZeroBoss:oe({id:P(),classPath:P(),map:P(),mapName:P(),encountered:k([le(!1),le(!0)]),killed:k([le(!1),le(!0)]),kill:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),records:k([te(),J(Y(()=>W.PhantomBladeZeroBossRecord))])}),PhantomBladeZeroBossRecord:oe({cycle:P(),diff:P(),diffName:P(),kill:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCollectibles:oe({overall:Y(()=>W.PhantomBladeZeroCollectionSummary),craneBellCount:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),byBigMap:k([te(),J(Y(()=>W.PhantomBladeZeroBigMapProgress))]),currentChapter:Y(()=>W.PhantomBladeZeroChapterProgress)}),PhantomBladeZeroCollectionSummary:oe({bell:Y(()=>W.PhantomBladeZeroCollectionCount),weapon:Y(()=>W.PhantomBladeZeroCollectionCount),shaqi:Y(()=>W.PhantomBladeZeroCollectionCount),accessory:Y(()=>W.PhantomBladeZeroCollectionCount),medicine:Y(()=>W.PhantomBladeZeroCollectionCount),challenge:Y(()=>W.PhantomBladeZeroCollectionCount),hupo:Y(()=>W.PhantomBladeZeroCollectionCount),heishi:Y(()=>W.PhantomBladeZeroCollectionCount),flower:Y(()=>W.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroBigMapProgress:oe({unknown:V(k([P(),$()])),mapID:P(),name:P(),pct:$(),done:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),subMaps:k([te(),J(P())])}),PhantomBladeZeroChapterProgress:oe({unknown:V(k([P(),$()])),mapID:P(),pct:$(),done:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:P()}),PhantomBladeZeroQuestDetails:oe({CurrentMainQuestPath:P(),CurrentTutorialQuestPath:P(),TrackedQuestPath:P(),TrackedBranchID:P(),TrackedTaskPointID:P(),ManualTrackingOptOut:k([le(!1),le(!0)]),NarrativeSavedQuests:k([te(),J(Y(()=>W.PhantomBladeZeroQuest))])}),PhantomBladeZeroQuest:oe({QuestClass:P(),QuestCompletion:P(),QuestBranches:k([te(),J(Y(()=>W.PhantomBladeZeroQuestBranch))]),CompletedBranches:k([te(),J(P())]),ReachedStateNames:k([te(),J(P())])}),PhantomBladeZeroQuestBranch:oe({BranchID:P(),TasksProgress:k([te(),J(k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),BranchType:P()}),PhantomBladeZeroInventoryItem:oe({id:P(),amount:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotDetail:oe({bell:k([te(),J(Y(()=>W.PhantomBladeZeroBellDetail))]),weapon:k([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),shaqi:k([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),accessory:k([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),medicine:k([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),challenge:k([te(),J(Y(()=>W.PhantomBladeZeroChallengeDetail))]),hupo:k([te(),J(Y(()=>W.PhantomBladeZeroWorldItemDetail))]),heishi:k([te(),J(Y(()=>W.PhantomBladeZeroWorldItemDetail))]),flower:k([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),achievements:k([te(),J(Y(()=>W.PhantomBladeZeroAchievementDetail))])}),PhantomBladeZeroBellDetail:oe({unknown:V(k([le(!1),le(!0)])),id:P(),done:k([le(!1),le(!0)]),equip:k([le(!1),le(!0)])}),PhantomBladeZeroItemDetail:oe({level:V($()),soul_forged:V(k([le(!1),le(!0)])),reincarnation_count:V($()),unknown:V(k([le(!1),le(!0)])),id:P(),name:P(),done:k([le(!1),le(!0)]),equip:k([le(!1),le(!0)]),locs:k([te(),J(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroLocation:oe({map:P(),mapName:P(),x:$(),y:$(),z:$()}),PhantomBladeZeroChallengeDetail:oe({key:V(P()),unknown:V(k([le(!1),le(!0)])),index:k([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),guids:k([te(),J(P())]),done:k([le(!1),le(!0)]),locs:k([te(),J(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroWorldItemDetail:oe({key:V(P()),unknown:V(k([le(!1),le(!0)])),id:P(),saveGuid:P(),mobDomain:P(),done:k([le(!1),le(!0)]),locs:k([te(),J(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroAchievementDetail:oe({id:P(),name:P(),desc:P(),grade:P(),hidden:k([le(!1),le(!0)]),done:k([le(!1),le(!0)])}),UserGameDataSaveFilePage:oe({items:J(Y(()=>W.UserGameDataSaveInfo)),hasMore:le(!1)}),UserGameDataSaveInfo:oe({saveId:P(),createdAt:P(),files:J(Y(()=>W.UserGameDataSaveFileInfo))}),UserGameDataSaveFileInfo:oe({fileId:P(),name:P(),sizeBytes:$(),modifiedAt:P()})},np=new Map([["ark.profile",Y(()=>W.ArkProfile)],["ark.gacha-analysis",Y(()=>W.ArkGachaAnalysis)],["ark.gacha-record-page",oe({items:J(Y(()=>W.GachaRecord)),nextCursor:V(P()),hasMore:k([le(!1),le(!0)]),total:V($())})],["black_myth_wukong.save",Y(()=>W.BlackMythWukongSave)],["task_bar_hero.save",Y(()=>W.TaskBarHeroSave)],["phantom_blade_zero.save",Y(()=>W.PhantomBladeZeroSave)],["save-file-page",Y(()=>W.UserGameDataSaveFilePage)]]);function ip(e,t){return np.get(e)?.safeParse(t).success??!1}function op(e){const t=Lc.contracts[e];if(!t)throw new Error("未知资料 schema");function r(n){if(Object.prototype.hasOwnProperty.call(n,"const"))return n.const;if(n.$ref)return r(Lc.$defs[n.$ref.slice(8)]);if(n.anyOf)return r(n.anyOf[0]);switch(n.type){case"string":return n.pattern?"0":"";case"number":case"integer":return 0;case"boolean":return!1;case"null":return null;case"array":return n.prefixItems?n.prefixItems.map(r):[];case"object":return Object.fromEntries((n.required??[]).map(i=>[i,r(n.properties[i])]));default:throw new Error("未知资料类型")}}return r(t)}zt.map(e=>e.method);function oi(){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:oi()}function Bl(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 Hl="METHOD_FORBIDDEN";function tt(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Hl,t}class Le extends Error{code="HOST_REQUEST_UNSUPPORTED";constructor(t="当前 Host 不支持该请求形状",r){super(t),this.name="HostRequestUnsupportedError",r&&"cause"in r&&Object.defineProperty(this,"cause",{configurable:!0,enumerable:!1,value:r.cause}),Object.setPrototypeOf(this,new.target.prototype)}}const sp=/^[A-Za-z0-9_-]{1,64}$/,Uc=1e3;function Fl(e){return sp.test(e)?e:up(e)}function ap(e){return`id_${Fl(e.trim())}`}function fr(e,t){return`hb_miniprogram_${e}_${t}`}function $n(e){return`hb_miniprogram_keys_${e}`}const cp="hb_user_game_data_consent_";function dp(e){return`${cp}${e}`}function up(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 lp=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 $a(e){const t=new TextEncoder().encode(e),r=Math.ceil((t.length+9)/64)*64,n=new Uint8Array(r);n.set(t),n[t.length]=128,new DataView(n.buffer).setUint32(r-4,t.length*8,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64),s=new DataView(n.buffer);for(let a=0;a<r;a+=64){for(let I=0;I<16;I+=1)o[I]=s.getUint32(a+I*4,!1);for(let I=16;I<64;I+=1){const E=o[I-15],b=o[I-2],y=mt(E,7)^mt(E,18)^E>>>3,v=mt(b,17)^mt(b,19)^b>>>10;o[I]=o[I-16]+y+o[I-7]+v>>>0}let[c,d,u,f,l,h,m,g]=i;for(let I=0;I<64;I+=1){const E=g+(mt(l,6)^mt(l,11)^mt(l,25))+(l&h^~l&m)+lp[I]+o[I]>>>0,b=(mt(c,2)^mt(c,13)^mt(c,22))+(c&d^c&u^d&u);g=m,m=h,h=l,l=f+E>>>0,f=u,u=d,d=c,c=E+b>>>0}[c,d,u,f,l,h,m,g].forEach((I,E)=>{i[E]=i[E]+I>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function mt(e,t){return e>>>t|e<<32-t}const fp=Object.freeze({upload:"你允许读取的数据可能会被上传至开发者服务器。",no_network:"此小程序未获准将你允许读取的数据上传至开发者服务器。"});function mp(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&&!pp(s.consentFingerprint))return;n[i]={decision:s.decision,revision:s.revision,...s.decision==="allow"&&s.consentFingerprint!==void 0?{consentFingerprint:s.consentFingerprint}:{}}}return{schema_version:1,records:n}}function hp(e){return $a(`${e.miniProgramId}\0${e.userId}\0${e.environment}`).slice(0,32)}function gp(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 pp(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function Ee(e,t,r){return{code:e,message:t,data:r}}function Va(e){return yp(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?Ee("RUNTIME_ERROR",e.message):Ee("UNKNOWN_ERROR","小程序运行时异常",e)}function yp(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}const Qt=["account.getCurrentUserId","account.onChange","storage.getRaw","storage.setRaw"],qo=[...Qt,"network.request"],xc={"gameSaves.list":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.sync":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.readParsedData":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.getFile":["account.getCurrentUserId","account.onChange","network.request","network.stream","files.transfer","files.access"],[Ai]:["workspaceCards.requestRefresh"],[Di]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[bi]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Mi]:["account.getCurrentUserId","account.onChange","network.request"],[Si]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Ni]:["account.getCurrentUserId","account.onChange","network.request"],[Ti]:["account.getCurrentUserId","account.onChange","network.request"],[vi]:["account.getCurrentUserId","account.onChange","network.request"],[Oi]:["presentation.setClipboard"],[ki]:["presentation.showShareMenu"],[Pi]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Ri]:["presentation.getViewportMetrics","presentation.captureAndShare"],[nr]:["presentation.applyOrientation"],[Ci]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Li]:["presentation.setNavigationBarStyle"],[yn]:["storage.getRaw"],[wn]:["storage.setRaw"],[Ui]:["network.request"],[xi]:["network.stream","files.transfer","files.access"],[ji]:["network.upload","files.access"],[zi]:["files.external"],[Bi]:["files.external"],[Hi]:["files.save"],[En]:["files.access"],[In]:["files.removeFile"],[Fi]:["files.access"],[_n]:["files.access"],[$i]:["files.access"],[An]:["files.access"],[Vi]:["files.access"],[Dn]:["files.access"],[Gi]:["files.access"],[bn]:["files.removeDirectory"],[qi]:["files.access"],[Qi]:["files.access"],[Mn]:["media.pick"],[pn]:["presentation.showAppreciation"],[Yi]:["presentation.showToast"],[Wi]:["presentation.showLoading"],[Zi]:["presentation.hideLoading"],[Ki]:["presentation.vibrate"],[Ji]:["presentation.setClipboard"],[Xi]:["protocol.invoke"],[eo]:["presentation.close"],[to]:["presentation.reload"],[ro]:["presentation.openAppPage"],[Nt]:["account.getCurrentUserId","account.onChange","network.request"],[at]:["account.onChange","network.request"],[jt]:["account.getCurrentUserId","account.onChange","network.request"],[ir]:["account.getCurrentUserId","account.onChange","network.request"],[It]:["account.onChange","network.request"],[vr]:["account.getCurrentUserId","account.onChange","network.request"],[Or]:["account.getCurrentUserId","account.onChange","network.request"],[kr]:["account.getCurrentUserId","account.onChange","network.request"],[or]:["account.getCurrentUserId","account.onChange","network.request"],[wo]:["companion.getInfo"],[Eo]:["companion.getPreparationStatus"],[Io]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[_o]:["companion.cancelPreparation"],[Ao]:["companion.getActiveSession"],[Do]:["companion.getInfo","companion.launch"],[bo]:["companion.session.write"],[Mo]:["companion.session.closeStdin"],[So]:["companion.session.terminate"],[No]:["companion.session.ackOutput"],[To]:["companion.openAttachment"],[vo]:["companion.showNotification"],[Ca]:Qt,[Ii]:qo,[dn]:qo,[_i]:[...qo,"files.sandbox","files.removeFile","network.stream","files.transfer"],[La]:[...Qt,"presentation.confirmDataPermission"],[Ua]:Qt,[xa]:Qt,[ja]:[...Qt,"presentation.openDataPermissions"],[za]:Qt},wp=new Set([pn]);function $l(e,t){if(t[e]!==!0)throw wp.has(e)?Ee("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):tt(e)}const Ep=32*1024*1024,Ip=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function _p(e){if(e.mode==="request-only")return{network:{request:(n,i)=>e.request(n,i)}};if(e.mode==="override-request")return{network:{request:(n,i)=>e.request(n,i)},...e.stream===void 0?{}:{stream:e.stream}};const{consume:t,stream:r}=e;return{stream:r,network:{async request(n,i){const o=await r.open(n,i);let s;try{const a=await t(o.body,{maxBytes:Ep},i);return Ap(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Ap(e,t){const r=Object.fromEntries(Object.entries(e.headers).map(([n,i])=>[n,i.join(", ")]));return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:r,data:Dp(t,Mp(e,"content-type"))}}function Dp(e,t){bp(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new Le("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!Ip.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function bp(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new Le(`Host network response 不支持 charset=${t}`)}function Mp(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function Z(e){return typeof e=="function"}function jc(e){return(...t)=>{throw tt(e)}}function Ce(e){return async(...t)=>{throw tt(e)}}const Sp=(e,t)=>{},Np=()=>()=>{};function Tp(e){const t={request:Z(e.network?.request)?e.network.request.bind(e.network):Ce("network.request")},r={...Z(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:Z(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):Ce("account.getCurrentUserId"),ensureAuthenticated:Z(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Ce("account.ensureAuthenticated"),onChange:Z(e.account?.onChange)?e.account.onChange.bind(e.account):Np},n={...e.storage?.withLock?{withLock:e.storage.withLock.bind(e.storage)}:{},getRaw:Z(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Ce("storage.getRaw"),setRaw:Z(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Ce("storage.setRaw")},i={...Z(e.presentation?.showSteamLoginRequired)?{showSteamLoginRequired:e.presentation.showSteamLoginRequired.bind(e.presentation)}:{},...Z(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...Z(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:Z(e.presentation?.close)?e.presentation.close.bind(e.presentation):Ce("presentation.close"),reload:Z(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Ce("presentation.reload"),openAppPage:Z(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Ce("presentation.openAppPage"),openWindow:Z(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Ce("presentation.openWindow"),getViewportMetrics:Z(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):jc("presentation.getViewportMetrics"),getNavigationBarHeight:Z(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):jc("presentation.getNavigationBarHeight"),setNavigationBarStyle:Z(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Ce("presentation.setNavigationBarStyle"),showShareMenu:Z(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Ce("presentation.showShareMenu"),setScreenshotChromeHidden:Z(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):Sp,supportsLongScreenshot:e.presentation?.supportsLongScreenshot===!0,captureAndShare:Z(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Ce("presentation.captureAndShare"),showAppreciation:Z(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw Ee("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:Z(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Ce("presentation.showToast"),showLoading:Z(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Ce("presentation.showLoading"),hideLoading:Z(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Ce("presentation.hideLoading"),vibrate:Z(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Ce("presentation.vibrate"),setClipboard:Z(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Ce("presentation.setClipboard")},o=Z(e.storageDiagnostics?.listRaw)?{listRaw:e.storageDiagnostics.listRaw.bind(e.storageDiagnostics)}:void 0,s=Object.fromEntries(["getInfo","getPreparationStatus","prepare","cancelPreparation","getActiveSession","launch","write","closeStdin","terminate","ackOutput","openAttachment","showNotification"].map(c=>[c,Z(e.companion?.[c])?e.companion[c].bind(e.companion):Ce(`companion.${c}`)]));Z(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const a={invoke:Z(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):Ce("protocol.invoke")};return{network:t,...e.workspaceCards?{workspaceCards:e.workspaceCards}:{},account:r,storage:n,presentation:i,companion:s,protocol:a,...e.files===void 0?{}:{files:e.files},...e.picker===void 0?{}:{picker:e.picker},...e.media===void 0?{}:{media:e.media},...e.transfer===void 0?{}:{transfer:e.transfer},...e.scopedStorage?{scopedStorage:e.scopedStorage}:{},...o?{storageDiagnostics:o}:{}}}function vp(e,t={}){const r=Op(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 Op(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 zc(e,t){return t?.[e]!==!1}function kp(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function Vl(e,t={}){const r={};for(const n of Object.keys(xc)){const o=xc[n].every(a=>e[a]),s=!kp(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=zc(n,t.callerCapabilities)&&zc(n,t.hostCapabilities)&&o&&s}return r}function Gl(e={},t={}){const r=vp(e,t),n=Vl(r,t);return{ports:Tp(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]):Pp(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function Pp(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 Rp(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 Cp=4,Lp=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Up=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),xp=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],jp=["/account/restore_login","/account/check_login","/account/login","/account/get_login_code","/account/login_code","/account/get_qrcode_url","/account/qr_state","/account/google_2fa_verify","/account/open/login","/account/captcha","/account/get_verify_code","/account/send_verify_code","/account/verify_code"];function zp(e,t){const r=Fp(e);return r===null||Bc(r,xp)?!0:t&&Bc(r,jp)}function Bp(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Lp.some(r=>t===r||t.endsWith(`.${r}`))}function Hp(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||Up.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Fp(e){let t=e;for(let r=0;r<Cp;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Hc(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Hc(t)}function Bc(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Hc(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function $p(e){if(typeof e!="string"||e!==e.trim()||e.length>253)return;const t=e.toLowerCase();if(!(!t.includes(".")||/^\d+(?:\.\d+)*$/.test(t))&&t.split(".").every(r=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(r))&&!(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")))return t}function ql(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw Qo("网络策略格式无效");const t=e,r=t.entries===void 0?[]:t.entries;if(!Number.isSafeInteger(t.revision)||t.revision<1||t.enforcement!=="approved_domains"&&t.enforcement!=="restricted"||!Array.isArray(r)||r.length>20)throw Qo("网络策略格式无效");const n=new Set;for(const i of r){const o=$p(i&&typeof i=="object"?i.domain:void 0);if(!o)throw Qo("网络策略包含无效域名");n.add(o)}return Object.freeze({revision:t.revision,enforcement:t.enforcement,entries:Object.freeze([...n].sort().map(i=>Object.freeze({domain:i})))})}function Qo(e){return Object.assign(new TypeError(e),{code:"NETWORK_POLICY_INVALID"})}function Fc(e){return e instanceof Le?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function fe(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(oi());let n;try{n=e()}catch(i){return Promise.reject(Fc(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(oi())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(oi()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(Fc(d))))})}async function Vp(e,t,r){pe(r);const i=e.ownerDocument.defaultView;if(!i||!e.isConnected)throw new Error("长图容器不可用");const o=e.getAttribute("style"),s=i.scrollX,a=i.scrollY,c=e.getBoundingClientRect().width,d=()=>{o===null?e.removeAttribute("style"):e.setAttribute("style",o),i.scrollTo(s,a)};try{e.style.setProperty("width",`${c}px`,"important"),e.style.setProperty("height",`${t.top+t.height}px`,"important"),e.style.setProperty("min-height","0","important"),e.style.setProperty("max-height","none","important"),i.scrollTo(0,0),await fe(()=>new Promise(f=>i.requestAnimationFrame(()=>i.requestAnimationFrame(()=>f()))),r);const u=e.getBoundingClientRect();if(u.height+1<t.top+t.height||u.width+1<t.left+t.width||u.left<0||u.top<0)throw new Error("宿主布局无法容纳长图");for(let f=e.parentElement;f;f=f.parentElement){const l=i.getComputedStyle(f),h=f.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(l.overflowY)&&(u.top+t.top<h.top-1||u.top+t.top+t.height>h.bottom+1))throw new Error("宿主布局无法容纳长图:祖先容器存在纵向裁剪")}return{rect:{...t,left:t.left+u.left,top:t.top+u.top},restore:d}}catch(u){throw d(),u}}function Gp(e,t,r,n=1e4){const i=new AbortController;return new Promise((o,s)=>{let a=!1;const c=f=>{a||(a=!0,clearTimeout(u),r.signal.removeEventListener("abort",d),i.abort(f),s(f))},d=()=>{i.abort(),c({code:"NETWORK_POLICY_CHANGED",message:"网络策略初始化已取消"})},u=setTimeout(()=>c({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 网络策略初始化超时"}),n);if(r.signal.addEventListener("abort",d,{once:!0}),r.signal.aborted){d();return}Promise.resolve().then(()=>e.activate(t,{signal:i.signal})).then(f=>{if(typeof f!="function"){c({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 未完成严格网络策略初始化"});return}if(a){try{f()}catch{}return}a=!0,clearTimeout(u),o(()=>{r.signal.removeEventListener("abort",d),i.abort(),f()})},c)})}function Ql(e,t){return qp(t)??Qp(e.pathname)}function qp(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Qp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const Yp=1,Yl="allow-scripts allow-same-origin",Wp="",Zp="no-referrer";function Kp(e=Yl){return!e.split(/\s+/).includes("allow-same-origin")}function $c(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Jp=new Set(["javascript:","data:","blob:","file:"]),Vc="xiaoheihe.cn";function Xp(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(Jp.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!ty(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function ey(e,t){const r=new URL(e);return r.searchParams.set(pl,t),r.toString()}function Wl(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Ql(n,r);return i.pathname.startsWith(o)}catch{return!1}}function Gc(e){const t=new URL(e);return Ga(t)?"loopback":qa(t)?"lan":"production"}function ty(e,t,r){return ry(e)||Ga(e)||qa(e)&&iy(t,r)}function ry(e){return e.protocol==="https:"&&ay(e.hostname)}function Ga(e){return e.protocol==="http:"&&ny(e.hostname)}function ny(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function qa(e){return e.protocol==="http:"&&oy(e.hostname)}function iy(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Ga(r)||qa(r)}catch{return!1}}function oy(e){const t=sy(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function sy(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 ay(e){return e===Vc||e.endsWith(`.${Vc}`)}function cy(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||!Wl(e.launchUrl,a.href,e.locationBasePath))return;const c=new URL(a.href);if(!(c.username||c.password||c.searchParams.get(pl)!==e.nonce)){if(a.phase==="leaving"){a.documentId===t&&!r&&(r=!0,e.onLeaving());return}if(a.phase==="boot"){if(t!==void 0&&t!==a.documentId&&a.navigationType==="reload"){n=!0,e.onReload(c.href);return}r&&t===a.documentId&&e.onResume(),t=a.documentId,r=!1}}};return window.addEventListener("message",o),()=>{window.removeEventListener("message",o)}}function Zl(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 dy(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 uy(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const ly=1e3;function fy(e,t=uy()){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<=ly}const my="runtime.gate.probe",Kl=new Set(zt.map(e=>e.method));class hy{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=gl;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.getWorkspaceCardLaunchContext=t.getWorkspaceCardLaunchContext,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,this.onDevUploadSession=t.onDevUploadSession,this.handleMessage=this.onMessage.bind(this),this.handleUserInteraction=this.onUserInteraction.bind(this),this.dispatcher=t.dispatcher,this.environmentInfo=t.environmentInfo,this.targetOrigin=t.targetOrigin||"*"}get protocolVersion(){return this.handshaken?this.bridgeVersion:void 0}start(){if(!(this.started||this.destroyed)){this.started=!0,window.addEventListener("message",this.handleMessage);for(const t of["pointerdown","touchend","mousedown","keydown"])window.addEventListener(t,this.handleUserInteraction,!0)}}setTargetOrigin(t){this.targetOrigin=t||"*"}destroy(){if(this.destroyed)return;const t=this.started;this.destroyed=!0,this.started=!1,this.handshaken=!1;try{t&&this.postMessage({namespace:qt,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:qt,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:qt,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:qt,version:2,nonce:this.nonce,type:"event",id:t,method:wl,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=fy(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&&Rh(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:qt,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:yl,payload:{environment:this.environmentInfo,...this.getWorkspaceCardLaunchContext?{workspaceCardLaunchContext:this.getWorkspaceCardLaunchContext()}:{}}}),this.postEvent("ready",{timestamp:Date.now()}),o?this.onReady?.(n):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===my){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,Ee("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Kl.has(t.method)){this.postResponse(t,void 0,Ee("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,Ee("INVALID_PARAMS","bridge request id 重复"));return}const n=new AbortController;this.operations.set(t.id,n);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{requestId:t.id,postEvent:this.postEvent.bind(this),postProgress:o=>{this.operations.get(t.id)===n&&this.postProgress(t.id,o)},signal:n.signal,trustedUserGesture:r});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==n)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==n)return;const o=Va(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:qt,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!gy(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 gy(e){return typeof e=="string"&&Kl.has(e)}function w(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qa(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw w("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 w("FILE_IO_FAILED","无法生成安全文件标识")}}function Jl(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:n,create:i?(s,a)=>e.create(s,a):Ys,remove:o?s=>e.remove(s):ef,read:s=>e.read(s),...typeof e.readPrefix=="function"?{readPrefix:(s,a)=>e.readPrefix(s,a)}:{},write:i?(s,a)=>e.write(s,a):Ys,stat:s=>e.stat(s)})}function Xl(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=>Jl(e.file(a),n,{allowRemove:o}),directory:a=>Xl(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Ys,remove:s?(a,c)=>e.remove(a,c):ef,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Ys(){return Promise.reject(w("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function ef(){return Promise.reject(w("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const py=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"]),yy={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 Rr(e){const t=Ya(e),r=t&&py.has(t)?w(t,yy[t]??"文件操作失败"):w("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function bt(e){try{return e()}catch(t){throw Rr(t)}}function Ya(e){try{if(!re(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const qc=1024;class Wa{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new Wa(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 Vn(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=bt(()=>{if(!Array.isArray(t))throw w("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw w("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>qc)throw w("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw w("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>Vn(a.handle,{kind:"file",handleId:s[c]}))}revokeFiles(t){for(const r of t)this.handles.get(r)?.handle.kind==="file"&&this.handles.delete(r)}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[o]=this.registerMany([i]);return Yc(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!er(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!er(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}isUserDataDownloadRef(t){return!er(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="download"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Ey(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Nn(r.relativePath);Yo(n.origin,i);const o=this.prepareFile(bt(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Iy(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==="."?".":Nn(r.relativePath);Yo(n.origin,i);const o=this.prepareDirectory(i==="."?n.hostHandle:bt(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Zc(t),Vn(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),bt(()=>{if(!Array.isArray(r))throw w("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw w("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw w("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&re(a)&&typeof a.name=="string"&&tf(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return bt(()=>{if(re(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Vn(n.handle,Qc(t.ref,n.handle.name))}if(re(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return Yc(n.handle,wy(t.ref,n.handle.name))}throw w("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Cn(r);Yo(t.origin,n);const i=this.prepareFile(bt(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:Qc(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw w("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return bt(()=>{Zc(t);const i=n??t.mode;return Wc(t.mode,i),{handle:Jl(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return bt(()=>{Dy(t,i);const o=n??t.mode;return Wc(t.mode,o),{handle:Xl(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>qc)throw w("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Qa();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw w("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!_y(t))throw w("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw w("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw w("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw tt("files.sandbox");return this.prepareDirectory(bt(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw w("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw tt("files")}}function Nn(e){if(!Ba(e))throw w("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Yo(e,t){if(e==="sandbox"&&tf(t))throw w("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function tf(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function Cn(e,t="文件名"){const r=Nn(e);if(r.includes("/"))throw w("INVALID_PARAMS",`${t} 只能是 basename`);return r}function Qc(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Nn(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function wy(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Nn(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Vn(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function Yc(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Wc(e,t){if(t==="readwrite"&&e!=="readwrite")throw w("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Ey(e){return er(e)||rf(),e}function Iy(e){return Il(e)||rf(),e}function rf(){throw w("INVALID_PARAMS","文件引用不合法")}function _y(e){return/^[0-9a-f]{32}$/.test(e)}function Ay(e){return re(e)&&e.kind==="file"&&typeof e.name=="string"&&(e.mode==="read"||e.mode==="readwrite")&&typeof e.create=="function"&&typeof e.read=="function"&&typeof e.write=="function"&&typeof e.stat=="function"}function Zc(e){if(!Ay(e))throw w("FILE_IO_FAILED","Host 返回了无效 File handle");Cn(e.name,"Host File name")}function Dy(e,t=!1){if(!re(e)||e.kind!=="directory"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.file!="function"||typeof e.directory!="function"||typeof e.create!="function"||typeof e.stat!="function"||typeof e.list!="function")throw w("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw w("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&Cn(e.name,"Host Directory name")}const by=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),My=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Sy=new Set(["range","if-range","a-im"]),Ny=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"]),Ty=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Gn={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class vy{constructor(t){this.signal=t}phase="initial";transition(t){if(Gn[t]<=Gn[this.phase])throw w("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Gn[this.phase]<Gn.committed&&this.signal.aborted)throw sf()}normalizeHostError(t,r){return this.throwIfCancelled(),Ka(t,r,this.signal)}}async function nf(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 vy(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Ry(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=Ly(c);Uy(c,u);const f=xy(c.status,u);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw w("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const l=Cy(e,a,u,i);let h=0;const m=ky(f.expectedBytes,e.maxBytes);Zo(t,Wo(0,f));const g={...o,onProgress(b){!Number.isSafeInteger(b)||b<h||m!==void 0&&b>m||(h=b,Zo(t,Wo(h,f)))}};s.transition("transfer"),d=!0;let I;try{I=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}},g)}catch(b){throw s.normalizeHostError(b,"transfer")}s.transition("committed"),h=Oy(I,f,h,e.maxBytes),Zo(t,Wo(h,f));const E=i.describeFile(l.handle,l.ref);return s.transition("completed"),E}finally{d||Py(n.network,c.body)}}function Oy(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 ky(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Py(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Ry(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Ws(i.handle.mode),await Vy(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Ws(n.handle.mode),await Gy(n.handle,r),{kind:"directory",...n}}function Cy(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=zy(e,r),o=n.deriveFile(t,i);return Ws(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Ly(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 w("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!re(e.headers))throw w("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!by.has(r)||!Array.isArray(n)||n.length===0)throw w("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw w("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Uy(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw w("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:$y(t,My)});if((t["content-range"]?.length??0)>0)throw w("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function xy(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw w("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw w("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw w("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=jy(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 jy(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Wo(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Zo(e,t){try{e.postProgress(t)}catch{}}function zy(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=By(i);if(o&&si(o))return o}for(const i of r){const o=Hy(i);if(o&&si(o))return o}if(e.suggestedName!==void 0)return Za(e.suggestedName);const n=Fy(e.url);return n&&si(n)?n:"download.bin"}function By(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 Hy(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 Fy(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Za(e){try{Cn(e,"suggestedName")}catch{throw w("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!si(e))throw w("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function si(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Ty.test(e))}function $y(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Vy(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw of()}catch(r){throw Ka(r,"file",t.signal)}}async function Gy(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw of()}catch(r){throw Ka(r,"file",t.signal)}}function Ws(e){if(e!=="readwrite")throw w("FILE_ACCESS_DENIED","下载目标只允许读取")}const qy={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 Ka(e,t,r){if(r.aborted)return sf();const n=Qy(e);if(n&&Ny.has(n)){const o=w(n,qy[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?w("DOWNLOAD_TIMEOUT","下载网络请求超时"):w("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?w("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):w("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function Qy(e){return re(e)&&typeof e.code=="string"?e.code:void 0}function of(){return w("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function sf(){return w("DOWNLOAD_CANCELLED","下载已取消")}function Yy(e){if(!e)return;const t=Object.keys(e).find(r=>Sy.has(r.trim().toLowerCase()));if(t)throw w("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Kc=8*1024*1024,Wy=32*1024*1024;function Ja(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 w("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 w("INVALID_RESPONSE","存档下载描述无效");if(u.size_bytes>Kc)throw w("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(!Bl(f)||new URL(a.download_url).pathname!==`/cloud_archive/${u.file_id}.zip`||a.expires_at<=Date.now())throw w("INVALID_RESPONSE","存档下载地址无效");s(d);const l=Math.min(Kc,Wy-r);if(l<=0)throw w("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达上限");const h=e.files.sandbox.file(`.hb-game-saves/${Qa()}.zip`);if(!h.remove)throw w("REQUEST_UNSUPPORTED","宿主不支持私有存档清理");r+=l;let m=!1;try{await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},d),await h.create({recursive:!0,exclusive:!0},d);const g=e.registry.createTransferScope();try{const y=g.registerFile(h,"game-save","readwrite");await nf({request:f,url:new URL(a.download_url),to:y.ref,targetKind:"file",maxBytes:l},{...d,trustedUserGesture:!1,postEvent:()=>{},postProgress:()=>{}},{transfer:e.transfer,fileRegistry:g,operationContext:d})}finally{g.dispose()}s(d);const I=(await h.stat(d)).size;if(!Number.isSafeInteger(I)||I<0||I>l)throw w("FILE_TOO_LARGE","存档实际大小超过限额");await c(d),s(d);const E=async()=>{throw w("FILE_ACCESS_DENIED","存档文件只读")},b={kind:"file",mode:"read",name:u.name,create:E,write:E,async read(y){s(y),await c(y);const v=await h.read(y);try{if(s(y),await c(y),v.byteLength!==I)throw w("INVALID_RESPONSE","私有存档副本长度不匹配");return v}catch(j){throw v.fill(0),j}},async stat(y){return s(y),await c(y),await h.stat(y),s(y),await c(y),{kind:"file",size:I,...typeof u.modified_at=="number"&&Number.isSafeInteger(u.modified_at)?{modifiedAt:u.modified_at}:{}}}};return r-=l-I,t.set(b,{target:h,size:I}),m=!0,b}finally{m||(r-=l,await i(h))}}}}const Zy=/^(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 Ky(e){if(!e?.minimumSdkVersion)throw Ee("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=Zt(e.minimumSdkVersion),r=e.sdkVersion?Zt(e.sdkVersion):void 0;if(!t)throw Ee("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw Ee("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=Zt("0.6.0");if(!r){if(ai(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw Ee("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0&&e.allowPublicPrerelease!==!0)throw Ee("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(ai(r,t)<0)throw Ee("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:ai(r,Zt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Jy(e,t){if(typeof t!="string"||!Zt(t))throw Ee("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw Ee("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function Xa(e,t){const r=Zt(e),n=Zt(t);if(!(!r||!n))return ai(r,n)}function Zt(e){const t=Zy.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 ai(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 Xy(e){return{[pn]:async(t,r)=>{const n=Se(e.operationContext,r.signal);if(pe(n.signal),t!==void 0)throw w("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw w("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw w("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const o=e.presentation.showAppreciation;if(!o)throw w("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await fe(()=>o({name:i.name,author:i.author},n),n.signal)}}}function mr(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Jc(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function af(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,o=new Map,s=new Set,a=new Set;let c=!1;function d(g,I){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:g,type:I})).catch(()=>{})}catch{}}function u(g){const I=r.get(g);if(!I)throw new Error("Unknown runtime cache scope");return I}function f(g,I){return g.flatMap((E,b)=>{const y=JSON.stringify(g.slice(0,b+1));return[JSON.stringify([y]),JSON.stringify([y,I])]})}function l(g,I){return JSON.stringify(f(g,I).map(E=>n.get(E)??0))}async function h(g,I){const E=u(g),b=JSON.stringify([JSON.stringify(E),...I?[I]:[]]),y=(n.get(b)??0)+1;n.set(b,y),i.add(b);for(const v of a)v(E,I);if(!e.store){i.delete(b),d(I??"*","invalidation");return}try{await e.store.invalidate(E,I)}catch(v){throw d(I??"*","storage_error"),v}n.get(b)===y&&i.delete(b),d(I??"*","invalidation")}function m(g){if(c)throw new Error("Runtime cache manager disposed");const I=o.get(g.namespace);if(I){if(I.sourceCodec!==g.codec||I.definition.codec.version!==g.codec.version||JSON.stringify(I.definition.policy)!==JSON.stringify(g.policy))throw new Error("Conflicting runtime cache namespace");return I.cache}if(!g.namespace||!g.codec.version)throw new Error("Invalid runtime cache definition");const E=Object.freeze({...g.policy}),b=Object.freeze({version:g.codec.version,encode:g.codec.encode.bind(g.codec),decode:g.codec.decode.bind(g.codec),validate:g.codec.validate.bind(g.codec),clone:g.codec.clone.bind(g.codec)}),y=g.namespace;for(const L of[E.ttlMs,E.memoryMaxEntries,E.diskMaxEntries,E.diskMaxBytes,E.maxEntryBytes])if(!Number.isFinite(L)||L<0)throw new Error("Invalid runtime cache policy");const v=new Map,j=new Map,A=new Map;let D=!1;function _(L,C,H){if(c||D||L.aborted||l(C,y)!==H)throw mr()}function T(L){return E.ttlMs>0&&E.persistence==="memory-and-disk"&&!!e.store&&!f(L,y).some(C=>i.has(C))}function N(L,C,H){const F=t();return L.envelopeVersion===1&&JSON.stringify(L.address)===JSON.stringify(C)&&Jc(L.revisions,H)&&L.payload.byteLength<=E.maxEntryBytes&&Number.isFinite(L.cachedAt)&&Number.isFinite(L.expiresAt)&&L.cachedAt<=F&&L.cachedAt>=0&&L.expiresAt>L.cachedAt&&Math.min(L.expiresAt,L.cachedAt+E.ttlMs)>F}function x(L,C,H,F,G){if(!(E.ttlMs<=0||E.memoryMaxEntries<1)){for(const[K,p]of v)Math.min(p.entry.expiresAt,p.entry.cachedAt+E.ttlMs)<=t()&&v.delete(K);for(v.delete(L);v.size>=Math.floor(E.memoryMaxEntries);){const K=v.keys().next();if(K.done)break;v.delete(K.value)}v.set(L,{entry:C,value:H,epoch:F,persistent:G})}}async function M(L,C,H,F){const G={namespace:y,codecVersion:b.version,scopeIds:C,key:L.key},K=JSON.stringify(G);let p=[],R=T(C);if(R)try{p=await e.store.readRevisions(C,y)}catch{R=!1,d(y,"storage_error")}_(F.signal,C,H);async function B(){if(!R)return!0;try{return Jc(p,await e.store.readRevisions(C,y))}catch{return R=!1,d(y,"storage_error"),!1}}const Q=v.get(K);if(E.ttlMs>0&&Q&&Q.epoch===H&&N(Q.entry,G,p)&&Q.persistent===R&&await B())return _(F.signal,C,H),d(y,"memory_hit"),Q.value;if(v.delete(K),R){let ie,ue;try{ie=await e.store.read(G,E.maxEntryBytes),ie&&N(ie,G,p)?ue=b.decode(ie.payload):ie=void 0}catch{ie=void 0,d(y,"storage_error")}if(_(F.signal,C,H),ie&&await B())return _(F.signal,C,H),x(K,ie,ue,H,!0),d(y,"disk_hit"),ue}d(y,"miss");const X=b.validate(await L.load(F.signal));_(F.signal,C,H);const ne=b.clone(X);if(!await B()&&R)throw mr();if(_(F.signal,C,H),E.ttlMs>0){const ie=t();let ue;try{ue=b.encode(ne)}catch{return ne}const we={envelopeVersion:1,address:G,revisions:R?p:[],cachedAt:ie,expiresAt:ie+E.ttlMs,payload:ue};if(R&&ue.byteLength<=E.maxEntryBytes){let he=!0,ge=!1;try{he=await e.store.publish(we,E),ge=he}catch{d(y,"storage_error")}if(_(F.signal,C,H),!he)throw mr();ge&&d(y,"published")}_(F.signal,C,H),x(K,we,ne,H,R)}return ne}async function S(L){if(c||D||L.signal?.aborted)return Promise.reject(mr());const C=u(L.scope),H=l(C,y);let F;if(T(C)){const R=new AbortController;A.set(R,C);const B=()=>R.abort();L.signal?.addEventListener("abort",B,{once:!0});let Q=()=>{};try{F=await Promise.race([e.store.readRevisions(C,y),new Promise((X,ne)=>{const ie=()=>ne(mr());R.signal.addEventListener("abort",ie,{once:!0}),Q=()=>R.signal.removeEventListener("abort",ie)})])}catch{R.signal.aborted||d(y,"storage_error")}finally{Q(),A.delete(R),L.signal?.removeEventListener("abort",B)}}_(L.signal??new AbortController().signal,C,H);const G=JSON.stringify([C,L.key,H,F]);let K=j.get(G);if(K?.controller.signal.aborted&&(K=void 0),!K){const R=new AbortController;K={ids:C,controller:R,waiters:0,promise:Promise.resolve(void 0)};const B=K;B.promise=M(L,C,H,R).finally(()=>{j.get(G)===B&&j.delete(G)}),j.set(G,B)}const p=K;return p.waiters+=1,new Promise((R,B)=>{let Q=!1;function X(ie){Q||(Q=!0,L.signal?.removeEventListener("abort",ne),p.controller.signal.removeEventListener("abort",ne),p.waiters-=1,p.waiters===0&&p.controller.abort(),ie())}function ne(){X(()=>B(mr()))}L.signal?.addEventListener("abort",ne,{once:!0}),p.controller.signal.addEventListener("abort",ne,{once:!0}),p.promise.then(ie=>X(()=>{try{_(L.signal??new AbortController().signal,C,H),R(b.clone(ie))}catch(ue){B(ue)}}),ie=>X(()=>B(ie)))})}function O(L,C){if(C&&C!==y)return;const H=F=>L.every((G,K)=>F[K]===G);for(const[F,G]of v)H(G.entry.address.scopeIds)&&v.delete(F);for(const[F,G]of j)H(G.ids)&&(G.controller.abort(),j.delete(F));for(const[F,G]of A)H(G)&&F.abort()}function z(){if(!D){D=!0,v.clear();for(const L of A.keys())L.abort();A.clear();for(const L of j.values())L.controller.abort();j.clear(),s.delete(z),a.delete(O),o.get(y)?.cache===U&&o.delete(y)}}const U={read:S,invalidateScope:L=>h(L,y),dispose:z};return s.add(z),a.add(O),o.set(y,{definition:{namespace:y,codec:b,policy:E},sourceCodec:g.codec,cache:U}),U}return{createScope(g,I){if(c||!g)throw new Error("Invalid runtime cache scope");const E=Object.freeze({});return r.set(E,[...I?u(I):[],g]),E},register:m,invalidateScope:g=>h(g),dispose(){if(!c){c=!0;for(const g of[...s])g();o.clear(),n.clear(),i.clear()}}}}function ew(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 tw=".hb-runtime-cache-v1",rw=1e3,Ko=64*1024,hr=1e3,nw=2048,Zr=32*1024*1024,iw=1024,ci=new TextEncoder,Xc=new TextDecoder("utf-8",{fatal:!0});function Kr(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function qn(e){const t=await globalThis.crypto.subtle.digest("SHA-256",ci.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function ht(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ed(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function ow(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function td(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function sw(e,t){const r=e.sandbox.directory(tw),n=r.directory("revisions"),i=r.directory("entries");for(const M of[r,n,i,i.directory("capability-check")])td(M,["directory","file","create","stat","list","remove"]),td(M.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(M){d=M,o.abort(),t.signal.removeEventListener("abort",s)}function f(M){if(ow(M))throw u(M),M}function l(){if(d)throw d;if(a.signal.aborted)throw Kr()}function h(M,S=a.signal){const O=c.then(()=>{if(S.aborted)throw d??Kr();return l(),M()},()=>{if(S.aborted)throw d??Kr();return l(),M()}).catch(C=>{throw f(C),C});if(c=O.catch(()=>{}),S.aborted)return Promise.reject(d??Kr());let z=()=>{};const U=new Promise((C,H)=>{const F=()=>H(d??Kr());S.addEventListener("abort",F,{once:!0}),z=()=>S.removeEventListener("abort",F)}),L=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},rw);return Promise.race([O,U]).finally(()=>{clearTimeout(L),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 g(M,S){const O=n.file(`${await qn([M,S??null])}.revision`);await E(O);let z=!1;try{await O.create({recursive:!1,exclusive:!0},a),z=!0}catch(C){f(C),l()}if(z){const C=ed();return await O.write(ci.encode(C),a),l(),C}const U=await O.stat(a);if(U.size<1||U.size>128)throw new Error("缓存 revision 文件损坏");const L=Xc.decode(await O.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(L))throw new Error("缓存 revision 文件损坏");return l(),L}async function I(M){const S=await M.list({limit:hr},a);if(S.length>=hr)throw new Error("缓存目录超过治理上限");return S}async function E(M){try{await M.stat(a);return}catch(O){if(!Qn(O))throw O}if((await I(n)).length>=hr-1)throw new Error("缓存 metadata 超过治理上限")}async function b(M,S){await m();const O=[];for(let z=0;z<M.length;z+=1){const U=M.slice(0,z+1);O.push(await g(U),await g(U,S))}return O}async function y(M){return r.directory(`entries/${await qn([M.namespace,M.codecVersion,M.scopeIds])}`)}async function v(M){return(await y(M)).file(`${await qn(M.key)}.cache`)}async function j(M,S){const O=await M.stat(a);if(O.size<5||O.size>S+Ko+4)throw new Error("缓存条目超过大小限制");const z=await M.read(a);if(l(),z.length!==O.size)throw new Error("缓存条目读取不完整");const U=new DataView(z.buffer,z.byteOffset,z.byteLength).getUint32(0);if(U<1||U>Ko||U+4>z.length)throw new Error("缓存信封损坏");const L=JSON.parse(Xc.decode(z.subarray(4,U+4))),C=z.slice(U+4);if(L.envelopeVersion!==1||!L.address||!Array.isArray(L.address.scopeIds)||!L.address.scopeIds.every(H=>typeof H=="string")||typeof L.address.namespace!="string"||typeof L.address.codecVersion!="string"||typeof L.address.key!="string"||!Array.isArray(L.revisions)||L.revisions.length!==L.address.scopeIds.length*2||!L.revisions.every(H=>typeof H=="string"&&H.length>0)||!Number.isSafeInteger(L.cachedAt)||!Number.isSafeInteger(L.expiresAt)||L.cachedAt<0||L.expiresAt<=L.cachedAt||L.payloadBytes!==C.length||C.length>S)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:L.address,revisions:L.revisions,cachedAt:L.cachedAt,expiresAt:L.expiresAt,payload:C}}async function A(M){if(!M.remove)throw new Error("Host 不支持缓存文件删除");await M.remove(a)}async function D(M){try{if((await M.file.stat(a)).size!==M.size)return!1;const S=await j(M.file,Zr);return!ht(S.address,M.entry.address)||!ht(S.revisions,M.entry.revisions)||S.cachedAt!==M.entry.cachedAt||S.expiresAt!==M.entry.expiresAt||!ht(await _(S.payload),await _(M.entry.payload))?!1:(await A(M.file),!0)}catch(S){if(Qn(S))return!0;throw S}}async function _(M){const S=await globalThis.crypto.subtle.digest("SHA-256",M);return Array.from(new Uint8Array(S),O=>O.toString(16).padStart(2,"0")).join("")}async function T(){const M=await I(n);let S=0;for(const L of M)if(L.kind==="file"&&(S+=(await L.stat(a)).size,S>Zr))throw new Error("缓存扫描超过字节上限");const O=[];let z=0,U=S;for(const L of await I(i)){if(L.kind!=="directory")throw new Error("缓存目录结构损坏");for(const C of await I(L)){if(C.kind!=="file"||++z>nw)throw new Error("缓存文件超过治理上限");const H=(await C.stat(a)).size;if(U+=H,U>Zr)throw new Error("缓存扫描超过字节上限");try{const F=await j(C,Zr);O.push({file:C,entry:F,size:(await C.stat(a)).size,bucketName:L.name})}catch(F){f(F),l(),Qn(F)||await A(C)}}}return{entries:O,metadataBytes:S}}async function N(){for(const M of await I(i))if(M.kind==="directory"&&M.remove&&(await I(M)).length===0)try{await M.remove({recursive:!1},a)}catch(S){f(S),l()}}function x(M){const{payload:S,...O}=M,z=ci.encode(JSON.stringify({...O,payloadBytes:S.length}));if(z.length>Ko)throw new Error("缓存信封过大");const U=new Uint8Array(4+z.length+S.length);return new DataView(U.buffer).setUint32(0,z.length),U.set(z,4),U.set(S,z.length+4),U}return{readRevisions:(M,S)=>h(()=>b(M,S)),read:(M,S)=>h(async()=>{l();const O=await v(M);let z;try{z=await j(O,S)}catch(U){if(l(),Qn(U))return;throw U}if(!(!ht(z.address,M)||z.expiresAt<=Date.now())&&ht(z.revisions,await b(M.scopeIds,M.namespace)))return z}),publish:(M,S)=>h(async()=>{l();const{address:O}=M;if(!ht(M.revisions,await b(O.scopeIds,O.namespace)))return!1;const z=x(M);if(M.payload.length>S.maxEntryBytes||z.length>S.diskMaxBytes||S.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await m();const U=await y(O),L=await v(O),C=await T(),H=[],F=new Map;for(const p of C.entries){if(p.bucketName===U.name&&p.file.name===L.name)continue;const R=JSON.stringify([p.entry.address.scopeIds,p.entry.address.namespace]);let B=F.get(R);if(B||(B=await b(p.entry.address.scopeIds,p.entry.address.namespace),F.set(R,B)),p.entry.expiresAt<=Date.now()||!ht(p.entry.revisions,B)){if(!await D(p))throw new Error("缓存治理期间条目已变化")}else H.push(p)}H.sort((p,R)=>p.entry.cachedAt-R.entry.cachedAt);function G(){const p=H.filter(R=>R.bucketName===U.name);return H.length+1>iw||z.length+C.metadataBytes+H.reduce((R,B)=>R+B.size,0)>Zr||p.length+1>Math.min(S.diskMaxEntries,hr-1)||z.length+p.reduce((R,B)=>R+B.size,0)>S.diskMaxBytes}for(;G();){const p=H.filter(Q=>Q.bucketName===U.name),B=p.length+1>Math.min(S.diskMaxEntries,hr-1)||z.length+p.reduce((Q,X)=>Q+X.size,0)>S.diskMaxBytes?p[0]:H[0];if(!B||!await D(B))throw new Error("缓存容量不足或条目已变化");H.splice(H.indexOf(B),1)}await N();const K=await I(i);if(!K.some(p=>p.name===U.name)&&K.length>=hr-1)throw new Error("缓存目录超过治理上限");if(await U.create({recursive:!0,exclusive:!1},a),!ht(M.revisions,await b(O.scopeIds,O.namespace)))return!1;try{await L.create({recursive:!1,exclusive:!0},a)}catch(p){f(p),await L.stat(a)}return await L.write(z,a),l(),ht(M.revisions,await b(O.scopeIds,O.namespace))}),invalidate:(M,S)=>h(async()=>{await m();const O=n.file(`${await qn([M,S??null])}.revision`);await E(O);try{await O.create({recursive:!1,exclusive:!0},a)}catch(z){f(z),await O.stat(a)}await O.write(ci.encode(ed()),a),l();try{const{entries:z}=await T();for(const U of z){if(S!==void 0&&U.entry.address.namespace!==S||!M.every((C,H)=>U.entry.address.scopeIds[H]===C))continue;const L=await b(U.entry.address.scopeIds,U.entry.address.namespace);ht(U.entry.revisions,L)||await D(U)}await N()}catch(z){f(z),l()}})}}function Qn(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const aw="RATE_LIMITED_BY_RUNTIME",cw="RATE_LIMITED",cf=20,df=40,uf=150,lf=20,ff=1e4,mf=45e3,hf=1,dw=300*1e3,uw=64;function gr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function lw(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function fw(e={}){const t=e.now??Date.now,r=lw(e.coalesceWindowMs,uf),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,gr(e.budget?.ratePerSecond,cf)),burst:Math.max(1,Math.floor(gr(e.budget?.burst,df)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(gr(e.loopDetection?.maxCalls,lf))),windowMs:Math.max(1,Math.floor(gr(e.loopDetection?.windowMs,ff)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(gr(e.circuitBreaker?.failureThreshold,hf))),openMs:Math.max(1,Math.floor(gr(e.circuitBreaker?.openMs,mf)))},s=new Map,a=new Map,c=new Set,d=new Map,u=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},f={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let l=!1;function h(D){try{e.onReport?.(D)}catch{}}function m(D,_){if(!i)return{exceeded:!1,count:0};const T=a.get(D)??[],N=_-i.windowMs;let x=0;for(;x<T.length&&T[x]<=N;)x+=1;x>0&&T.splice(0,x);const M=T.length>=i.maxCalls;return M||(T.push(_),T.length>i.maxCalls+1&&T.splice(0,T.length-(i.maxCalls+1))),a.set(D,T),{exceeded:M,count:T.length}}function g(D){if(!n)return!0;const _=Math.max(0,D-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+_*n.ratePerSecond),u.updatedAt=D,u.tokens<1?!1:(u.tokens-=1,!0)}function I(D){if(!n)return 0;const _=Math.max(0,D-u.updatedAt)/1e3,T=Math.min(n.burst,u.tokens+_*n.ratePerSecond);return Math.max(0,Math.ceil((1-T)/n.ratePerSecond*1e3))}function E(D,_,T,N,x){if(!o)return;const M=d.get(_),S=(M?.open?0:M?.failures??0)+1;if(S<o.failureThreshold){d.set(_,{open:!1,openedAt:0,openMs:0,failures:S});return}const O=Math.min(Math.max(o.openMs,N),dw);d.set(_,{open:!0,openedAt:x,openMs:O,failures:S}),f.circuitOpened+=1,h({type:"circuit_opened",capability:D,endpointId:_,status:T,openMs:O,timestamp:x})}function b(D){const _=d.get(D);_&&!_.open&&d.delete(D)}function y(D){for(const[_,T]of s)!T.pending&&T.expiresAt<=D&&s.delete(_);for(;s.size>=uw;){const _=[...s].find(([,T])=>!T.pending);if(!_)break;s.delete(_[0])}}function v(D,_){if(D===void 0)return;const T=s.get(D);T?.promise===_&&(T.pending=!1)}function j(D,_){if(D===void 0)return;s.get(D)?.promise===_&&s.delete(D)}async function A(D){if(l)return D.load();const _=t();if(o){const M=d.get(D.endpointId);if(M?.open){const S=M.openedAt+M.openMs-_;if(S>0)throw f.circuitRejected+=1,h({type:"circuit_rejected",capability:D.capability,endpointId:D.endpointId,retryAfterMs:S,timestamp:_}),gw("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:D.endpointId,retryAfterMs:S});d.delete(D.endpointId)}}const T=m(D.endpointId,_);T.exceeded&&i?c.has(D.endpointId)||(c.add(D.endpointId),h({type:"loop_detected",capability:D.capability,endpointId:D.endpointId,count:T.count,windowMs:i.windowMs,timestamp:_})):c.delete(D.endpointId);const N=r>0?D.coalesceKey:void 0;if(N!==void 0){const M=s.get(N);if(M&&(M.pending||M.expiresAt>_))return f.coalesced+=1,h({type:"coalesced",capability:D.capability,endpointId:D.endpointId,timestamp:_}),M.promise;M&&s.delete(N)}if(T.exceeded&&i)throw f.loopRejected+=1,rd("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:D.capability,endpointId:D.endpointId,count:T.count,windowMs:i.windowMs});if(!g(_)){f.budgetRejected+=1;const M=I(_);throw h({type:"budget_exhausted",capability:D.capability,endpointId:D.endpointId,retryAfterMs:M,timestamp:_}),rd("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:D.capability,endpointId:D.endpointId,retryAfterMs:M})}N!==void 0&&y(_);const x=D.load().then(M=>(v(N,x),b(D.endpointId),M),M=>{j(N,x);const S=mw(M);throw S!==void 0&&E(D.capability,D.endpointId,S,hw(M),_),M});return N!==void 0&&s.set(N,{endpointId:D.endpointId,promise:x,expiresAt:_+r,pending:!0}),x}return{execute:A,invalidateCoalescing(D){if(D===void 0){s.clear();return}for(const[_,T]of s)D.includes(T.endpointId)&&s.delete(_)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,D])=>D.open).map(([D])=>D)}},dispose(){l||(l=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function mw(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 hw(e){if(typeof e!="object"||e===null)return 0;const t=e.retryAfterMs;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function rd(e,t){return{code:aw,message:e,data:t}}function gw(e,t){return{code:cw,message:e,data:t}}const gf=3e4,pf=6e4,Zs=1440*60*1e3;function pw(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??gf)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??pf)):0,steamGameListTtlMs:t?yw(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:cf,burst:df},coalesceWindowMs:r?.coalesceWindowMs??uf,loopDetection:r?.loopDetection??{maxCalls:lf,windowMs:ff},circuitBreaker:r?.circuitBreaker??{failureThreshold:hf,openMs:mf}}}}function yw(e){return e===void 0||!Number.isFinite(e)?Zs:Math.max(0,Math.floor(e))}function ww(e){return typeof e=="object"&&e!==null}function Te(e,t){const r=e.data;if(!ww(r)||typeof r.status!="string")throw new Error(t);return r}const yf={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Ew={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 Ln(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Iw(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function _w(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=Iw(r.consent_challenge)),{...t,result:n}}const Aw={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=>({...Ln(e.runtimeContext),challenge:e.challenge}),parse:e=>Te(e,"小程序授权取消接口响应异常")},Dw={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=>Ln(e.runtimeContext),parse:e=>Te(e,"小程序授权撤销接口响应异常")},bw={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=>Ln(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}:{}}}}},Mw={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=>({...Ln(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>_w(e)},Sw={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=>({...Ln(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}}}},Nw=64;function wf(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??Nw)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(f){for(const[l,h]of i)h.expiresAt<=f&&i.delete(l)}function d(f,l,h){if(a||t<=0||h!==s)return;const m=n();for(c(m),i.delete(f);i.size>=r;){const g=i.keys().next();if(g.done)break;i.delete(g.value)}i.set(f,{expiresAt:m+t,value:l})}function u(f,l){if(a)return l();if(t>0){const I=i.get(f);if(I&&I.expiresAt>n())return Promise.resolve(I.value);I&&i.delete(f)}const h=o.get(f);if(h)return h;const m=s,g=l().then(I=>(d(f,I,m),I)).finally(()=>{o.get(f)===g&&o.delete(f)});return o.set(f,g),g}return{read:u,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function Tw(e,t){return t?e?"server":"local":"legacy"}function vw(e,t){if(e==="local")throw w("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const Ow=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],kw=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Pw=/authorization|cookie|pkey|password|secret|token/i,Ef=/authorization|cookie|pkey|token|password|secret/i;function gt(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Rw(e){for(const t of Object.keys(e))if(!kw.has(t))throw new Le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of Ow)if(Object.prototype.hasOwnProperty.call(e,t)&>(e,t)!==void 0)throw new Le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(gt(e,"bodyEncoding")!==void 0&>(e,"bodyEncoding")!=="json"&>(e,"bodyEncoding")!=="form")throw new Le("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(gt(e,"failurePresentation")!==void 0&>(e,"failurePresentation")!=="none")throw new Le("endpoint failurePresentation 必须为 none");if(gt(e,"auth")!==void 0&>(e,"auth")!=="none"&>(e,"auth")!=="optional"&>(e,"auth")!=="required")throw new Le("endpoint auth 必须为 none、optional 或 required")}function io(e){if(Array.isArray(e))return e.map(io);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Pw.test(n)||(r[n]=io(i));return r}function nd(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Ef.test(r)||(t[r]=n);return t}function Cw(e){if(!e)return;const t=Object.keys(e).find(r=>Ef.test(r));if(t)throw new Le(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Un extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;retryAfterMs;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,Object.defineProperty(this,"responseData",{value:t.responseData,enumerable:!1}),t.retryAfterMs!==void 0&&(this.retryAfterMs=t.retryAfterMs),Object.setPrototypeOf(this,new.target.prototype)}}const id=1440*60*1e3,Lw=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function Uw(e,t=Date.now){if(!e)return;const r=Object.entries(e).find(([s])=>s.trim().toLowerCase()==="retry-after")?.[1];if(typeof r!="string"||!r.trim())return;const n=r.trim();if(/^\d+$/.test(n)){const s=Number(n)*1e3;return s>0?Math.min(s,id):void 0}if(!Lw.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,id):void 0}function xw(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 If(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class Cr extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,If(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class xn extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,If(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function jw(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:io(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:nd(o),method:e.method,metadata:{endpointId:e.id},query:io(n),timeout:e.timeout,url:r},data:a.data,headers:nd(a.headers)||{},status:a.status,statusText:a.statusText}}async function Ro(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(Rw(t),typeof t.id!="string"||!t.id)throw new Le("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new Le("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new Le("endpoint path 必须为非空字符串");const o=t.query?await t.query(r):void 0,s=t.body?await t.body(r):void 0,a=t.headers?await t.headers(r):void 0;Cw(a);const c=async()=>{let f;try{f=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...o===void 0?{}:{params:o},...s===void 0?{}:{data:s},...a===void 0?{}:{headers:a},credentials:n.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:n.signal,...n.miniProgramDetail===void 0?{}:{miniProgramDetail:n.miniProgramDetail}})}catch(h){throw h instanceof Le?h:new Cr({endpointId:t.id,cause:h})}if(f.status<200||f.status>=300)throw new Un({endpointId:t.id,status:f.status,responseData:f.data,retryAfterMs:Uw(f.headers)});const l=jw(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(l,r)}catch(h){throw new xn({endpointId:t.id,cause:h})}return l.data},d=n.gate;if(!d)return c();const u=xw(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const zw=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),Bw=new Set(Pr),ec="steam_account",_f=new Set(Pr.filter(e=>e!==ec)),Hw=1e3;function Fw(e){const t=new Set,r=wf({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??gf))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??Tw(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 w("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let C;try{C=await e.authorizationContext.get(e.operationContext)}catch(F){throw Js(F)?Jo(F.code,F.message,F):Jo("REQUEST_FAILED","读取 Runtime auth context 失败",F)}if(C.steamAccount!==c||C.userDataMode!==d)throw w("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const H=C.token.trim();if(!H)throw w("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:H}}const h=e.account.onChange(C=>{if(m(),g("heybox_app_login_change",C?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),C&&e.account.getAccountKey){const H=i;j().then(F=>{!o&&i===H&&g("heybox_app_login_change",F)}).catch(()=>{})}});function m(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function g(C,H){C==="user_info_authorization_change"&&Yw(H)&&r.invalidate();for(const F of t)try{F(C,H)}catch{}}function I(){const C=e.identity.get()?.miniProgramId?.trim();if(!C)throw w("INVALID_STATE","当前能力缺少 canonical 小程序身份");return C}function E(){if(o||e.operationContext.signal.aborted)throw w("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function b(){E();let C;try{C=await e.account.getCurrentUserId(e.operationContext)}catch(H){throw cd(H,e.operationContext.signal,"读取小黑盒账号失败")}return typeof C=="string"&&C.trim()?C.trim():void 0}async function y(C,H){const F=await b();if(i!==H||F!==C)throw w("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function v(C,H,F=I()){if(!e.account.getAccountKey)throw w("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let G;try{G=await e.account.getAccountKey(F,C,e.operationContext)}catch{throw E(),w("REQUEST_FAILED","读取本地账号标识失败")}if(await y(C,H),I()!==F)throw w("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof G!="string"||!G.trim())throw w("INVALID_RESPONSE","Host 返回了无效的账号标识");return G}async function j(){const C=I(),H=i,F=await b();if(E(),i!==H)throw w("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return F?{isHeyboxAppLoggedIn:!0,accountKey:await v(F,H,C)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function A(C){E();try{await e.account.ensureAuthenticated({trustedUserGesture:C,reason:"runtime_auth",signal:e.operationContext.signal})}catch(F){throw cd(F,e.operationContext.signal,"小黑盒登录失败")}const H=await b();if(!H)throw w("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return H}async function D(C,H,F=e.operationContext.signal){try{if(F.aborted)throw Ks();return await Qw(Ro(e.network,C,H,{...e.operationContext,credentials:"heybox-session",signal:F,...f?{gate:f}:{}}),F)}catch(G){throw e.operationContext.signal.aborted?w("RUNTIME_DESTROYED","小程序 Runtime 已终止"):G instanceof Le?w("REQUEST_UNSUPPORTED",G.message):G instanceof xn?w("INVALID_RESPONSE","授权接口响应不合法"):G instanceof Cr?w("REQUEST_FAILED","授权请求失败"):G instanceof Un?u&&(G.status===403||G.status===429)?w("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:G.status,...G.retryAfterMs===void 0?{}:{retryAfterMs:G.retryAfterMs}}):w("REQUEST_FAILED",G.message):Js(G)?G:w("REQUEST_FAILED","授权请求失败")}}async function _(C,H){await D(Aw,{runtimeContext:{miniProgramId:C,...await l()},challenge:H}).catch(()=>{})}function T(C){const H=async()=>{const G=sd(e.operationContext.signal);a=G;try{return await C(G.signal)}finally{a===G&&(a=void 0),G.abort()}},F=s.then(H,H);return s=F.then(()=>{},()=>{}),F}async function N(C,H,F,G,K){if(!F)throw await _(C,H.challenge),w("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await _(C,H.challenge),w("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return T(async p=>{await y(G,K);const R=await x(C,H.displayedScopes,p);await y(G,K);let B;try{B=await e.authPresentation.confirmAuthorization({miniProgramId:C,scopes:H.displayedScopes,...R,signal:p})}catch(X){throw e.operationContext.signal.aborted?w("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await y(G,K),await _(C,H.challenge),Jo("REQUEST_FAILED","授权确认界面执行失败",X))}if(await y(G,K),B.status!=="granted")throw await _(C,H.challenge),w("AUTHORIZATION_CANCELLED","用户取消授权");const Q=Gw(B.grantedScopes,H.displayedScopes,c);if(!Q.includes("identity"))throw await _(C,H.challenge),w("AUTHORIZATION_CANCELLED","用户拒绝授权");return Q})}async function x(C,H,F){const G=sd(F),K=setTimeout(()=>G.abort(),Hw);try{const p=qw(e.miniProgramPresentation),[R,B]=await Promise.all([p?Promise.resolve(p):M(C,G.signal),H.includes("profile")?S(G.signal):Promise.resolve(void 0)]);return{...R?{miniProgram:R}:{},...B?{userProfile:B}:{}}}finally{clearTimeout(K),G.abort()}}async function M(C,H){try{const F=e.identity.get()?.version?.trim(),G=await D(Ew,{mini_program_id:C,...F?{miniprogram_version:F}:{}},H),K=pr(G,"小程序公开资料"),p=br(K.name),R=br(K.icon_url);return p||R?{...p?{name:p}:{},...R?{avatarUrl:R}:{}}:void 0}catch{return}}async function S(C){try{const H=await D(yf,void 0,C),F=pr(H,"账号基础信息"),G=br(F.display_username),K=br(F.display_avatar);return G||K?{...G?{nickname:G}:{},...K?{avatar:K}:{}}:void 0}catch{return}}async function O(C,H){if(vw(d,"auth.login"),!c&&C.includes(ec))throw w("INVALID_PARAMS","auth.login 参数不合法");const F=I(),G=await A(H),K=i,p=await D(Mw,{runtimeContext:{miniProgramId:F,...await l()},scopes:C});await y(G,K);const R=pr(p,"小程序登录"),B=ad(R,"loginCode"),Q=ad(R,"consentChallenge");if(B===Q)throw w("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let X;if(B)X=od(R.loginCode,c);else{const ie=$w(R.consentChallenge,c),ue=await N(F,ie,H,G,K);await y(G,K);const we=await D(Sw,{runtimeContext:{miniProgramId:F,...await l()},challenge:ie.challenge,selectedScopes:ue});if(await y(G,K),X=od(pr(we,"小程序登录确认"),c),X.scopes.some(he=>!ue.includes(he)))throw w("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ie of X.scopes)n.add(ie);r.invalidate();const ne=e.account.getAccountKey?await v(G,K,F):void 0;return g("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...ne===void 0?{}:{accountKey:ne}}),g("user_info_authorization_change",Xo(n,c)),{...X,...ne===void 0?{}:{accountKey:ne}}}async function z(C,H){const F=i,G=await D(bw,{runtimeContext:{miniProgramId:H,...await l()}});await y(C,F);const K=Vw(pr(G,"用户本地身份"),c);for(const p of c?Pr:_f)n.add(p);return g("user_info_authorization_change",Xo(n,c)),K}function U(C){E();const H=I(),F=`${C}\0${H}\0${i}\0${c}`;return r.read(F,()=>z(C,H))}async function L(C){if(!C)throw w("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const H=I(),F=i,G=await b();if(!G)throw w("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const K=await D(Dw,{runtimeContext:{miniProgramId:H,...await l()}});await y(G,F),pr(K,"用户授权撤销"),m(),g("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:j,login:O,async confirmGameSaves(C){if(!C)throw w("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw w("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const H=I(),F=await A(C),G=i;await T(async K=>{await y(F,G);const p=await x(H,["identity"],K),R=await e.authPresentation.confirmAuthorization({miniProgramId:H,scopes:["identity","game_saves"],...p,signal:K});if(await y(F,G),R.status!=="granted"||!R.grantedScopes.includes("game_saves")||!R.grantedScopes.includes("identity"))throw w("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:U,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Xo(n,c),revoke:L,onEvent(C){return t.add(C),()=>t.delete(C)},dispose(){o||(o=!0,m(),r.dispose(),h(),t.clear())}}}function Jo(e,t,r){const n=w(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function pr(e,t){if(!re(e))throw w("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":zw.has(r)?r:"REQUEST_FAILED";throw w(n,r)}if(!re(e.result))throw w("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function od(e,t){if(!re(e))throw w("INVALID_RESPONSE","login code 必须是对象");const r=oo(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 w("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function $w(e,t){if(!re(e))throw w("INVALID_RESPONSE","授权 challenge 必须是对象");const r=oo(e.requestedScopes,"challenge requestedScopes",t),n=oo(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 w("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function Vw(e,t){if(!re(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw w("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw w("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 Gw(e,t,r){const n=oo(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw w("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function br(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function qw(e){const t=br(e?.name),r=br(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function sd(e){const t=new AbortController;return e.aborted?t.abort(e.reason):e.addEventListener("abort",()=>t.abort(e.reason),{once:!0,signal:t.signal}),t}function Qw(e,t){return t.aborted?Promise.reject(Ks()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Ks()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Ks(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function oo(e,t,r){const n=r?Bw:_f;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw w("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Xo(e,t){const r=t?Pr:Pr.filter(n=>n!==ec);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function ad(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Yw(e){return re(e)?Object.values(e).some(t=>t==="denied"):!1}function Js(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}function cd(e,t,r){return t.aborted?w("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Js(e)?e:w("REQUEST_FAILED",r)}const Ww=new Set(Pr);function Zw(e){return{[Di]:async t=>{if(t!==void 0)throw w("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[bi]:async(t,r)=>e.authorization.login(Kw(t),r.trustedUserGesture)}}function Kw(e){if(e===void 0)return["identity"];if(!re(e)||Object.keys(e).some(t=>t!=="scopes"))throw dd();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Ww.has(t))||new Set(e.scopes).size!==e.scopes.length)throw dd();return[...e.scopes]}function dd(){return w("INVALID_PARAMS","auth.login 参数不合法")}const Jw={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,"排行榜记录删除接口响应异常")}},Xw={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,"当前排行榜记录接口响应异常")}},eE={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,"排行榜信息接口响应异常")}},tE={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,"排行榜列表接口响应异常")}},rE={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,"排行榜提交接口响应异常")}},nE={1:"Canceled",2:"Unknown",3:"InvalidArgument",4:"DeadlineExceeded",5:"NotFound",6:"AlreadyExists",7:"PermissionDenied",8:"ResourceExhausted",9:"FailedPrecondition",10:"Aborted",11:"OutOfRange",12:"Unimplemented",13:"Internal",14:"Unavailable",15:"DataLoss",16:"Unauthenticated"};async function Co(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await fe(()=>Ro(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(co(i)||sn(i,"REQUEST_UNSUPPORTED")||sn(i,"RATE_LIMITED")||sn(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof Le)throw ee("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof Cr&&sn(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Un){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw ee("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw ee("UNAUTHORIZED","当前用户未登录");const o=iE(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"||so(o.result)||so(o)||s&&/^[A-Z][A-Z0-9_]+$/.test(s))throw Af(o,e.subject)}throw ee("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof Cr?ao(e.subject):i instanceof xn?be(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):be(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function st(e,t,r){if(!Ie(e)||typeof e.status!="string")throw be(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Af(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw be(`${t} 响应缺少 result`);return e.result}function Lo(e,t){try{return e.onChange(t)}catch(r){if(sn(r,Hl))return()=>{};throw r}}function Af(e,t){if(e.status==="login"||e.status==="relogin")throw ee("UNAUTHORIZED",Mt(e.msg)||"当前用户未登录");if(Ie(e.result)){const i=Mt(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw ee(i,Mt(e.result.message)||Mt(e.msg)||`${t}请求失败`)}const r=so(e.result)??so(e),n=Mt(r?.user_message)||Mt(e.msg)||Mt(r?.developer_message)||`${t}请求失败`;throw r?ee(oE(r),n,{status:e.status,sbe:r}):ee("HEYBOX_API_ERROR",n,{status:e.status})}function iE(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function so(e){return Ie(e)&&Ie(e.sbe)?e.sbe:void 0}function oE(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 nE[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 sn(e,t){return Ie(e)&&e.code===t}function ee(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function be(e){return ee("INVALID_RESPONSE",e)}function ao(e){return ee("REQUEST_FAILED",`${e}请求失败`)}function co(e){return e instanceof Error&&e.name==="AbortError"}const sE="default",Vt="排行榜",aE=/^[A-Za-z0-9_-]{1,64}$/,cE=300*1e3,dE=250,uE=3;class lE{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Lo(t.account,()=>this.invalidateForAccountChange()),t.operationContext.signal.aborted?this.dispose():t.operationContext.signal.addEventListener("abort",this.handleTerminalAbort,{once:!0})}accountGeneration=0;buckets=new Map;inflight=new Map;unsubscribeAccountChange;requestGateContext;disposed=!1;handleTerminalAbort=()=>this.dispose();async submit(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(rE,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=st(i,Nt,Vt);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),es(o,Nt)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Jr("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(tE,{miniProgramId:r,...t}),s=st(o,at,Vt);if(!Ie(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw be(`${at} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw be(`${at} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>es(a,at)),...typeof s.cursor=="string"&&s.cursor?{cursor:s.cursor}:{},hasMore:s.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId(),i=await this.requireCurrentUser(r),o=this.createBucketKey(n,t.key),s=Jr("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(Xw,{miniProgramId:n,...t}),c=st(a,jt,Vt);if(!Ie(c))throw be(`${jt} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:es(c.entry,jt)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Jw,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=st(i,ir,Vt);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Ie(o)||typeof o.deleted!="boolean")throw be(`${ir} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Jr("info"),async()=>{const i=await this.request(eE,{miniProgramId:r,...t}),o=st(i,It,Vt);if(!Ie(o)||typeof o.key!="string"||!aE.test(o.key))throw be(`${It} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw be(`${It} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw be(`${It} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw be(`${It} 返回的 rankLimit 必须是非负整数`);return{key:o.key,order:o.order,rankLimit:o.rank_limit}})}read(t,r,n,i){this.assertUsable();const o=this.getOrCreateBucket(t),s=o?.caches[r],a=s?.get(n);if(a&&a.expiresAt>Date.now())return Promise.resolve(a.value);s?.delete(n);const c=Jr(t,n),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,f=o?.generation,l=i().then(h=>(this.assertAccountGeneration(u),o&&s&&o.generation===f&&(r==="list"?s.size>=dE&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+cE,value:h})),h)).finally(()=>{this.inflight.get(c)?.promise===l&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:l}),l}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=uE)return;const n={generation:0,caches:{list:new Map,current:new Map,info:new Map}};return this.buckets.set(t,n),n}invalidateMutableReads(t){this.invalidateInflight(t);const r=this.buckets.get(t);r&&(r.generation+=1,r.caches.list.clear(),r.caches.current.clear())}invalidateForAccountChange(){this.accountGeneration+=1,this.buckets.clear(),this.inflight.clear()}invalidateInflight(t){for(const[r,n]of this.inflight)n.bucketKey===t&&this.inflight.delete(r)}pruneExpiredBuckets(){const t=Date.now();for(const[r,n]of this.buckets)ud(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){ud(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await fe(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw co(n)?n:ao(Vt)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ee("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ee("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Jr(t,r??sE)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ee("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return Co({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Vt,assertUsable:()=>this.assertUsable()},t,r)}dispose(){this.disposed||(this.disposed=!0,this.accountGeneration+=1,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.buckets.clear(),this.inflight.clear())}assertUsable(){if(pe(this.options.operationContext.signal),this.disposed)throw ee("INVALID_STATE","Cloud capability 已释放")}}function fE(e){return new lE(e)}function es(e,t){if(!Ie(e))throw be(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw be(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw be(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw be(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw be(`${t} 返回的 score 必须是有限数字`);if(!Ie(e.extra))throw be(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw be(`${t} 返回的时间字段必须是有限数字`);return{appUserId:e.app_user_id,createdAt:e.created_at,extra:e.extra,rank:e.rank,ranked:e.ranked,score:e.score,updatedAt:e.updated_at}}function ud(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Jr(...e){return JSON.stringify(e)}const mE={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.delete.post",method:"POST",path:"/user_miniprogram/cloud/storage/delete",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken,key:e.key}},parse(e,t){return Te(e,"云端存储删除接口响应异常")}},ld={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.get.post",method:"POST",path:"/user_miniprogram/cloud/storage/get",body(e){return{key:e.key,runtime_auth_context_token:e.runtimeAuthContextToken}},parse(e,t){return Te(e,"云端存储读取接口响应异常")}},fd={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.keys.post",method:"POST",path:"/user_miniprogram/cloud/storage/keys",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken}},parse(e,t){return Te(e,"云端存储 key 列表接口响应异常")}},hE={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.set.post",method:"POST",path:"/user_miniprogram/cloud/storage/set",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken,key:e.key,value:e.value,expected_version:String(e.expectedVersion),expected_revision:e.expectedRevision}},parse(e,t){return Te(e,"云端存储写入接口响应异常")}},Gt="云端存储",gE=3e4,pE=128,yE=500;class wE{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Lo(t.account,r=>{this.observedUserId=r?.trim()||void 0,this.hasAccountObservation=!0,!(this.boundUserId===void 0||this.boundUserId===this.observedUserId)&&this.invalidateForAccountChange()}),t.operationContext.signal.aborted?this.dispose():t.operationContext.signal.addEventListener("abort",this.handleTerminalAbort,{once:!0})}accountGeneration=0;cache=new Map;inflight=new Map;keyGenerations=new Map;queues=new Map;activeKeys=new Set;timers=new Map;blockedKeys=new Map;unfinished=new Set;disposed=!1;boundScope;boundUserId;observedUserId;hasAccountObservation=!1;unsubscribeAccountChange;requestGateContext;handleTerminalAbort=()=>this.dispose();async getItem(t){const r=this.accountGeneration;await this.requireCurrentUser(r),this.assertAccountGeneration(r);const n=[...this.unfinished].filter(s=>s.key===t).at(-1);if(n)return n.kind==="set"?n.value:void 0;const i=this.keyGenerations.get(t)??0,o=await this.readStored(t,r,!1);return this.assertAccountGeneration(r),(this.keyGenerations.get(t)??0)!==i?this.getItem(t):(this.blockedKeys.delete(t),o.found?o.value:void 0)}setItem(t,r){return this.enqueue("set",t,r)}removeItem(t){return this.enqueue("remove",t,"")}async getKeys(){const t=this.accountGeneration;await this.requireCurrentUser(t),this.assertAccountGeneration(t);const r=st(await this.request(fd,{}),or,Gt);if(this.assertAccountGeneration(t),!Ie(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw be("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"?yE: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(mE,{key:t}),kr,Gt);if(this.assertAccountGeneration(r.generation),!Ie(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw be("删除结果不合法");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 be("云存储版本超出安全整数范围");const o=st(await this.request(hE,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),Or,Gt);if(this.assertAccountGeneration(r.generation),!Ie(o)||o.success!==!0)throw be("云存储写入结果不合法");const s=md({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw be("写入版本凭证不匹配");this.writeCache(t,s)}this.finish(r)}catch(i){if(this.finish(r,i),r.generation===this.accountGeneration){this.cache.delete(t),this.blockedKeys.set(t,i);for(const o of this.queues.get(t)??[])this.finish(o,i);this.queues.delete(t)}}}}finally{this.activeKeys.delete(t),this.queues.get(t)?.length||this.queues.delete(t)}}}async readStored(t,r,n){this.assertAccountGeneration(r);const i=this.cache.get(t);if(i&&(n||i.expiresAt>Date.now()))return i.value;const o=this.inflight.get(t);if(o)return o;const s=this.keyGenerations.get(t)??0,a=this.request(ld,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=md(st(c,vr,Gt));return(this.keyGenerations.get(t)??0)===s&&this.writeCache(t,d),d}).finally(()=>{this.inflight.get(t)===a&&this.inflight.delete(t)});return this.inflight.set(t,a),a}writeCache(t,r){this.cache.delete(t),this.cache.size>=pE&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+gE,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([ld.id,fd.id])}finish(t,r){if(this.unfinished.delete(t)){t.generation===this.accountGeneration&&this.invalidateRead(t.key);for(const n of t.waiters)r===void 0?n.resolve():n.reject(r)}}dispose(){this.disposed||(this.disposed=!0,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.purge(ee("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(ee("UNAUTHORIZED","登录状态已变化,请重试")),this.options.requestGate?.invalidateCoalescing()}purge(t){this.accountGeneration+=1;for(const r of this.timers.values())clearTimeout(r);this.timers.clear();for(const r of[...this.unfinished])this.finish(r,t);this.queues.clear(),this.blockedKeys.clear(),this.cache.clear(),this.inflight.clear(),this.keyGenerations.clear(),this.boundScope=void 0,this.boundUserId=void 0}async requireCurrentUser(t){this.assertAccountGeneration(t);const r=this.readMiniProgramId();let n;try{n=await fe(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw co(o)?o:ao(Gt)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),ee("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),ee("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw ee("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ee("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ee("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw ee("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await fe(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw co(s)?s:ao(Gt)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw ee("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return Co({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Gt,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(pe(this.options.operationContext.signal),this.disposed)throw ee("INVALID_STATE","Cloud capability 已释放")}}function EE(e){return new wE(e)}function md(e){if(!Ie(e))throw be("云存储读取结果必须是对象");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 be("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw be("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const IE=/^[A-Za-z0-9_-]{1,64}$/,hd=20,_E=100,gd=2048,AE=/^[A-Za-z0-9_-]{1,128}$/,pd=16*1024;function DE(e){const t=fE(e),r=EE(e);return{handlers:{[Nt]:async i=>t.submit(bE(i)),[at]:async i=>t.getList(ME(i)),[jt]:async i=>t.getCurrentUserEntry(ts(i,jt)),[ir]:async i=>t.deleteCurrentUserEntry(ts(i,ir)),[It]:async i=>t.getInfo(ts(i,It)),[vr]:async i=>r.getItem(yd(i,vr)),[Or]:async i=>{const{key:o,value:s}=SE(i);return r.setItem(o,s)},[kr]:async i=>r.removeItem(yd(i,kr)),[or]:async i=>(TE(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function bE(e){const t=Gr(e,Nt,!1);if(qr(t,["key","score","extra"],Nt),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{...tc(t.key,Nt),score:t.score,...t.extra===void 0?{}:{extra:vE(t.extra)}}}function ME(e){if(e===void 0)return{limit:hd};const t=Gr(e,at,!0);qr(t,["key","limit","cursor"],at);const r=t.limit===void 0?hd:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>_E)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{...tc(t.key,at),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function ts(e,t){if(e===void 0)return{};const r=Gr(e,t,!0);return qr(r,["key"],t),tc(r.key,t)}function yd(e,t){const r=Gr(e,t,!1);return qr(r,["key"],t),Df(r.key,t)}function SE(e){const t=Or,r=Gr(e,t,!1);qr(r,["key","value"],t);const n=Df(r.key,t);if(typeof r.value!="string")throw Ye("INVALID_PARAMS",`${t} value 必须是字符串`);if(NE(r.value))throw Ye("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>pd)throw Ye("INVALID_PARAMS",`${t} value 不能超过 ${pd} 字节`);return{key:n,value:r.value}}function NE(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 TE(e){const t=Gr(e,or,!0);qr(t,[],or)}function Df(e,t){if(typeof e!="string"||!AE.test(e))throw Ye("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function Gr(e,t,r){if(e===void 0&&r)return{};if(!bf(e))throw Ye("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function qr(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Ye("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function tc(e,t){if(e===void 0)return{};if(typeof e!="string"||!IE.test(e))throw Ye("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function vE(e){if(!bf(e))throw Ye("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw Ye("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw Ye("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>gd)throw Ye("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${gd} 字节`);return e}function bf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ye(e,t){return{code:e,message:t}}const OE={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,"游戏存档接口响应异常")}},kE=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function Xs(e,t=0){return t>64?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e)&&(!Number.isInteger(e)||Number.isSafeInteger(e)):Array.isArray(e)?e.every(r=>Xs(r,t+1)):Ie(e)&&Object.values(e).every(r=>Xs(r,t+1))}function PE(e,t){const r=kE.get(t);if(!r||Ie(e)&&e.status==="unsupported")return{status:"unsupported"};if(Ie(e)&&e.game===r){if(e.status==="empty")return{status:"empty"};if(e.status==="failed"&&["UNAUTHORIZED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED"].includes(String(e.error_code)))throw ee(String(e.error_code),"账号或授权已变化");if(e.status==="ready"&&Ie(e.data)&&Xs(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function Mf(e){const t=new Map,r=new Map,n=c=>c.resource?`hb_runtime_game_save_resource_sync_v1_${[c.miniProgramId,c.userId,c.resource].map(encodeURIComponent).join(":")}`:`hb_runtime_game_save_sync_v1_${[c.miniProgramId,c.userId,c.gameId].map(encodeURIComponent).join(":")}`;async function i(c,d,u){const f=n(c),l=r.get(f)??Promise.resolve();let h;const m=new Promise(I=>{h=I}),g=l.then(()=>m);r.set(f,g);try{return await fe(()=>l,d.signal),pe(d.signal),e?.withLock?await e.withLock(f,u):await u()}finally{h(),r.get(f)===g&&g.then(()=>{r.get(f)===g&&r.delete(f)})}}async function o(c,d,u=!1){const f=n(c);if(!u&&t.has(f)||!e)return t.get(f);try{const l=await fe(()=>e.getRaw(f,d),d.signal);if(!l)return;const h=JSON.parse(l);if(!h||typeof h!="object")return;const m=h;return m.version!==1||m.miniProgramId!==c.miniProgramId||m.userId!==c.userId||m.gameId!==c.gameId||(c.resource?m.resource!==c.resource:typeof m.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(m.accountId))||typeof m.taskId!="string"||(c.resource?m.taskId.length<1||m.taskId.length>128:!/^[1-9][0-9]{0,19}$/.test(m.taskId))?void 0:(u||t.set(f,m),m)}catch(l){if(pe(d.signal),u)throw l;return t.get(f)}}async function s(c,d,u){pe(u.signal);const f=n(c),l=d?{...c,version:1,taskId:d}:void 0;if(t.set(f,l),!!e)try{await fe(()=>e.setRaw(f,l?JSON.stringify(l):"",u),u.signal)}catch{pe(u.signal)}}async function a(c,d,u){await i(c,u,async()=>{const f=n(c),l=t.get(f),h=l?.taskId===d&&l.accountId===c.accountId;let m;try{m=await o(c,u,!0)}catch{pe(u.signal),h&&t.set(f,void 0);return}m?.taskId===d&&m.accountId===c.accountId?(await s(c,void 0,u),l&&!h&&t.set(f,l)):h&&t.set(f,m)})}return{run:i,async get(c,d){const u=await o(c,d);if(u&&u.accountId!==c.accountId){t.delete(n(c));return}return u?.taskId},set:s,remove:a,clear(c){for(const d of t.values())d&&a(d,d.taskId,c).catch(()=>{})}}}const RE=2e3,CE=5*6e4;function LE(e){const t=Mf(e.storage);let r=0,n=!1,i;const o=e.fileDownloads??(e.files&&e.transfer?Ja({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=_=>o?.release(_)??Promise.resolve(),u=new Set;let f=new AbortController,l;const h=()=>{f.abort(),f=new AbortController,l=void 0},m=(_=!0)=>{_&&t.clear(c),r++,h();for(const T of u)T.abort();for(const T of s)d(T).catch(()=>{});s.clear(),a.clear()},g=Lo(e.account,_=>{i&&_!==i&&(m(),i=void 0)}),I=e.authorization.onEvent(()=>m());function E(_,T,N,x){if(b(N),x.signal.aborted||!_.account_id||!e.presentation?.showSteamLoginRequired)return;const M=`${_.account_id}:${_.game_id}:${_.task_id??"sync"}`;if(l!==M){l=M;try{e.presentation.showSteamLoginRequired({userId:T,accountId:_.account_id},Se(e.operationContext,f.signal))}catch{}}}function b(_){if(n||e.operationContext.signal.aborted)throw ee("RUNTIME_DESTROYED","小程序已关闭");if(_!==r)throw ee("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function y(_,T,N){if(b(T),await e.account.getCurrentUserId(N)!==_)throw m(),ee("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");b(T)}async function v(_,T,N,x){if(await y(T,N,x),!e.authorizationContext)throw ee("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const M=await e.authorizationContext.get(x);if(!M.token||M.expiresAt<=Date.now())throw ee("UNAUTHORIZED","小程序运行上下文已过期");const S=await Co({network:e.network,operationContext:x,subject:"游戏存档",assertUsable:()=>b(N),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},OE,{..._,runtime_auth_context_token:M.token});if(await y(T,N,x),S.status==="failed"&&Ie(S.result)&&S.result.error_code==="RECENT_SAVE_AVAILABLE")throw ee("RECENT_SAVE_AVAILABLE",typeof S.msg=="string"&&S.msg?S.msg:"已有近期存档,请直接查询使用");const O=st(S,_.action,"游戏存档");if(!Ie(O))throw ee("INVALID_RESPONSE","存档响应不合法");return O}async function j(_,T,N){const x=UE(_,T),M=r;if(b(M),_==="file"&&(!e.transfer||!e.files))throw ee("METHOD_FORBIDDEN","宿主不支持存档文件读取");const S=new AbortController;u.add(S);let O=!1;const z=_==="sync"?setTimeout(()=>{O=!0,S.abort()},CE):void 0,U=Se(Se(e.operationContext,N.signal),S.signal);try{const L=await e.account.getCurrentUserId(U);if(!L)throw ee("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==L)throw m(),ee("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=L,_==="sync"||_==="parsed"){if(_==="sync"&&h(),!x.account_id){const K=await v({action:"check",game_id:x.game_id},L,M,U);x.account_id=Tn(K.account_id)}if(_==="sync")return await A(x,L,M,U)}const C=await v({action:_,...x},L,M,U);if(_==="list")return xE(C);if(_==="parsed")return PE(C.parsed_data,x.game_id);if(Sf(C.file).fileId!==x.file_id)throw ee("INVALID_RESPONSE","文件标识不匹配");if(!o)throw ee("REQUEST_UNSUPPORTED","宿主不支持存档下载");const F=await o.download(C,async K=>{try{b(M),await v({action:"check",game_id:x.game_id,account_id:x.account_id},L,M,K)}catch(p){const R=Ie(p)?String(p.code):"";throw["RUNTIME_DESTROYED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED","UNAUTHORIZED"].includes(R)?(m(),ee("FILE_ACCESS_REVOKED","游戏存档授权已失效")):p}},U);let G=!1;try{if(await y(L,M,U),b(M),U.signal.aborted)throw ee("DOWNLOAD_CANCELLED","存档下载已取消");const K=e.fileRegistry.registerFile(F,"game-save","read");return s.add(F),a.set(Qa(),{file:F,sizeBytes:o.sizeOf(F)}),G=!0,K}finally{G||await o.release(F)}}catch(L){throw O?ee("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):L}finally{z!==void 0&&clearTimeout(z),u.delete(S)}}async function A(_,T,N,x){const M=e.identity.get()?.miniProgramId;if(!M)throw ee("INVALID_STATE","小程序身份尚未确认");const S={miniProgramId:M,userId:T,gameId:_.game_id,accountId:_.account_id},O=U=>v({action:"status",..._,task_id:U},T,N,x);let z;try{const U=await t.run(S,x,async()=>{await y(T,N,x);const C=await t.get(S,x);if(C){z=C;try{return{taskId:C,status:await O(C)}}catch(F){if(!Ie(F)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(F.code)))throw F;await t.set(S,void 0,x),z=void 0}}const H=await v({action:"sync",..._},T,N,x);return z=Tn(H.task_id),await t.set(S,z,x),await y(T,N,x),{taskId:z,status:void 0}});z=U.taskId;let L=U.status;for(;;){if(b(N),x.signal.aborted)throw ee("REQUEST_CANCELLED","已停止等待存档同步");if(L??=await O(z),L.state==="succeeded"||L.state==="failed"){if(await t.remove(S,z,x),await y(T,N,x),L.state==="succeeded")return{state:"succeeded"};throw ee(L.error_code?uo(L.error_code):"SYNC_FAILED",L.message?uo(L.message):"存档同步失败")}if(L.state!=="syncing"&&L.state!=="uploading")throw ee("INVALID_RESPONSE","同步状态不合法");L=void 0,await jE(RE,x.signal)}}catch(U){if(Ie(U)){const L=String(U.code);L==="STEAM_LOGIN_REQUIRED"&&E({..._,task_id:z},T,N,x),z&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(L)&&await t.remove(S,z,c)}throw U}}return{handlers:{"gameSaves.list":(_,T)=>j("list",_,T),"gameSaves.sync":(_,T)=>j("sync",_,T),"gameSaves.readParsedData":(_,T)=>j("parsed",_,T),"gameSaves.getFile":(_,T)=>j("file",_,T)},diagnostics:{async getSnapshot(){const _=r;return i&&await y(i,_,e.operationContext),b(_),Array.from(a,([T,N])=>({id:T,name:N.file.name,sizeBytes:N.sizeBytes}))},async readFile(_,T){const N=r;b(N);const x=a.get(_);if(!x)throw ee("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const M=Se(e.operationContext,T);M.signal.throwIfAborted();const S=await x.file.read(M);try{return M.signal.throwIfAborted(),b(N),{name:x.file.name,bytes:S}}catch(O){throw S.fill(0),O}}},allowsRead(_,T){return["file.readBytes","file.readText","file.stat","file.exists"].includes(_)&&Ie(T)&&e.fileRegistry.isGameSaveRef(T.target)},dispose(){n||(n=!0,m(!1),g(),I())}}}function UE(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!Ie(t)||Object.keys(t).some(i=>!r.includes(i)))throw ee("INVALID_PARAMS","存档参数不合法");const n=an(t.gameId);if(Number(n)>2147483647)throw ee("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:an(t.accountId)}:{},...e==="file"?{save_id:an(t.saveId),file_id:an(t.fileId)}:{}}}function an(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw ee("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function Tn(e){try{return an(e)}catch{throw ee("INVALID_RESPONSE","服务端存档标识无效")}}function uo(e){if(typeof e!="string")throw ee("INVALID_RESPONSE","服务端存档字段无效");return e}function ea(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw ee("INVALID_RESPONSE","服务端存档数值无效");return e}function Sf(e){if(!Ie(e))throw ee("INVALID_RESPONSE","存档文件信息无效");return{fileId:Tn(e.file_id),name:uo(e.name),originalPath:uo(e.original_path),sizeBytes:ea(e.size_bytes),modifiedAt:ea(e.modified_at)}}function xE(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw ee("INVALID_RESPONSE","存档列表无效");return{accountId:Tn(e.account_id),saves:e.saves.map(t=>{if(!Ie(t)||!Array.isArray(t.files)||t.files.length>200)throw ee("INVALID_RESPONSE","存档文件列表无效");return{saveId:Tn(t.save_id),createdAt:ea(t.created_at),files:t.files.map(Sf)}})}}function jE(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(o),t.removeEventListener("abort",i),n(ee("REQUEST_CANCELLED","已停止等待存档同步"))},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}const zE=new Set(["stdio","attachments","notifications"]),Nf=new Set(["windows-x64","macos-arm64"]),BE=new Set(["unsigned","valid","invalid","unknown"]),HE=/^[a-f0-9]{64}$/,FE=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),$E=new Set(Ol),VE=new Set([...Ol,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Tf=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 GE(e){const t=async(n,i,o,s)=>{const a=qE(n);try{Et(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Et(i.signal),c}catch(c){throw ra(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw w("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw w("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>QE(d,i)).catch(d=>{throw ra(d)});Et(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Et(o.signal),c.status!=="granted")throw w("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[wo]:(n,i)=>t(n,i,async(o,s)=>ta(await e.companion.getInfo(o,s),o)),[Eo]:(n,i)=>t(n,i,async(o,s)=>wd(await e.companion.getPreparationStatus(o,s))),[Io]:(n,i)=>t(n,i,async(o,s)=>{const a=wd(await e.companion.getPreparationStatus(o,s));return Et(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Et(i.signal),ta(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(Of(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[_o]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Ao]:(n,i)=>t(n,i,async(o,s)=>Ed(await e.companion.getActiveSession(o,s),o)),[Do]:(n,i)=>t(n,i,async(o,s)=>{const a=Ed(await e.companion.getActiveSession(o,s),o);return Et(i.signal),a||(await r("launch",o,i),Et(i.signal),kf(await e.companion.launch(o,s),o))}),[bo]:(n,i)=>yr(n,i,e,"write"),[Mo]:(n,i)=>yr(n,i,e,"closeStdin"),[So]:(n,i)=>yr(n,i,e,"terminate"),[No]:(n,i)=>yr(n,i,e,"ackOutput"),[To]:async(n,i)=>{const o=await yr(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[vo]:(n,i)=>yr(n,i,e,"showNotification")}}function qE(e){if(!re(e)||typeof e.alias!="string"||!rg.test(e.alias))throw w("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Et(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function yr(e,t,r,n){if(!re(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw w("INVALID_PARAMS","Companion Session controller 不合法");try{Et(t.signal);const i=await r.companion[n](YE(e,n),{...r.operationContext,signal:t.signal});return Et(t.signal),i}catch(i){throw ra(i)}}function dt(){throw w("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function vf(e){return!Array.isArray(e)||e.some(t=>!zE.has(t))?dt():Object.freeze([...new Set(e)])}function ta(e,t){return!re(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Nf.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!BE.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:vf(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function QE(e,t){const r=ta(e,t);return!re(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!HE.test(e.sha256)?dt():Object.freeze({...r,sha256:e.sha256})}function Of(e){return re(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):dt():dt()}function wd(e){return re(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Of(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&re(e.error)&&typeof e.error.code=="string"&&$E.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:Tf[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):dt():dt()}function kf(e,t){return!re(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Nf.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:vf(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Ed(e,t){return e===void 0?void 0:kf(e,t)}function YE(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Dl(r.data))throw w("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 w("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw w("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw w("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function WE(e){return!re(e)||!FE.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 ZE(e){if(!re(e)||!re(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,r=t.sessionId;if(e.type==="companion.session.output")return!Number.isSafeInteger(t.controllerGeneration)||Number(t.controllerGeneration)<0||t.stream!=="stdout"&&t.stream!=="stderr"||!Number.isSafeInteger(t.sequence)||Number(t.sequence)<0||!Dl(t.data)?void 0:{type:e.type,payload:{sessionId:r,controllerGeneration:t.controllerGeneration,stream:t.stream,sequence:t.sequence,data:new Uint8Array(t.data)}};if(e.type==="companion.session.exit")try{return{type:e.type,payload:{sessionId:r,exit:WE(t.exit)}}}catch{return}if(e.type==="companion.session.ownershipLost"&&Number.isSafeInteger(t.controllerGeneration)&&Number(t.controllerGeneration)>=0)return{type:e.type,payload:{sessionId:r,controllerGeneration:t.controllerGeneration}}}function ra(e,t){return re(e)&&typeof e.code=="string"&&VE.has(e.code)?w(e.code,Tf[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&re(e)&&e.name==="AbortError"?w(t,"Companion 准备已取消"):w("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Id=5e3,_d=1e4;function Ge(e){throw{code:"INVALID_PARAMS",message:e}}function rc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pf(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Ge(`${r} 不支持字段: ${n.join(", ")}`)}function KE(e){if(e===void 0)return{intensity:"light",delay:0};if(!rc(e))return Ge("device.vibrate 参数必须是对象");Pf(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return Ge("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Id?Ge(`device.vibrate delay 必须是 0-${Id} 的整数毫秒`):{intensity:r,delay:n}}function JE(e){return rc(e)?(Pf(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?Ge("device.setClipboard text 必须是非空字符串"):e.text.length>_d?Ge(`device.setClipboard text 不能超过 ${_d} 字符`):{text:e.text}):Ge("device.setClipboard 参数必须是对象")}function XE(e){return typeof e=="string"?e.trim()?e:Ge("device.executeProtocol 协议字符串不能为空"):rc(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?Ge("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(na(e,new Set),e):Ge("device.executeProtocol 参数必须是协议字符串或协议对象")}function na(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||Ge("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":Ge("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":Ge(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&Ge("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)na(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&Ge("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))na(i,t);t.delete(r)}function eI(e){return{[Ki]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.vibrate(KE(t),n),n.signal)},[Ji]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.setClipboard(JE(t),n),n.signal)},[Xi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal);const i=XE(t);await fe(()=>e.protocol.invoke(i,n),n.signal)}}}const Ad=1e3,tI=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function rI(e){const t=r=>Se(e.operationContext,r.signal);return{files:{[zi]:async(r,n)=>{rs(n);const i=ns(e.picker),o=nI(r),s=await Ze(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Bi]:async(r,n)=>{rs(n);const i=ns(e.picker),o=iI(r),s=await Ze(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[Hi]:async(r,n)=>{rs(n);const i=ns(e.picker),o=oI(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:{[En]:async(r,n)=>{const i=Xe(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);wr(o.mode),await Ze(()=>o.create(Dd(i),t(n)))},[In]:async(r,n)=>{const i=Xe(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),wr(o.handle.mode),!o.handle.remove)throw tt(In);await Ze(()=>o.handle.remove(t(n)))},[Fi]:async(r,n)=>{const i=Xe(r);return bd(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!re(o)||o.kind!=="file")throw Sd()})},[_n]:async(r,n)=>{const i=Xe(r),o=Md(await Ze(()=>e.registry.resolveFile(i.target).read(t(n))));try{const s=new TextDecoder("utf-8",{fatal:!0}).decode(o);return s.charCodeAt(0)===65279?s.slice(1):s}catch{throw w("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[$i]:async(r,n)=>{const i=Xe(r,["content"]);typeof i.content!="string"&&nt("content 必须是字符串");const o=e.registry.resolveFile(i.target);wr(o.mode),await Ze(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[An]:async(r,n)=>{const i=Xe(r),o=await Ze(()=>e.registry.resolveFile(i.target).read(t(n)));return Md(o)},[Vi]:async(r,n)=>{const i=Xe(r,["content"]),o=e.registry.resolveFile(i.target);wr(o.mode),await Ze(()=>o.write(aI(i.content),t(n)))},[Dn]:async(r,n)=>{const i=Xe(r),o=await Ze(()=>e.registry.resolveFile(i.target).stat(t(n)));return cI(o)}},directory:{[Gi]:async(r,n)=>{const i=Xe(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);wr(o.mode),await Ze(()=>o.create(Dd(i),t(n)))},[bn]:async(r,n)=>{const i=Xe(r,["recursive"]);if(re(i.target)&&i.target.relativePath===".")throw w("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),wr(o.handle.mode),!o.handle.remove)throw tt(bn);await Ze(()=>o.handle.remove({recursive:i.recursive===void 0?!1:lo(i.recursive,"recursive")},t(n)))},[qi]:async(r,n)=>{const i=Xe(r);return bd(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!re(o)||o.kind!=="directory")throw Sd()})},[Qi]:async(r,n)=>{const i=Xe(r,["limit"]),o=sI(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 nI(e){if(e===void 0)return{mode:"read",multiple:!1};re(e)||nt("pickFiles 参数必须是对象"),Uo(e,["mode","accept","multiple"]);const t=Rf(e.mode,"read"),r=e.multiple===void 0?!1:lo(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 iI(e){return e===void 0?{mode:"read"}:(re(e)||nt("pickDirectory 参数必须是对象"),Uo(e,["mode"]),{mode:Rf(e.mode,"read")})}function oI(e){return re(e)||nt("saveFile 参数必须是对象"),Uo(e,["suggestedName"]),{suggestedName:Cn(e.suggestedName,"suggestedName")}}function Xe(e,t=[]){return(!re(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&nt("文件操作参数必须包含 target"),Uo(e,["target",...t]),e}function Dd(e){return{recursive:e.recursive===void 0?!1:lo(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:lo(e.exclusive,"exclusive")}}function Rf(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&nt("mode 必须是 read 或 readwrite"),e)}function lo(e,t){return typeof e!="boolean"&&nt(`${t} 必须是布尔值`),e}function sI(e){if(e===void 0)return Ad;if((!Number.isSafeInteger(e)||e<=0)&&nt("limit 必须是正整数"),e>Ad)throw w("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Uo(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&nt(`不支持字段: ${r.join(", ")}`)}function wr(e){if(e!=="readwrite")throw w("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function rs(e){if(!e.trustedUserGesture)throw w("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function ns(e){if(!e)throw tt("files.external");return e}async function bd(e){try{return await e(),!0}catch(t){if(tI.has(Ya(t)??""))return!1;throw Rr(t)}}async function Ze(e){try{return await e()}catch(t){throw Rr(t)}}function aI(e){return e instanceof Uint8Array||nt("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&nt("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Md(e){if(!(e instanceof Uint8Array))throw w("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Sd(){return w("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function cI(e){if(!re(e)||e.kind!=="file"||!dI(e.size))throw w("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!uI(e[t]))throw w("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 dI(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function uI(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function nt(e){throw w("INVALID_PARAMS",e)}const Nd=16*1024,Td=200;function lI(e){const t=Zl(e.runtimePermissions);function r(n,i){e.capabilities&&$l(i,e.capabilities);const o=t({kind:"all",permissions:["filesystem"]},i);if(!o.allowed)throw w(o.code,o.message);const s=Se(e.operationContext,n);return ia(s),s}return{async list(n,i={}){const o=r(i.signal,"directory.list"),s=e.registry.resolveDirectoryEntry({kind:"directory",root:{kind:"sandbox"},relativePath:n}),a=await vd(()=>s.handle.list({limit:Td},o),o);return e.registry.describeListedEntries(s,a,Td).map(({name:c,kind:d})=>({name:c,kind:d}))},async read(n,i={}){const o=i.maxBytes??Nd;if(!Number.isSafeInteger(o)||o<1||o>Nd)throw w("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 w("DIAGNOSTICS_UNSUPPORTED","当前 Host 不支持有界文件诊断读取");const c=await vd(()=>a.readPrefix({maxBytes:o},s),s);if(!c||!(c.bytes instanceof Uint8Array)||c.bytes.byteLength>o||typeof c.truncated!="boolean")throw w("FILE_IO_FAILED","Host 返回了无效的有界读取结果");return{bytes:new Uint8Array(c.bytes),truncated:c.truncated}}}}function ia(e){if(e.signal.aborted)throw w("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")}async function vd(e,t){let r;try{const n=await Promise.race([e(),new Promise((i,o)=>{r=()=>o(w("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")),t.signal.addEventListener("abort",r,{once:!0}),t.signal.aborted&&r()})]);return ia(t),n}catch(n){throw t.signal.aborted&&ia(t),Rr(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const fI=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),is={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function mI(e){if(e instanceof Le)return w("REQUEST_UNSUPPORTED",is.REQUEST_UNSUPPORTED);const t=Cf(e);return t!==void 0&&fI.has(t)?w(t,is[t]??"媒体操作失败"):w("MEDIA_PREPARE_FAILED",is.MEDIA_PREPARE_FAILED)}function Cf(e){try{if(!re(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const hI=["source","mediaType","maxCount"],di=Object.freeze({source:"album",mediaType:"all",maxCount:1});function gI(e){if(e===void 0)return di;if(!Lh(e))throw w("INVALID_PARAMS",yI(e));return pI(e)}function pI(e){return Object.freeze({source:e.source??di.source,mediaType:e.mediaType??di.mediaType,maxCount:e.maxCount??di.maxCount})}function yI(e){if(!re(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!hI.includes(r));if(t.length>0)return`media.pick 不支持字段: ${t.join(", ")}`;if(e.source!==void 0&&e.source!=="album"&&e.source!=="camera")return"source 必须是 album 或 camera";if(e.mediaType!==void 0&&e.mediaType!=="image"&&e.mediaType!=="video"&&e.mediaType!=="all")return"mediaType 必须是 image、video 或 all";if(e.maxCount!==void 0){if(typeof e.maxCount!="number"||!Number.isSafeInteger(e.maxCount))return"maxCount 必须是安全整数";if(e.source==="camera"&&e.maxCount!==1)return"相机只支持 maxCount 为 1 或省略,不能静默收窄"}return"media.pick 参数不合法"}const wI=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),EI={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class II{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=_I(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>DI(s,i[a]));if(!Uh(o))throw _t("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(bI).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=Cf(n);throw i!==void 0&&wI.has(i)?n:_t("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function Od(e,t){if(e.signal.aborted)throw w("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw w("REQUEST_CANCELLED","media.pick 已取消")}function _I(e,t){if(!Array.isArray(e))throw _t("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw _t("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw _t("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw _t("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw _t("Host 返回了稀疏媒体结果");AI(e[n],n)}return e}function AI(e,t){if(!re(e))throw _t(`第 ${t+1} 项不是对象`);if(!Al({...e,file:EI}))throw _t(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!re(e.file))throw _t(`第 ${t+1} 项缺少文件句柄`)}function DI(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 bI(e){return"handleId"in e.ref?e.ref.handleId:void 0}function _t(e){return w("MEDIA_PREPARE_FAILED",e)}function MI(e){const t=e.media?new II(e.registry,e.media,e.operationContext):void 0;return{handlers:{[Mn]:async(n,i)=>{const o=gI(n);NI(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw tt(Mn);const c=Se(e.operationContext,i.signal);Od(e.operationContext,i.signal);const d=await SI(s,o,c,e.operationContext,i.signal);Od(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function SI(e,t,r,n,i){try{return await fe(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?w("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?w("REQUEST_CANCELLED","media.pick 已取消"):mI(o)}}function NI(e){if(!e.trustedUserGesture)throw w("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Yn=4294967296;function TI(e){const t=new vI;return t.write(e),t.finish()}class vI{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<Yn?(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=OI(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<Yn)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/Yn),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Yn)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function OI(e){const t=new Uint8Array(kI(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 kI(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 Lf(e){oa(e);const t=TI(e);if(t.byteLength>128)throw new Error("launch extra is too large");return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function oa(e,t=0,r=new WeakSet){if(t>8)throw new Error("extra nesting depth exceeded");if(e===null||typeof e=="string"||typeof e=="boolean")return;if(typeof e=="number"){if(Number.isFinite(e))return;throw new Error("extra number must be finite")}if(typeof e!="object")throw new Error("extra value must be JSON-compatible");if(r.has(e))throw new Error("extra value must not contain cycles");if(r.add(e),Array.isArray(e)){if(e.length>64)throw new Error("extra array is too large");for(const o of e)oa(o,t+1,r);r.delete(e);return}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new Error("extra object must be a plain object");const i=Object.entries(e);if(i.length>64)throw new Error("extra object has too many fields");for(const[o,s]of i){if(o==="__proto__")throw new Error("extra object key is not supported");oa(s,t+1,r)}r.delete(e)}const PI=["pc","console","mobile"],RI=["game","wiki"];function fo(e){throw{code:"INVALID_PARAMS",message:e}}function CI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bt(e,t){return typeof e!="string"||!e.trim()?fo(t):e.trim()}function kd(e,t,r){return typeof e!="string"||!t.includes(e)?fo(r):e}function LI(e){const t={target:"game_detail",appId:Bt(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:kd(e.gameType,PI,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=kd(e.page,RI,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Bt(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Bt(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function UI(e){return{target:"user_detail",userId:Bt(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function xI(e){const t={target:"post_detail",linkId:Bt(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Bt(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Bt(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function jI(e){const t={target:"mini_program",miniProgramId:Bt(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function zI(e){return CI(e)?e.target==="game_detail"?LI(e):e.target==="user_detail"?UI(e):e.target==="post_detail"?xI(e):e.target==="mini_program"?jI(e):fo("navigation.openAppPage target 不支持"):fo("navigation.openAppPage options 必须是对象")}function BI(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 HI(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function FI(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 $I(e){const t=e;return t.target==="game_detail"?BI(t):t.target==="user_detail"?HI(t):FI(t)}const VI="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",GI="data-hb-sdk-fullscreen-exit",qI=3e3,QI=2e3,Pd="var(--white-70a,rgba(255,255,255,.7))",Rd="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function YI(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(GI,""),t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true");const r=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;t.style.cssText=["position:fixed","right:0","top:50%","z-index:2147483647","box-sizing:border-box","width:48px","height:44px","padding:5px 0",`border:1px solid ${Pd}`,`box-shadow:${Rd}`,"border-radius:var(--radius-m-token,5px)","display:flex","flex-direction:column","align-items:center","justify-content:center","gap:3px","background:var(--general-color-text-2,#64696e)","color:var(--white-100a,#fff)",'font:400 var(--font-size-9,9px)/var(--line-height-12,12px) "PingFang SC",sans-serif',"cursor:pointer","touch-action:manipulation","opacity:1","transform:translateY(-50%)",r?"transition:none":"transition:width var(--token-transition-arrow,220ms cubic-bezier(.2,.8,.2,1))"].join(";");const n=document.createElement("img");n.src=VI,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let o=!0,s=!1,a=!1,c,d;function u(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function f(){o||(t.style.width=u())}function l(){d?.cancel(),d=void 0}function h(I=QI){clearTimeout(c),c=setTimeout(()=>{l(),o=!1,t.style.width=u(),t.style.opacity="0.5",t.style.borderColor="var(--white-40a,rgba(255,255,255,.4))",t.style.boxShadow="none",n.style.visibility="hidden",i.style.display="none",t.setAttribute("aria-label","展开退出全屏按钮"),t.setAttribute("aria-expanded","false")},I)}function m(){l(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Pd,t.style.boxShadow=Rd,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),h()}async function g(){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",g),window.addEventListener("resize",f),document.body.append(t),!r&&t.animate&&(d=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),h(qI),{dispose(){s=!0,clearTimeout(c),l(),t.removeEventListener("click",g),window.removeEventListener("resize",f),t.remove()}}}const Uf=1e4;function xf(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()},Uf);return{signal:r.signal,async run(s){try{return await fe(s,r.signal)}catch(a){throw n??a}},dispose(){clearTimeout(o),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function Cd(e){if(typeof e!="object"||e===null||Array.isArray(e))throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 参数必须是对象"};const{orientation:t,fullscreen:r}=e;if(t!==void 0&&t!=="portrait"&&t!=="landscape")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay orientation 必须是 portrait 或 landscape"};if(r!==void 0&&typeof r!="boolean")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay fullscreen 必须是布尔值"};if(t===void 0&&r===void 0)throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 至少设置 orientation 或 fullscreen"};return{orientation:t,fullscreen:r}}function os(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Xr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function WI(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??=YI(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",c,{once:!0});function u(m,g){if(n===m){if(n=void 0,clearTimeout(m.timer),e.operationContext.signal.removeEventListener("abort",f),"error"in g)m.controller.abort();else if(i={options:m.options,result:g.result},o=m.options,d(m.options),e.onApplied?.(m.options),g.result.supported&&!os(s,m.options)){s={...m.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:m.source})}catch{}}for(const I of m.subscribers)I.dispose(),"error"in g?I.reject(g.error):I.resolve(g.result);m.subscribers.clear()}}function f(){n&&u(n,{error:Xr()})}function l(m,g){return new Promise((I,E)=>{const b=()=>{m.subscribers.delete(y),y.dispose(),E(Xr()),m.subscribers.size===0&&u(m,{error:Xr()})},y={resolve:I,reject:E,dispose:()=>g?.removeEventListener("abort",b)};m.subscribers.add(y),g?.addEventListener("abort",b,{once:!0}),g?.aborted&&b()})}const h={async runDisplayRequest(m,g,I){const E=++t,b=xf(g,e.operationContext.signal);try{return await b.run(async()=>{if(await I(b.signal),b.signal.aborted)throw Xr();if(Cd(m),E<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=E,h.apply(m,b.signal)})}finally{b.dispose()}},async apply(m,g,I="api"){if(pe(e.operationContext.signal),g?.aborted)throw Xr();const E=Cd(m),b=n?.options??o,y={mode:E.orientation??b.mode,hideCapsule:E.fullscreen??b.hideCapsule};y.mode==="landscape"&&(y.hideCapsule=!0);const v=e.presentation.applyOrientation;if(!v)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&os(n.options,y))return l(n,g);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&os(i.options,y))return i.result;i=void 0;const j={options:y,source:I,controller:new AbortController,subscribers:new Set};n=j;const A=l(j,g);return e.operationContext.signal.addEventListener("abort",f,{once:!0}),g||(j.timer=setTimeout(()=>{u(j,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Uf)),fe(()=>v.call(e.presentation,y,{...e.operationContext,signal:j.controller.signal}),j.controller.signal).then(D=>u(j,{result:D??{supported:!0}}),D=>u(j,{error:D})),A},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return h}function jf(e){throw{code:"INVALID_PARAMS",message:e}}function Ld(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&jf(`${t} 不支持参数`)}function ZI(e){return{[eo]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),Ld(t,"navigation.close"),await fe(()=>e.presentation.close(n),n.signal)},[to]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),Ld(t,"navigation.reload"),await fe(()=>e.presentation.reload(n),n.signal)},[ro]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal);const i=zI(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Lf(i.extra)}catch{jf("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=xf(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($I(i),n),n.signal)}}}const Ud={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function KI(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 w("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(l){throw s(),Rr(l)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw w("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw w("FILE_TOO_LARGE","文件超过大小限制");let d=0,u=!1;const f=l=>{u||o.signal.aborted||!Number.isSafeInteger(l)||l<d||l>c.size||(d=l,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:l,...h}=e,m=await n.upload(a,{...h,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:f});if(u=!0,!Number.isSafeInteger(m.uploadedBytes)||m.uploadedBytes<d||m.uploadedBytes>c.size)throw w("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(m.status>=200&&m.status<300&&m.uploadedBytes!==c.size)throw w("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:m.uploadedBytes,total:c.size,lengthComputable:!0}),m}catch(l){u=!0;const h=Ya(l);throw h&&Ud[h]?w(h,Ud[h]):o.signal.aborted?w("UPLOAD_CANCELLED","上传已取消"):h?.startsWith("FILE_")||h?.startsWith("DIRECTORY_")?Rr(l):w("UPLOAD_NETWORK_FAILED","上传网络失败")}}const nc="withCredentials",JI=new Set(["url","method","params","data","headers","timeout",nc]),XI=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",nc]),e_=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),xd=3e4,sa=2*1024*1024,t_=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,zf=/[\u0000-\u0008\u000A-\u001F\u007F]/,r_=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,n_="network.request 不支持 multipart/form-data,请使用专用上传能力";function i_(e){const t=o_(e.runtimePermissions);t.networkPolicy=ql(e.networkPolicy);const r=E_(e.allowedHttpOrigins);return{[ji]:async(n,i)=>{const o=a_(n,{permission:t,allowedHttpOrigins:r}),s=await KI(o,i,e),{uploadedBytes:a,...c}=s;return zd(c)},[xi]:async(n,i)=>{const o=c_(n,{permission:t,allowedHttpOrigins:r});return nf(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Ui]:async(n,i)=>{const o=Se(e.operationContext,i?.signal);pe(o.signal);const s=s_(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await fe(()=>e.network.request(s,o),o.signal)}catch(c){throw __(c)?c:A_(c,"REQUEST_UNSUPPORTED")?me("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):me("REQUEST_FAILED","网络请求失败")}return zd(a)}}}function o_(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 s_(e,t){const r=Lr(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!JI.has(c));if(n.length>0)throw me("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Bf(r,"network.request");const i=ic(r,t,"network.request"),o=u_(r.method),s=r.data;s!==void 0&&m_(s),g_(i.headers,s);const a=p_(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 a_(e,t){const r=Lr(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(u=>!n.has(u)))throw me("INVALID_PARAMS","network.upload 包含不支持的字段");const i=ic(r,t,"network.upload");if(i.official)throw me("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw me("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!er(r.from))throw me("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw me("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw me("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw me("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 me("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(u=>u.toLowerCase()==="content-type"))throw me("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=jd(r.fieldName),c=r.fields===void 0?void 0:Lr(r.fields,"fields 必须是字符串字典");for(const[u,f]of Object.entries(c??{}))if(jd(u),typeof f!="string"||u===a)throw me("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw me("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||zf.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw me("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:a,fields:c,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>sa)throw me("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:Za(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function jd(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw me("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function c_(e,t){const r=Lr(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!XI.has(c));if(n.length>0)throw me("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Bf(r,"network.download");const i=ic(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw me("INVALID_PARAMS","network.download timeout 必须是有限正数");Yy(i.headers);const o=er(r.to),s=Il(r.to);if(!o&&!s)throw me("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw me("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw me("INVALID_PARAMS","suggestedName 必须是字符串");a=Za(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw me("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw me("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 ic(e,t,r){const n=d_(e.url,t.allowedHttpOrigins,r),i=t.permission.networkPolicy,o=i?.enforcement==="approved_domains"&&n.protocol==="http:"&&t.allowedHttpOrigins.has(n.origin);if(i&&!o&&(n.protocol!=="https:"||n.port!==""||!i.entries.some(a=>a.domain===n.hostname.toLowerCase())))throw me("PERMISSION_DENIED",`${r} 目标不在平台批准的域名清单中`);const s=Bp(n);if(s&&!t.permission.useOfficialDomain)throw me("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(zp(n.pathname,s))throw me("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:s,params:e.params===void 0?void 0:{...Lr(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:l_(e.headers,r),timeout:f_(e.timeout,r)}}function d_(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw me("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw me("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw me("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw me("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw me("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function u_(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw me("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!e_.has(t))throw me("INVALID_PARAMS","network.request method 不合法");return t}function l_(e,t="network.request"){const r=Lr(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!t_.test(s)||typeof o!="string"||zf.test(o))throw me("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Hp(s))throw me("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function Bf(e,t){const r=e[nc];if(r!==void 0&&typeof r!="boolean")throw me("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function f_(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw me("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>xd)throw me("INVALID_PARAMS",`${t} timeout 不能超过 ${xd}ms`);return e}}function m_(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw me("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(h_(e)>sa)throw me("INVALID_PARAMS",`network.request data 不能超过 ${sa} 字节`)}function h_(e){if(typeof e=="string")return ss(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return ss(e.toString());try{const t=JSON.stringify(e);return t?ss(t):0}catch{throw me("INVALID_PARAMS","network.request data 必须可序列化")}}function g_(e,t){const r=Hf(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 me("INVALID_PARAMS",n_)}function p_(e,t,r){if(t===void 0)return;const n=Hf(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)||w_(t))?"form":y_(t)?"json":void 0}function Hf(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function y_(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function w_(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function E_(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&&I_(n.hostname)&&t.add(n.origin)}catch{}return t}function I_(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 zd(e){return Object.keys(e.headers).some(Bd)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Bd(t)))}:e}function Bd(e){const t=e.trim().toLowerCase();return r_.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function __(e){return e instanceof Error&&e.name==="AbortError"}function A_(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Lr(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw me("INVALID_PARAMS",t);return e}function ss(e){return new TextEncoder().encode(e).length}function me(e,t){return{code:e,message:t}}function D_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function b_(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 M_(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=b_(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function S_(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 Ff(e,t){if(e==null)return{};if(!D_(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=M_(e.topicIds),n=S_(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 N_(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function T_(e){try{if(N_(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function xe(e){throw{code:"INVALID_PARAMS",message:e}}function jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aa(e,t){return typeof e!="string"||!e.trim()?xe(t):e}function v_(e,t){const r=aa(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?xe(t):r}catch{return xe(t)}}function O_(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function $f(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return xe(`${t} 缺少有效的小程序分享地址`);try{const o=new URL(e.environment.getCurrentHref()),s=new URL("/tools/common_share",o);s.searchParams.set("user_miniprogram_id",i);const a=n?.version?.trim();a&&s.searchParams.set("miniprogram_version",a);const c=o.searchParams.get("h_src");return c?.trim()&&s.searchParams.set("h_src",c),r!==void 0&&s.searchParams.set("extra",r),s.href}catch{return xe(`${t} 缺少有效的小程序分享地址`)}}function k_(e,t){if(!jn(e))return xe("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return xe("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!O_(r))return xe("share.showShareMenu channel 不合法");const n=Vf(e.extra,"share.showShareMenu");return{title:aa(e.title,"share.showShareMenu title 必须是非空字符串"),description:aa(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:$f(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:v_(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Vf(e,t){if(e!==void 0)try{return Lf(e)}catch{return xe(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function Gf(e,t){return e.invalidMessage&&await fe(()=>T_(t.environment),t.operationContext.signal)?xe(e.invalidMessage):e.post}function Hd(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function P_(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Hd(t.windowWidth,0),height:Hd(t.windowHeight,0)}}function ca(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?xe(t):r}function Fd(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?xe(t):r}function R_(e){return jn(e)?{left:ca(e.left,"share.screenshot rect.left 必须是非负数字"),top:ca(e.top,"share.screenshot rect.top 必须是非负数字"),width:Fd(e.width,"share.screenshot rect.width 必须是正数"),height:Fd(e.height,"share.screenshot rect.height 必须是正数")}:xe("share.screenshot rect 必须是对象")}function $d(e,t){if(e!=null&&!jn(e))return xe("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?xe("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?xe("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?P_(t):R_(r.rect),...r.delay===void 0?{}:{delay:ca(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function C_(e,t){pe(t.operationContext.signal);const r=k_(e,t);let n=Ff(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await Gf(n,t);return fe(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function L_(e,t){if(pe(t.operationContext.signal),e!==void 0&&!jn(e))return xe("share.copyLink 参数必须是对象");const r=Vf(e?.extra,"share.copyLink"),n=$f(t,"share.copyLink",r);return await fe(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Vd(e,t,r,n=!1){pe(t.operationContext.signal);const i=Ff(jn(e)?e.post:void 0,{method:"share.screenshot"}),o=await Gf(i,t),s=t.identity.get()?.miniProgramId.trim()||void 0,a=U_(),{watermarkTheme:c,...d}=r;let u=!1,f,l,h;try{if(n&&(!t.presentation.supportsLongScreenshot||!t.prepareLongScreenshot))throw{code:"REQUEST_UNSUPPORTED",message:"当前宿主不支持 DOM 长图,请更新宿主"};if(u=!0,await fe(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),n){const I=await t.prepareLongScreenshot(r.rect,t.operationContext.signal);f=I.restore,d.rect=I.rect}l=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,c),h={status:"fulfilled",value:await fe(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:o,...s?{sourceMiniProgramId:s}:{}},t.operationContext),t.operationContext.signal)}}catch(g){h={status:"rejected",error:g}}finally{try{l?.()}finally{f?.()}}const m=u?await x_(t.presentation,a,t.operationContext.signal):void 0;if(h.status==="rejected")throw h.error;if(m)throw m;return h.value}function U_(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function x_(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 j_(e){let t=Promise.resolve();const r=async(n,i)=>{const o=Se(e.operationContext,i.signal,i.requestId),s=$d(n,e.presentation);(s.rect.top+s.rect.height>1e4||s.rect.left+s.rect.width>2048||s.rect.width*s.rect.height>4e6)&&xe("长图尺寸超出限制");const a=t.then(()=>Vd(n,{...e,operationContext:o},s,!0));return t=a.then(()=>{},()=>{}),a};return{[Ri]:r,[Oi]:(n,i)=>L_(n,{...e,operationContext:Se(e.operationContext,i.signal,i.requestId)}),[ki]:(n,i)=>C_(n,{...e,operationContext:Se(e.operationContext,i.signal,i.requestId)}),[Pi]:async(n,i)=>{const o=Se(e.operationContext,i.signal,i.requestId);pe(o.signal);const s=$d(n,e.presentation),a=t.then(()=>Vd(n,{...e,operationContext:o},s));return t=a.then(()=>{},()=>{}),fe(()=>a,o.signal)}}}const Gd=new WeakMap,Wn=new Map;function qf(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return ap(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Fl(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Qf(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=Gd.get(t);f||(f=new Map,Gd.set(t,f));const l=f.get(u)??Promise.resolve(),h=async()=>(pe(c.signal,{preserveReason:!0}),d(u)),m=l.catch(()=>{}).then(()=>e.lock?e.lock(u,h):h());f.set(u,m);try{return await m}finally{f.get(u)===m&&f.delete(u)}},o=async(c,d,u=!1)=>{const f=fr(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(m=>m.key.startsWith(f)&&m.value!=="").map(m=>m.key.slice(f.length)))];const l=await e.storage.getRaw($n(c),d);if((l===void 0||l==="")&&!u)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let h;try{h=l?JSON.parse(l):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(h)||h.length>Uc||h.some(m=>typeof m!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(m)))throw new Error("本地数据索引异常");return[...new Set(h)]},s=async(c,d)=>{if(e.diagnostics){const l=fr(c,"");return(await e.diagnostics.listRaw(d)).filter(h=>h.key.startsWith(l)&&h.value!=="").map(h=>({...h,key:h.key.slice(l.length)}))}const u=[],f=await o(c,d);for(let l=0;l<f.length;l+=16){pe(d.signal,{preserveReason:!0});const h=await Promise.all(f.slice(l,l+16).map(async m=>{const g=await e.storage.getRaw(fr(c,m),d);return g!==void 0&&g!==""?{area:"local",key:m,value:g}:void 0}));for(const m of h)m&&u.push(m)}return u},a=c=>{if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw Object.assign(new Error("storage key 不合法"),{code:"INVALID_REQUEST"})};return{get(c,d){return a(c),i(d,u=>e.storage.getRaw(fr(u,c),d))},set(c,d,u){return a(c),i(u,async f=>{const l=await o(f,u,!0);if(!l.includes(c)&&l.length>=Uc)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const h=[...new Set([...l,c])];await e.storage.setRaw($n(f),JSON.stringify(h),u)}pe(u.signal,{preserveReason:!0}),await e.storage.setRaw(fr(f,c),d,u),pe(u.signal,{preserveReason:!0})})},list(c){return i(c,d=>s(d,c))},clear(c){return i(c,async d=>{const u=await o(d,c);e.diagnostics||await e.storage.setRaw($n(d),JSON.stringify(u),c);for(let f=0;f<u.length;f+=16){pe(c.signal,{preserveReason:!0});const h=(await Promise.allSettled(u.slice(f,f+16).map(m=>e.storage.setRaw(fr(d,m),"",c)))).find(m=>m.status==="rejected");if(h)throw h.reason}pe(c.signal,{preserveReason:!0}),await e.storage.setRaw($n(d),"[]",c)})}}}function Yf(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=(Wn.get(e)??Promise.resolve()).catch(()=>{}).then(t);return Wn.set(e,r),r.finally(()=>{Wn.get(e)===r&&Wn.delete(e)})}const z_=128,B_=/^[A-Za-z0-9_-]+$/;function H_(e){const t=e.scopedStorage??Qf({storage:e.storage,resolveScope:()=>qf({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[yn]:async n=>{pe(e.operationContext.signal);const i=qd(n,yn,e.storageLimits?.maxKeyLength),o=await fe(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:Qd(o)}},[wn]:async n=>{pe(e.operationContext.signal);const i=Wf(n,"storage.setStorage 参数必须是对象"),o=qd(i,wn,e.storageLimits?.maxKeyLength),s=F_(i.data,e.storageLimits?.maxValueBytes);await fe(()=>t.set(o,s,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(pe(e.operationContext.signal),(await fe(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?rr("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:Qd(o),serializedValue:o,bytes:Zf(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function qd(e,t,r=z_){const i=Wf(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw rr("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!B_.test(i))throw rr("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function F_(e,t){let r;try{r=JSON.stringify(e)}catch{throw rr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw rr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Zf(r)>t)throw rr("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Qd(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Wf(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw rr("INVALID_PARAMS",t);return e}function Zf(e){return new TextEncoder().encode(e).length}function rr(e,t){return{code:e,message:t}}const Yd=120;function Ut(e){throw{code:"INVALID_PARAMS",message:e}}function oc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kf(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Ut(`${r} 不支持字段: ${n.join(", ")}`)}function $_(e){if(!oc(e))return Ut("ui.showToast 参数必须是对象");if(Kf(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Ut("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Yd)return Ut(`ui.showToast message 不能超过 ${Yd} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Ut("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function V_(e){return e===void 0?{dismissible:!1}:oc(e)?(Kf(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Ut("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Ut("ui.showLoading 参数必须是对象")}function G_(e){e!==void 0&&(!oc(e)||Object.keys(e).length)&&Ut("ui.hideLoading 不支持参数")}function q_(e){return{[Yi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.showToast($_(t),n),n.signal)},[Wi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.showLoading(V_(t),n),n.signal)},[Zi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),G_(t),await fe(()=>e.presentation.hideLoading(n),n.signal)}}}const Q_={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return Te(e,"当前用户首页资料接口响应异常")}},Y_=3e4;function W_(e,t,r={}){const n=r.ttlMs??Y_,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 Ro(e,Q_,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(l){throw t.signal.aborted?w("RUNTIME_DESTROYED","小程序 Runtime 已终止"):l instanceof Le?w("REQUEST_UNSUPPORTED",l.message):l instanceof xn?w("INVALID_RESPONSE","user home_v2 响应不合法"):l instanceof Cr?w("REQUEST_FAILED","user home_v2 请求失败"):l instanceof Un?i&&(l.status===403||l.status===429)?w("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:l.status,...l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs}}):w("REQUEST_FAILED",l.message):K_(l)?l:w("REQUEST_FAILED","user home_v2 请求失败")}return Z_(f,"user home_v2")}function u(f){const l=Date.now();if(a?.userId===f&&a.expiresAt>l)return Promise.resolve(a.value);if(c?.userId===f&&c.generation===s)return c.promise;const h=s,m=d().then(g=>(s===h&&(a={userId:f,value:g,expiresAt:Date.now()+n}),g)).finally(()=>{c?.promise===m&&(c=void 0)});return c={userId:f,generation:h,promise:m},m}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function Z_(e,t){if(!re(e))throw w("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 w(n,r)}if(!re(e.result))throw w("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function K_(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}const J_={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,"关注用户接口响应异常")}},X_={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 接口响应异常")}},eA={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 接口响应异常")}},tA={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 rA(e,t=Zs){const r=ew({version:"2",validate:iA}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):Zs,memoryMaxEntries:64,diskMaxEntries:256,diskMaxBytes:10*1024*1024,maxEntryBytes:512*1024};return{persistent:e.register({namespace:"user.steam-game-list",codec:r,policy:{...n,persistence:"memory-and-disk"}}),unresolved:e.register({namespace:"user.steam-game-list.unresolved",codec:r,policy:{...n,persistence:"memory"}})}}function Wd(e,t){if(e.steamId)return e.steamId;for(const r of["steamid","steam_id","steamId"]){const n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}function nA(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 iA(e){if(!re(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Zd(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Mr();for(const t of e.gameList){if(!re(t)||!da(t.appid)||!da(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Mr();for(const r of["image","portraitImage","icon"])oA(t,r);for(const r of["playtimeForever","playtime2Weeks"])Zd(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Mr()}return e}function da(e){return typeof e=="number"&&Number.isFinite(e)}function Zd(e,t){if(e[t]!==void 0&&!da(e[t]))throw Mr()}function oA(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Mr()}function Mr(){return w("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Jf=20,sA=100,aA=128,Xf=0,em="weeks",cA=100,dA=new Set(["weeks","all","achieved"]);function uA(){return{nickname:"",avatar:""}}function lA(e){const t=W_(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??af(),i=rA(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(O,z){const U=JSON.stringify([O,z]);return(!o||o.key!==U)&&(o={key:U,scope:n.createScope(z,n.createScope(O))}),o.scope}function d(){const O=o;o=void 0,O&&n.invalidateScope(O.scope).catch(()=>{}),s.clear()}const u=wf({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??pf))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let l,h,m=0,g=!1;const I=e.account.onChange(()=>{m+=1,t.clear(),u.invalidate(),d()}),E=e.authorization.onEvent((O,z)=>{O==="user_info_authorization_change"&&Object.values(z).some(U=>U==="denied")&&(m+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(g)return;const U=await e.account.getCurrentUserId(e.operationContext);typeof U=="string"&&U.trim()&&await n.invalidateScope(c(y(),U.trim()))}).catch(()=>{}))});function b(){if(g||e.operationContext.signal.aborted)throw w("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function y(){const O=e.identity.get()?.miniProgramId?.trim();if(!O)throw w("INVALID_STATE","用户能力缺少 canonical 小程序身份");return O}async function v(){b(),await a,b();let O;try{O=await e.account.getCurrentUserId(e.operationContext)}catch(z){throw e.operationContext.signal.aborted?w("RUNTIME_DESTROYED","小程序 Runtime 已终止"):en(z)?z:w("REQUEST_FAILED","读取小黑盒账号失败")}return typeof O=="string"&&O.trim()?O.trim():void 0}async function j(O,z){const U=await v();if(m!==z||U!==O)throw w("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function A(O,z,U=e.operationContext.signal){try{return await Ro(e.network,O,z,{...e.operationContext,signal:U,credentials:"heybox-session",...f?{gate:f}:{}})}catch(L){throw e.operationContext.signal.aborted?w("RUNTIME_DESTROYED","小程序 Runtime 已终止"):L instanceof Le?w("REQUEST_UNSUPPORTED",L.message):L instanceof xn?w("INVALID_RESPONSE","用户接口响应不合法"):L instanceof Cr?w("REQUEST_FAILED","用户请求失败"):L instanceof Un?r&&(L.status===403||L.status===429)?w("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:L.status,...L.retryAfterMs===void 0?{}:{retryAfterMs:L.retryAfterMs}}):w("REQUEST_FAILED",L.message):en(L)?L:w("REQUEST_FAILED","用户请求失败")}}async function D(O,z){if(!e.authorizationContext)return{mini_program_id:O};let U;try{U=await fe(()=>e.authorizationContext.get({...e.operationContext,signal:z}),z)}catch(L){if(en(L))throw L;const C=w("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(C,"cause",{configurable:!0,value:L}),C}if(!U.token?.trim())throw w("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:O,runtime_auth_context_token:U.token}}async function _(){b();const O=y(),z=m,U=await v();if(!U){if(m!==z)throw w("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const L=await D(O,e.operationContext.signal);await j(U,z);const C=await A(X_,L);if(await j(U,z),y()!==O)throw w("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Xd(Jd(C))}function T(O,z){if(!O)return Promise.reject(w("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(z?.aborted)return Promise.reject(w("REQUEST_CANCELLED","关注操作已取消"));if(l)return Promise.reject(w("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(w("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const U=N(z).finally(()=>{l===U&&(l=void 0)});return l=U,U}async function N(O){b();const z=y(),U=new AbortController;h=U;const L=()=>U.abort();e.operationContext.signal.addEventListener("abort",L,{once:!0}),O?.addEventListener("abort",L,{once:!0});let C=()=>{},H=!1;try{try{await fe(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:U.signal}),U.signal)}catch(ue){throw en(ue)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(ue.code)?w("FOLLOW_CANCELLED","已取消小黑盒登录"):ue}b();const F=m;C=e.account.onChange(()=>{H=!0,L()});const G=await fe(v,U.signal);if(!G)throw w("FOLLOW_CANCELLED","未完成小黑盒登录");const K=async()=>{if(await fe(()=>j(G,F),U.signal),b(),y()!==z)throw w("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await K();const p=await D(z,U.signal);await K();const R=IA(),B=await fe(()=>A(eA,{...p,request_id:R},U.signal),U.signal);await K();const Q=Jd(B);if(Q.status!=="notFollowing")return Xd(Q);if(Q.rateLimited)throw w("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const X=await fe(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:z,signal:U.signal}),U.signal);if(await K(),X!=="confirmed")throw w("FOLLOW_CANCELLED","已取消关注作者");const ne=Q.authorId,ie=await fe(()=>A(J_,{body:{following_id:ne}},U.signal),U.signal);if(await K(),ie.status!=="ok"){const ue=["login","relogin","lack_token"].includes(ie.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw w(ue,typeof ie.msg=="string"&&ie.msg.trim()?ie.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(F){throw b(),H?w("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):O?.aborted?w("REQUEST_CANCELLED","关注操作已取消"):en(F)?F:w("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{C(),e.operationContext.signal.removeEventListener("abort",L),O?.removeEventListener("abort",L),h===U&&(h=void 0)}}async function x(){y();const O=m,z=await v();if(!z)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[U,L]=await Promise.all([e.authorization.getOrCreateLocalIdentity(z),M(z).catch(()=>uA())]);return await j(z,O),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:U.appUserId,profile:L,...U.steamId?{steam_id:U.steamId}:{}}}}function M(O){return u.read(O,()=>A(yf,void 0).then(z=>{const U=ua(z,"账号基础信息");if(U.display_username!==void 0&&typeof U.display_username!="string")throw w("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(U.display_avatar!==void 0&&typeof U.display_avatar!="string")throw w("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:U.display_username??"",avatar:U.display_avatar??""}}))}async function S(O){const z=fA(O),U=y(),L=m,C=await v();if(!C)return d(),{isLogin:!1,isBound:!1,data:null};const H=await t.get(C);await j(C,L);const F=tm(H.steam_id_info);if(Object.keys(F).length===0)return await n.invalidateScope(c(U,C)).catch(()=>{}),await j(C,L),s.delete(JSON.stringify([U,C])),{isLogin:!0,isBound:!1,data:null};const G=JSON.stringify([U,C]),K=c(U,C),p=Wd({...z,steamId:void 0},F),R=rm(F.personal_infomation_open??F.personal_information_open),B=JSON.stringify([p??null,R??null]),Q=s.get(G);Q&&Q.identity!==B&&(await n.invalidateScope(K).catch(()=>{}),await j(C,L));const X={identity:B,scope:n.createScope(B,K)};s.set(G,X);const ne=Wd(z,F),ie=ne?i.persistent:i.unresolved,ue=n.createScope(ne??"unresolved",X.scope),we=async()=>{if(await j(C,L),y()!==U||s.get(G)?.identity!==B)throw w("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},he=await ie.read({scope:ue,key:nA({miniProgramId:U,userId:C,effectiveSteamId:ne,personalInformationOpen:R,query:z}),signal:e.operationContext.signal,load:async ge=>{const ye=await A(tA,{userId:C,...z,personalInformationOpen:R},ge);return await we(),yA(ua(ye,"Steam 游戏库"),z)}}).catch(async ge=>{throw await we(),ge});return await we(),{isLogin:!0,isBound:!0,data:he}}return{getFollowStatus:_,requestFollowAuthor:T,getInfo:x,getSteamGameList:S,async invalidateSteamGameListCache(){const O=y(),z=m,U=await v();if(!U)return;const L=c(O,U);await Promise.all([i.persistent.invalidateScope(L),i.unresolved.invalidateScope(L)]),t.clear(),s.delete(JSON.stringify([O,U])),await j(U,z)},dispose(){g||(g=!0,h?.abort(),m+=1,I(),E(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function fA(e){if(e==null)return{limit:Jf,offset:Xf,sort:em,includeHidden:!1};if(!re(e))throw xt("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw xt(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:mA(e.limit),offset:hA(e.offset),sort:gA(e.sort),includeHidden:pA(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>aA)throw xt("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw xt("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,cA))}return r}function mA(e){if(e===void 0)return Jf;if(!Number.isInteger(e)||Number(e)<1)throw xt("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),sA)}function hA(e){if(e===void 0)return Xf;if(!Number.isInteger(e)||Number(e)<0)throw xt("user.getSteamGameList offset 必须是非负整数");return Number(e)}function gA(e){if(e===void 0)return em;if(typeof e!="string"||!dA.has(e))throw xt("user.getSteamGameList sort 不支持");return e}function pA(e){if(e===void 0)return!1;if(typeof e!="boolean")throw xt("user.getSteamGameList includeHidden 必须是 boolean");return e}function yA(e,t){if(!Array.isArray(e.game_list))throw w("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(wA).filter(a=>a!==void 0),n=mo(e.total),i=t.offset+r.length,o={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(o.total=n,o.hasMore=i<n);const s=rm(e.is_me);return s!==void 0&&(o.isMe=s),o}function wA(e){const t=tm(e),r=mo(t.appid),n=mo(t.steam_appid)??r,i=sc(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};as(o,"image",t.image),typeof t.vertical_head_image=="string"&&as(o,"portraitImage",t.vertical_head_image),as(o,"icon",t.appicon??t.icon),Kd(o,"playtimeForever",t.playtime_forever),Kd(o,"playtime2Weeks",t.playtime_2weeks);const s=EA(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function ua(e,t){if(!re(e))throw w("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 w(n,r)}if(!re(e.result))throw w("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function tm(e){return re(e)?e:{}}function sc(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function EA(e){return Array.isArray(e)?e.map(sc).filter(Boolean):[]}function mo(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function rm(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function as(e,t,r){const n=sc(r);n&&Object.assign(e,{[t]:n})}function Kd(e,t,r){const n=mo(r);n!==void 0&&Object.assign(e,{[t]:n})}function xt(e){return w("INVALID_PARAMS",e)}function en(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Jd(e){const t=ua(e,"关注状态");if(![0,1,2].includes(t.follow_status)||typeof t.author_id!="string"||!/^[1-9]\d*$/.test(t.author_id)||typeof t.rate_limited!="boolean")throw w("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Xd(e){return e.status}function IA(){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 _A(e){return{[Mi]:async t=>(Zn(t,"user.getFollowStatus"),e.user.getFollowStatus()),[Si]:async(t,r)=>(Zn(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[Ni]:async t=>(Zn(t,"user.getInfo"),e.user.getInfo()),[Ti]:async(t,r)=>{Zn(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[vi]:async t=>e.user.getSteamGameList(t)}}function Zn(e,t){if(e!==void 0)throw w("INVALID_PARAMS",`${t} 不接收入参`)}function AA(){return w("USER_DATA_PERMISSION_STATE_INVALID","本地用户数据许可状态异常,已停止访问")}function eu(e){return w("USER_DATA_PERMISSION_SAVE_FAILED","本次运行已停止访问,设置未保存,请重试",e===void 0?void 0:{reason:e instanceof Error?e.message:String(e)})}function DA(e){const t=e.managedResources??Lt,r=typeof e.storage.withLock=="function"||typeof navigator<"u"&&!!navigator.locks,n=e.hash??$a,i=new Map,o=new Set;let s=!1;function a(){if(s)throw w("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function c(y,v){if(e.storage.withLock)return e.storage.withLock(u(y),v);if(typeof navigator<"u"&&navigator.locks)return Yf(u(y),v);throw w("REQUEST_UNSUPPORTED","当前宿主不支持跨实例保存资料许可")}function d(y){return gp({miniProgramId:e.resolveMiniProgramId(),userId:y,environment:e.resolveEnvironment()})}function u(y){return dp(hp(d(y)))}function f(y,v){return e.purposeOf?n(Nl(y,e.revisionOf(y),v,e.purposeOf(y))):n(`${y}\0${e.revisionOf(y)}\0${v}`)}function l(y,v){return`${y}\0${v}`}async function h(y,v){let j;try{j=await e.storage.getRaw(u(y),v)}catch(D){throw a(),v.signal.aborted?w("REQUEST_CANCELLED","许可操作已取消"):w("USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","无法读取本地用户数据许可",{reason:D instanceof Error?D.message:String(D)})}if(a(),v.signal.aborted)throw w("REQUEST_CANCELLED","许可操作已取消");const A=j===void 0||j===""?void 0:mp(j);if(j!==void 0&&j!==""&&A===void 0)throw AA();return A??{schema_version:1,records:{}}}async function m(y,v,j){if(a(),j.signal.aborted)throw w("REQUEST_CANCELLED","许可操作已取消");await e.storage.setRaw(u(y),JSON.stringify(v),j)}function g(y){return y?.revision??0}function I(y,v,j){const A=new Set(j.declared??[]),D=new Set(t);for(const N of Object.keys(v.records))Rt(N)&&D.add(N);for(const N of i.keys())N.startsWith(`${y}\0`)&&D.add(N.slice(y.length+1));const T=[...D].sort((N,x)=>{const M=Lt.indexOf(N),S=Lt.indexOf(x);return(M<0?Number.MAX_SAFE_INTEGER:M)-(S<0?Number.MAX_SAFE_INTEGER:S)}).map(N=>{const x=v.records[N],M=g(x),S=j.egressTier===void 0?void 0:f(N,j.egressTier),O=i.get(l(y,N)),z=O!==void 0&&O.revision===M&&(S===void 0||O.consentFingerprint===S);return{resource:N,name:Oo(N)?.name??N,purposeText:e.purposeOf?.(N)??"",scopeFingerprint:S??"",declared:A.has(N),available:A.has(N),decision:x?.decision??"ask",revision:M,...x?.decision==="allow"&&x.consentFingerprint?{consentFingerprint:x.consentFingerprint}:{},sessionAllowed:z,allowed:!o.has(l(y,N))&&A.has(N)&&x?.decision!=="deny"&&(z||r&&x?.decision==="allow"&&S!==void 0&&x.consentFingerprint===S)}});return Object.freeze({schema_version:1,canPersist:r,resources:Object.freeze(T),...j.egressTier===void 0?{}:{egressTier:j.egressTier}})}function E(y,v,j,A){const D=v.records[j],_=l(y,j);if(o.has(_))return{status:"denied",reason:"tightening"};if(D?.decision==="deny")return{status:"denied",reason:"deny"};const T=f(j,A);if(r&&D?.decision==="allow"&&D.consentFingerprint===T)return{status:"allowed",source:"persistent"};const N=i.get(_);return N&&N.revision===g(D)&&N.consentFingerprint===T?{status:"allowed",source:"session"}:{status:"ask"}}function b(y){if(typeof y!="string"||!Lt.includes(y))throw w("INVALID_PARAMS","用户数据资源标识不合法")}return{canPersist:r,async read(y,v,j={}){a();const A=await h(y,v);return I(y,A,j)},async evaluate(y,v,j){a(),b(v.resource);const A=await h(y,j);return E(y,A,v.resource,v.egressTier)},async decide(y,v){a(),b(y.resource);const j=async()=>{a();const A=await h(y.userId,v);if(a(),v.signal.aborted)throw w("REQUEST_CANCELLED","许可操作已取消");const D=A.records[y.resource],_=g(D);if(y.expectedRevision!==void 0&&_!==y.expectedRevision)throw w("AUTHORIZATION_CONTEXT_CHANGED","资料许可已变化,请重新确认");const T=l(y.userId,y.resource),N=f(y.resource,y.egressTier);if(y.expectedFingerprint!==void 0&&y.expectedFingerprint!==N)throw w("AUTHORIZATION_CONTEXT_CHANGED","资料披露范围已变化,请重新确认");if(y.scope==="session"){if(y.decision!=="allow")throw w("INVALID_PARAMS","本次许可只支持允许");return i.set(T,Object.freeze({revision:_,consentFingerprint:N})),I(y.userId,A,{egressTier:y.egressTier})}const x=_+1,M=y.decision==="allow"?{decision:"allow",revision:x,consentFingerprint:N}:{decision:y.decision,revision:x},S={schema_version:1,records:{...A.records,[y.resource]:M}};y.decision!=="allow"&&(o.add(T),i.delete(T));try{await m(y.userId,S,v)}catch(O){throw eu(O)}return o.delete(T),i.delete(T),I(y.userId,S,{egressTier:y.egressTier})};return y.scope==="session"?j():c(y.userId,j)},async revokeSession(y,v){a(),y.resource!==void 0&&b(y.resource);for(const A of[...i.keys()])A.startsWith(`${y.userId}\0`)&&(y.resource===void 0||A===l(y.userId,y.resource))&&i.delete(A);const j=await h(y.userId,v);return I(y.userId,j,{})},async reset(y,v){return a(),c(y.userId,async()=>{a();const j=await h(y.userId,v);if(a(),v.signal.aborted)throw w("REQUEST_CANCELLED","许可操作已取消");const A=new Set(t);for(const T of Object.keys(j.records))A.add(T);for(const T of i.keys())T.startsWith(`${y.userId}\0`)&&A.add(T.slice(y.userId.length+1));for(const T of A)o.add(l(y.userId,T));for(const T of[...i.keys()])T.startsWith(`${y.userId}\0`)&&i.delete(T);const D={...j.records};for(const T of A)D[T]={decision:"ask",revision:(D[T]?.revision??0)+1};const _={schema_version:1,records:D};try{await m(y.userId,_,v)}catch(T){throw eu(T)}for(const T of A)o.delete(l(y.userId,T));return I(y.userId,_,{})})},dispose(){s||(s=!0,i.clear(),o.clear())}}}const xo={auth:"none",channel:"api",method:"POST",bodyEncoding:"form",failurePresentation:"none",parse(e){return Te(e,"游戏资料接口响应异常")}};function jo(e){return{runtime_auth_context_token:e.runtime_auth_context_token,resource:e.resource,disclosure_revision:e.disclosure_revision}}const bA={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.query.post",path:"/user_miniprogram/runtime/user_game_data/query",body(e){return{...jo(e),operation:e.operation,schema_version:e.schema_version,...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit}}}},MA={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.sync.post",path:"/user_miniprogram/runtime/user_game_data/sync",body:jo},tu={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.sync_status.post",path:"/user_miniprogram/runtime/user_game_data/sync_status",body(e){return{...jo(e),task_id:e.task_id}}},SA={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.file.post",path:"/user_miniprogram/runtime/user_game_data/file",body(e){return{...jo(e),save_id:e.save_id,file_id:e.file_id}}};function NA(e){const t=Mf(e.storage),r=e.fileDownloads??(e.files&&e.transfer?Ja({files:e.files,transfer:e.transfer,registry:e.registry,signal:e.signal}):void 0),n=new Set,i=d=>{if(e.signal.aborted||d.signal.aborted)throw ee("REQUEST_CANCELLED","资料请求已取消")};async function o(d,u){if(i(u),!e.authorizationContext)throw ee("REQUEST_UNSUPPORTED","宿主缺少受信运行上下文");const f=await e.authorizationContext.get(u);if(!f.token||!Number.isFinite(f.expiresAt)||f.expiresAt<=Date.now())throw ee("UNAUTHORIZED","受信运行上下文已过期");return{runtime_auth_context_token:f.token,resource:d.key,disclosure_revision:d.disclosureRevision}}async function s(d,u,f){i(f);const l=await Co({network:e.network,operationContext:f,subject:"游戏资料",assertUsable:()=>i(f),requestPolicyEnabled:e.requestPolicyEnabled,...e.requestGate?{gate:{capability:"userGameData",gate:e.requestGate}}:{}},d,u),h=st(l,"user.data","游戏资料");if(!Ie(h))throw ee("INVALID_RESPONSE","游戏资料响应无效");return i(f),h}const a=d=>{const u=Oo(d);if(!u)throw ee("REQUEST_UNSUPPORTED","未开放资料资源");return u};async function c(d){n.delete(d),await r?.release(d)}return{releaseFile:c,invalidate(){for(const d of n)r?.release(d);n.clear()},async query(d,u){const f=a(d.resource),l=f.queries[d.operation];if(!l)throw ee("REQUEST_UNSUPPORTED","未开放资料操作");const h=await s(bA,{...await o(f,u),operation:d.operation,schema_version:l.version,...d.cursor===void 0?{}:{cursor:d.cursor},...d.limit===void 0?{}:{limit:d.limit}},u);if(h.resource!==d.resource||h.operation!==d.operation||h.schema_version!==l.version||h.disclosure_revision!==f.disclosureRevision)throw ee("INVALID_RESPONSE","游戏资料合同不匹配");if(h.status==="ready"){if(!ip(l.schema,h.data))throw ee("INVALID_RESPONSE","游戏资料正文不匹配公开 schema");return{status:"ready",data:h.data,meta:{},schemaVersion:l.version}}if(h.status==="empty"&&(h.reason==="no_data"||h.reason==="not_ready")&&typeof h.message=="string")return{status:"empty",reason:h.reason,message:h.message,meta:{},schemaVersion:l.version};throw ee("INVALID_RESPONSE","游戏资料状态无效")},async sync(d,u,f){const l=a(d.resource);if(!l.operations.includes("sync"))throw ee("REQUEST_UNSUPPORTED","资源不支持同步");const h=await o(l,u),m=new AbortController,g=()=>m.abort();u.signal.addEventListener("abort",g,{once:!0}),u.signal.aborted&&g();let I=!1;const E=setTimeout(()=>{I=!0,g()},5*6e4),b={...u,signal:m.signal},y={...f,gameId:l.game,resource:d.resource};let v;try{const j=await t.run(y,b,async()=>{const D=await t.get(y,b);if(D)return v=D,{id:D,status:await s(tu,{...await o(l,b),task_id:D},b)};const _=await s(MA,h,b);if(typeof _.task_id!="string"||!_.task_id||_.task_id.length>128)throw ee("INVALID_RESPONSE","同步任务缺失");return await t.set(y,_.task_id,b),{id:_.task_id,status:_}});let A=j.status;for(v=j.id;;){if(i(b),A.state==="succeeded")return await t.remove(y,v,b),{status:"succeeded"};if(A.state==="failed")throw await t.remove(y,v,b),ee(typeof A.error_code=="string"?A.error_code:"SYNC_FAILED","存档同步失败");if(A.state!=="syncing"&&A.state!=="uploading")throw ee("INVALID_RESPONSE","同步状态无效");if(await TA(b.signal),A=await s(tu,{...await o(l,b),task_id:v},b),A.task_id!==v)throw ee("INVALID_RESPONSE","同步任务不匹配")}}catch(j){throw v&&Ie(j)&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED"].includes(String(j.code))&&await t.remove(y,v,b),I?ee("REQUEST_TIMEOUT","等待同步超时,后台任务可能仍在执行"):j}finally{clearTimeout(E),u.signal.removeEventListener("abort",g)}},async file(d,u,f){const l=a(d.resource);if(!l.operations.includes("file")||!r)throw ee("REQUEST_UNSUPPORTED","宿主不支持资料文件下载");const h=async g=>{await f(g);const I=await s(SA,{...await o(l,g),save_id:d.saveId,file_id:d.fileId},g);if(!Ie(I.file)||I.file.file_id!==d.fileId)throw ee("INVALID_RESPONSE","文件标识不匹配");return await f(g),I},m=await r.download(await h(u),async g=>{await h(g)},u);try{return i(u),await f(u),i(u),n.add(m),m}catch(g){throw await c(m),g}}}}function TA(e){return new Promise((t,r)=>{const n=()=>{clearTimeout(i),e.removeEventListener("abort",n),r(ee("REQUEST_CANCELLED","已停止等待同步"))},i=setTimeout(()=>{e.removeEventListener("abort",n),t()},2e3);e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})}const tn=["event_id","miniProgramId","environment","host_platform","host_version","sdk_version","runtime_version","egress_tier","resource","call_id","flow_id"],vA=Object.freeze({user_game_data_permission_show:new Set([...tn,"entry","reason"]),user_game_data_permission_result:new Set([...tn,"choice","apply_result"]),user_game_data_permission_manage:new Set([...tn,"operation","apply_result","succeeded_count","failed_count"]),user_game_data_action:new Set([...tn,"stage","action_type","outcome","duration_ms"]),user_game_data_access_result:new Set([...tn,"api","trigger","status","error_code","failure_stage","duration_ms","cache_hit","sample_rate","overview_status_counts"])}),ru=10*6e4,OA=256;function kA(e){const t=e.now??Date.now,r=e.random??Math.random,n=e.createId??LA,i=RA(e.sampleRate),o=new Map,s=new Map,a=new Map;let c=!1,d=0,u=0,f=0,l=0;const h={get emitted(){return d},get failed(){return u},get skipped(){return f},get deduplicated(){return l}};function m(A){return`${A}${n()}`}function g(){const A=t();for(const[D,_]of o)A-_.createdAt<=ru||(o.delete(D),s.get(_.key)===D&&s.delete(_.key));for(const[D,_]of a){if(A-_<=ru&&a.size<=OA)break;a.delete(D)}}function I(A){const D=o.get(A);D!==void 0&&(o.delete(A),s.get(D.key)===A&&s.delete(D.key))}function E(A){I(A),a.delete(A),a.set(A,t())}function b(A,D){const _=vA[A],T={};for(const[N,x]of Object.entries(D))x===void 0||!_.has(N)||(T[N]=x);return Object.freeze(T)}function y(A){const D={event_id:m("evt_"),miniProgramId:Er(()=>e.resolveMiniProgramId())??"unknown",environment:PA(Er(()=>e.resolveEnvironment())),host_platform:Er(e.resolveHostPlatform)??"unknown",host_version:Er(e.resolveHostVersion)??"unknown",sdk_version:Er(e.resolveSdkVersion)??"unknown",runtime_version:Er(e.resolveRuntimeVersion)??"unknown",egress_tier:CA(e)};return A.resource!==void 0&&(D.resource=A.resource),A.callId!==void 0&&(D.call_id=A.callId),A.flowId!==void 0&&(D.flow_id=A.flowId),D}function v(A,D){if(c){f+=1;return}try{if(e.sink===void 0){f+=1;return}e.sink.postEvent(A,b(A,D)),d+=1}catch{u+=1}}function j(A,D){if(A===void 0)return!1;const _=o.get(A);return _===void 0?!1:D==="start"&&_.started||D==="shown"&&_.shown||D==="decided"&&_.decided?!0:(D==="start"&&(_.started=!0),D==="shown"&&(_.shown=!0),D==="decided"&&(_.decided=!0),!1)}return{diagnostics:h,createCallId(){return m("call_")},beginFlow(A){g();const D=`${A.resource??""}\0${A.actionType}`,_=s.get(D);if(_!==void 0&&o.has(_))return _;const T=m("flow_");return o.set(T,{key:D,createdAt:t(),started:!1,shown:!1,decided:!1}),s.set(D,T),T},permissionShow(A){if(j(A.flowId,"shown")){l+=1;return}v("user_game_data_permission_show",{...y(A),entry:A.entry,reason:A.reason})},permissionResult(A){if(j(A.flowId,"decided")){l+=1;return}v("user_game_data_permission_result",{...y(A),choice:A.choice,apply_result:A.applyResult})},permissionManage(A){v("user_game_data_permission_manage",{...y(A),operation:A.operation,apply_result:A.applyResult,...A.succeededCount===void 0?{}:{succeeded_count:A.succeededCount},...A.failedCount===void 0?{}:{failed_count:A.failedCount}})},action(A){if(A.stage==="start"&&j(A.flowId,"start")){l+=1;return}if(A.stage==="finish"){if(A.flowId!==void 0&&a.has(A.flowId)){l+=1;return}A.flowId!==void 0&&E(A.flowId)}v("user_game_data_action",{...y(A),stage:A.stage,action_type:A.actionType,...A.outcome===void 0?{}:{outcome:A.outcome},...A.durationMs===void 0?{}:{duration_ms:Math.max(0,Math.round(A.durationMs))}})},access(A){if(i<=0){f+=1;return}if(i<1&&r()>=i){f+=1;return}v("user_game_data_access_result",{...y(A),api:A.api,trigger:A.trigger,status:A.status,duration_ms:Math.max(0,Math.round(A.durationMs)),sample_rate:i,...A.errorCode===void 0?{}:{error_code:A.errorCode},...A.failureStage===void 0?{}:{failure_stage:A.failureStage},...A.cacheHit===void 0?{}:{cache_hit:A.cacheHit},...A.overviewStatusCounts===void 0?{}:{overview_status_counts:A.overviewStatusCounts}})},dispose(){c||(c=!0,o.clear(),s.clear(),a.clear())}}}function PA(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 RA(e){return e===void 0||!Number.isFinite(e)?1:e<=0?0:e>=1?1:e}function Er(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 CA(e){try{return e.resolveEgressTier()==="upload"?"upload":"no_network"}catch{return"no_network"}}function LA(){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 pt(e){const t=qe(e);return t.valid?t.permissions.network?.status==="enabled"||t.permissions.companion?.status==="enabled"?"upload":"no_network":"upload"}function UA(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=p=>E()[p]?.purpose??"",f=p=>{const R=Oo(p);if(!R)throw w("REQUEST_UNSUPPORTED","未开放的资料资源");return R},l=p=>Nl(p,f(p).disclosureRevision,pt(e.runtimePermissions),u(p)),h=()=>DA({storage:e.storage,resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,revisionOf:p=>f(p).disclosureRevision,purposeOf:u,...e.hash?{hash:e.hash}:{}});let m=h();const g=kA({resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,resolveEgressTier:()=>pt(e.runtimePermissions),...e.telemetry??{}}),I=NA({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 E(){const p=qe(e.runtimePermissions),R=p.valid?p.permissions.user_game_data:void 0;return R?.status==="enabled"?Sn(R.config.resources):{}}function b(p){if(t||e.operationContext.signal.aborted)throw w("RUNTIME_DESTROYED","小程序已关闭");if(p?.signal.aborted)throw w("REQUEST_CANCELLED","资料请求已取消")}function y(p){for(const[R,B]of o)B!==void 0&&(p===void 0||B===p)&&R.abort()}function v(p){for(const[R,B]of s)(p===void 0||R===p)&&(B.abort(),s.delete(R))}function j(){r++,v();for(const p of o.keys())p.abort();for(const p of a)e.fileRegistry.revokeFiles([p]);a.clear(),c.clear(),I.invalidate()}const A=Lo(e.account,p=>{if(i&&n===p)return;const R=n;i=!0,n=p,R!==void 0&&(j(),m.dispose(),m=h())}),D=()=>j();e.operationContext.signal.addEventListener("abort",D,{once:!0});async function _(p,R){b(p);const B=new AbortController,Q=()=>B.abort();o.set(B,void 0),p.signal.addEventListener("abort",Q,{once:!0}),p.signal.aborted&&Q();const X={...e.operationContext,...p,signal:B.signal};try{const ne=await R(X);return b(X),ne}catch(ne){throw re(ne)&&ne.name==="AbortError"?w("REQUEST_CANCELLED","资料操作已取消"):ne}finally{p.signal.removeEventListener("abort",Q),o.delete(B)}}function T(p){const R=f(p);if(!u(R.key))throw w("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明这项游戏资料",{resource:R.key});return R}async function N(p){b(p);const R=await e.account.getCurrentUserId(p);if(b(p),!i)i=!0,n=R;else if(n!==R){const B=n;n=R,B!==void 0&&(j(),m.dispose(),m=h(),b(p))}return R}function x(p,R){const B={login_required:"请先登录小黑盒",permission_required:"尚未允许读取这项资料",permission_denied:"已拒绝读取这项资料",source_not_linked:"请先在小黑盒关联对应游戏账号",source_login_required:"请先在小黑盒更新游戏来源登录"},Q=R==="login_required"?{type:"user_login",label:"登录并授权"}:R==="permission_required"?{type:"permission",label:"允许读取"}:R==="permission_denied"&&e.presentation?.openDataPermissions?{type:"manage",label:"管理数据权限"}:void 0;return{status:"blocked",resource:p,reason:R,message:B[R],...Q?{interaction:Q}:{}}}async function M(p,R){T(p);const B=await N(R);if(!B)return x(p,"login_required");const Q=await m.evaluate(B,{resource:p,egressTier:pt(e.runtimePermissions)},R);return b(R),Q.status==="allowed"?{userId:B}:x(p,Q.status==="denied"?"permission_denied":"permission_required")}async function S(p,R,B,Q,X){if(b(X),r!==B||await N(X)!==R||l(p)!==Q)throw w("AUTHORIZATION_CONTEXT_CHANGED","账号或资料范围已变化");return M(p,X)}function O(p,R){if(!re(p)||typeof p.resource!="string")throw w("INVALID_PARAMS","资料请求无效");if(!Rt(p.resource))throw w("REQUEST_UNSUPPORTED","当前宿主尚未开放该资料资源");const B=R==="query"?["resource","operation","schemaVersion","cursor","limit"]:["resource","saveId","fileId"];if(Object.keys(p).some(X=>!B.includes(X)))throw w("INVALID_PARAMS","资料请求包含未知参数");const Q=T(p.resource);if(R==="query"){if(p.operation!=="get"&&p.operation!=="list")throw w("INVALID_PARAMS","资料查询操作无效");const X=Q.queries[p.operation];if(!X)throw w("REQUEST_UNSUPPORTED","资源不支持该查询");if(p.schemaVersion!==X.version)throw w("REQUEST_UNSUPPORTED","SDK 与宿主正文合同版本不匹配");if(p.operation!=="list"&&(p.cursor!==void 0||p.limit!==void 0))throw w("INVALID_PARAMS","单份查询不能分页");if(p.cursor!==void 0&&(typeof p.cursor!="string"||!p.cursor||p.cursor.length>32768))throw w("INVALID_PARAMS","分页游标无效");if(!X.page&&(p.cursor!==void 0||p.limit!==void 0))throw w("INVALID_PARAMS","该列表不支持分页");if(p.limit!==void 0&&(typeof p.limit!="number"||!Number.isInteger(p.limit)||p.limit<1||p.limit>(X.page?.maxSize??100)))throw w("INVALID_PARAMS","分页数量无效")}else if(!Q.operations.includes(R))throw w("REQUEST_UNSUPPORTED","资源不支持该操作");if(R==="file"&&(typeof p.saveId!="string"||!p.saveId||typeof p.fileId!="string"||!p.fileId))throw w("INVALID_PARAMS","资料文件标识无效");return R==="query"?{resource:p.resource,operation:p.operation,schemaVersion:p.schemaVersion,...p.cursor===void 0?{}:{cursor:p.cursor},...p.limit===void 0?{}:{limit:p.limit}}:{resource:p.resource,saveId:p.saveId,fileId:p.fileId}}async function z(p,R,B,Q){const X=d(),ne=r,ie=l(R.resource);for(const ue of o.keys())ue.signal===B.signal&&o.set(ue,R.resource);try{const ue=await M(R.resource,B);if("status"in ue)return g.access({resource:R.resource,api:p,trigger:"initial",status:"blocked",durationMs:d()-X}),ue;let we;try{we=await Q()}catch(ge){const ye=re(ge)?ge.code:void 0;if(ye==="USER_DATA_SOURCE_NOT_LINKED"||ye==="USER_DATA_SOURCE_LOGIN_REQUIRED")return g.access({resource:R.resource,api:p,trigger:"initial",status:"blocked",durationMs:d()-X}),x(R.resource,ye==="USER_DATA_SOURCE_NOT_LINKED"?"source_not_linked":"source_login_required");throw ge}const he=await S(R.resource,ue.userId,ne,ie,B);return"status"in he?(g.access({resource:R.resource,api:p,trigger:"initial",status:"blocked",durationMs:d()-X}),he):(g.access({resource:R.resource,api:p,trigger:"initial",status:re(we)&&we.status==="empty"?"empty":p===dn?"succeeded":"ready",durationMs:d()-X}),we)}catch(ue){throw g.access({resource:R.resource,api:p,trigger:"initial",status:"error",durationMs:d()-X,errorCode:re(ue)?String(ue.code):"REQUEST_FAILED"}),ue}}async function U(p){const R=await N(p);if(!R)throw w("UNAUTHORIZED","请先登录小黑盒");return m.read(R,p,{declared:Object.keys(E()),egressTier:pt(e.runtimePermissions)})}async function L(p,R){const B=T(p);let Q=await N(R);if(Q||(await e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:R.signal}),Q=await N(R)),!Q)return{status:"cancelled"};let X=await m.evaluate(Q,{resource:p,egressTier:pt(e.runtimePermissions)},R);if(X.status==="allowed")return{status:"allowed"};if(X.status==="denied"){if(e.presentation?.openDataPermissions){const Me=r,Re=l(p),je=await e.presentation.openDataPermissions({resource:p,miniProgramName:e.miniProgramPresentation?.name,signal:R.signal});if(!("status"in await S(p,Q,Me,Re,R)))return{status:"allowed"};if(!je)return{status:"cancelled"}}return X=await m.evaluate(Q,{resource:p,egressTier:pt(e.runtimePermissions)},R),{status:X.status==="allowed"?"allowed":"denied"}}if(!e.presentation?.confirmDataPermission)throw w("REQUEST_UNSUPPORTED","当前宿主不支持资料许可弹窗");v(p);const ne=new AbortController;s.set(p,ne);const ie=()=>ne.abort();R.signal.addEventListener("abort",ie,{once:!0}),R.signal.aborted&&ie();const ue={...R,signal:ne.signal},we=r,he=l(p),ge=m,ye=g.beginFlow({resource:p,actionType:"permission"});let Oe="error";try{const Re=(await ge.read(Q,ue,{egressTier:pt(e.runtimePermissions)})).resources.find($t=>$t.resource===p);g.action({resource:p,flowId:ye,stage:"start",actionType:"permission"}),g.permissionShow({resource:p,flowId:ye,entry:"other",reason:Re?.decision==="allow"?"scope_changed":"first"});const je=await fe(()=>e.presentation.confirmDataPermission({miniProgramName:e.miniProgramPresentation?.name,resource:p,scopeText:`此黑盒账号关联的${B.name}${B.operations.includes("sync")?`。${Qh}`:""}`,purposeText:u(p),egress:pt(e.runtimePermissions),canPersist:ge.canPersist,signal:ne.signal}),ne.signal);if(b(ue),r!==we||await N(ue)!==Q||l(p)!==he)throw w("AUTHORIZATION_CONTEXT_CHANGED","资料许可范围已变化");return je.decision==="cancelled"?(Oe="cancelled",g.permissionResult({resource:p,flowId:ye,choice:"cancel",applyResult:"cancelled"}),{status:"cancelled"}):(await ge.decide({userId:Q,resource:p,decision:je.decision==="deny"?"deny":"allow",scope:je.decision==="session"?"session":"persistent",egressTier:pt(e.runtimePermissions),expectedRevision:Re?.revision??0,expectedFingerprint:Re?.scopeFingerprint},ue),je.decision==="deny"&&y(p),Oe=je.decision==="deny"?"unresolved":"resolved",g.permissionResult({resource:p,flowId:ye,choice:je.decision,applyResult:"applied"}),{status:je.decision==="deny"?"denied":"allowed"})}catch(Me){throw Oe=ue.signal.aborted?"cancelled":"error",g.permissionResult({resource:p,flowId:ye,choice:"cancel",applyResult:ue.signal.aborted?"cancelled":"error"}),Me}finally{g.action({resource:p,flowId:ye,stage:"finish",actionType:"permission",outcome:Oe}),R.signal.removeEventListener("abort",ie),s.get(p)===ne&&s.delete(p)}}async function C(p,R,B,Q,X,ne){R==="allow"?T(p):f(p);const ie=await N(Q);if(!ie)throw w("UNAUTHORIZED","请先登录小黑盒");try{await m.decide({userId:ie,resource:p,decision:R,scope:B,expectedRevision:X,expectedFingerprint:ne,egressTier:pt(e.runtimePermissions)},Q)}catch(ue){throw re(ue)&&ue.code==="USER_DATA_PERMISSION_SAVE_FAILED"&&y(p),ue}return v(p),R!=="allow"&&y(p),U(Q)}async function H(p,R,B){try{const Q=await B();return g.permissionManage({operation:p,resource:R,applyResult:"applied"}),Q}catch(Q){throw g.permissionManage({operation:p,resource:R,applyResult:re(Q)&&Q.code==="USER_DATA_PERMISSION_SAVE_FAILED"?"save_failed":"error"}),Q}}async function F(p,R){v(p),y(p);const B=await N(R);if(!B)throw w("UNAUTHORIZED","请先登录小黑盒");return H("revoke",p,async()=>(await m.revokeSession({userId:B,resource:p},R),U(R)))}function G(){let p;const R=B=>_(e.operationContext,async Q=>{const X=await N(Q);if(!X)throw w("UNAUTHORIZED","请先登录小黑盒");if(p&&(p.userId!==X||p.generation!==r))throw w("AUTHORIZATION_CONTEXT_CHANGED","管理页面所属账号已变化,请重新打开");return p??={userId:X,generation:r},B(Q)});return{getSnapshot:()=>R(U),setDecision:B=>R(Q=>H("modify",B.resource,()=>C(B.resource,B.decision,B.scope,Q,B.expectedRevision,B.expectedFingerprint))),revokeSession:B=>R(Q=>F(B?.resource,Q)),resetAll:()=>R(async B=>{v(),y();const Q=await N(B);return H("reset",void 0,async()=>(await m.reset({userId:Q},B),U(B)))})}}return{handlers:{[Ca]:async(p,R)=>_(R,async B=>{if(p!==void 0&&(!re(p)||Object.keys(p).some(ne=>ne!=="game")||p.game!==void 0&&typeof p.game!="string"))throw w("INVALID_PARAMS","概览参数无效");if(re(p)&&typeof p.game=="string"&&!Sc(p.game))throw w("REQUEST_UNSUPPORTED","当前宿主尚未开放该游戏");const Q=Object.keys(E()),X=re(p)?p.game:void 0;return Ml.filter(ne=>X===void 0||ne===X).map(ne=>({game:ne,name:bl[ne],resources:tr.filter(ie=>ie.game===ne&&Q.includes(ie.key)).map(ie=>({resource:ie.key,name:ie.name,status:"not_checked",statusText:"尚未检查"}))})).filter(ne=>ne.resources.length>0)}),[Ii]:async(p,R)=>_(R,B=>{const Q=O(p,"query");return z(Ii,Q,B,()=>I.query(Q,B))}),[dn]:async(p,R)=>_(R,async B=>{if(!re(p)||Object.keys(p).length!==1||typeof p.game!="string"||!Sc(p.game))throw w("INVALID_PARAMS","同步需要指定已开放的游戏");const Q={game:p.game};if(!tr.some(we=>we.game===Q.game&&we.sync))throw w("REQUEST_UNSUPPORTED","该游戏不支持存档同步");const X=tr.filter(we=>we.game===Q.game&&we.sync&&u(we.key));if(X.length===0)throw w("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明可同步的资料");let ne,ie;for(const we of X){const he=await M(we.key,B);if(!("status"in he)){ne=we.key;break}(!ie||ie.reason==="permission_denied")&&(ie=he)}if(!ne)return ie;const ue={resource:ne};return z(dn,ue,B,async()=>{const we=await N(B),he=`${we}\0${ue.resource}`;let ge=c.get(he);if(!ge){const ye=new AbortController;o.set(ye,ue.resource);const Oe={controller:ye,waiters:0,settled:!1,promise:Promise.resolve(void 0)};Oe.promise=I.sync(ue,{...e.operationContext,signal:ye.signal},{userId:we,miniProgramId:e.identity.get()?.miniProgramId??""}).finally(()=>{Oe.settled=!0,o.delete(ye),c.get(he)===Oe&&c.delete(he)}),Oe.promise.catch(()=>{}),c.set(he,Oe),ge=Oe}ge.waiters++;try{return await fe(()=>ge.promise,B.signal)}finally{ge.waiters--,ge.waiters===0&&!ge.settled&&ge.controller.abort()}})}),[_i]:async(p,R)=>_(R,async B=>{const Q=O(p,"file"),X=await N(B),ne=r,ie=l(Q.resource),ue=async he=>{try{const ge=await S(Q.resource,X,ne,ie,he);if("status"in ge)throw w("FILE_ACCESS_REVOKED","文件授权已撤销",{reason:ge.reason})}catch(ge){throw re(ge)&&["AUTHORIZATION_CONTEXT_CHANGED","USER_DATA_RESOURCE_NOT_DECLARED"].includes(String(ge.code))?w("FILE_ACCESS_REVOKED","文件授权已失效",{causeCode:ge.code}):ge}};let we;try{const he=await z(_i,Q,B,async()=>(we=await I.file(Q,B,ue),{handle:we}));if(re(he)&&he.status==="blocked"){const Me=String(he.reason);throw w(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(he.message),{reason:Me})}const ge=he.handle,ye={...ge,read:async Me=>{await ue(Me);const Re=await ge.read(Me);try{return await ue(Me),Re}catch(je){throw Re.fill(0),je}},stat:async Me=>{await ue(Me);const Re=await ge.stat(Me);return await ue(Me),Re}},Oe=e.fileRegistry.registerFile(ye,"download","read");return"handleId"in Oe.ref&&a.add(Oe.ref.handleId),Oe}catch(he){throw we&&await I.releaseFile(we),he}}),[La]:async(p,R)=>{if(!R.trustedUserGesture)throw w("USER_GESTURE_REQUIRED","许可操作需要点击");return _(R,B=>{if(!re(p)||Object.keys(p).length!==1||typeof p.resource!="string"||!Rt(p.resource))throw w("INVALID_PARAMS","许可资源无效");return L(p.resource,B)})},[Ua]:async(p,R)=>_(R,U),[xa]:async(p,R)=>{if(!R.trustedUserGesture)throw w("USER_GESTURE_REQUIRED","修改许可需要点击");if(!re(p)||typeof p.resource!="string"||!Rt(p.resource)||p.decision!=="deny"||p.scope!=="persistent"||Object.keys(p).some(B=>!["resource","decision","scope"].includes(B)))throw w("INVALID_PARAMS","允许许可只能由可信弹窗确认");return _(R,B=>C(p.resource,p.decision,"persistent",B))},[ja]:async(p,R)=>{if(!R.trustedUserGesture)throw w("USER_GESTURE_REQUIRED","管理资料许可需要点击");if(!e.presentation?.openDataPermissions)throw w("REQUEST_UNSUPPORTED","宿主未提供资料管理界面");if(p!==void 0&&(!re(p)||Object.keys(p).some(B=>B!=="resource")||p.resource!==void 0&&(typeof p.resource!="string"||!Rt(p.resource))))throw w("INVALID_PARAMS","管理资源无效");return _(R,async B=>(await e.presentation.openDataPermissions({resource:re(p)?p.resource:void 0,miniProgramName:e.miniProgramPresentation?.name,signal:B.signal}),U(B)))},[za]:async(p,R)=>{if(!R.trustedUserGesture)throw w("USER_GESTURE_REQUIRED","撤销许可需要点击");if(p!==void 0&&(!re(p)||Object.keys(p).some(B=>B!=="resource")||p.resource!==void 0&&(typeof p.resource!="string"||!Rt(p.resource))))throw w("INVALID_PARAMS","撤销资源无效");return _(R,B=>F(re(p)?p.resource:void 0,B))}},get permissionBridge(){return G()},diagnostics:{telemetry:g.diagnostics},dispose(){t||(t=!0,j(),A(),e.operationContext.signal.removeEventListener("abort",D),m.dispose(),g.dispose())}}}function nu(e){throw{code:"INVALID_PARAMS",message:e}}function rn(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function nm(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Kn(e,t,r){return Math.min(nm(e,t),r)}async function xA(e){try{return nm(await e.getNavigationBarHeight(),0)}catch{return 0}}function jA(e,t,r,n){const i=Kn(e.safeArea?.left,0,t),o=Math.max(i,Kn(e.safeArea?.right,t,t)),s=Kn(e.safeArea?.top,n,r),a=Math.max(s,Kn(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function iu(e){const t=e.getViewportMetrics(),r=rn(t.windowWidth,0),n=rn(t.windowHeight,0),i=await xA(e);return{pixelRatio:rn(t.pixelRatio,1),screenWidth:rn(t.screenWidth,r),screenHeight:rn(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:jA(t,r,n,i),screenTop:i}}function zA(e){const t=new AbortController,r={...e,operationContext:{...e.operationContext,signal:t.signal}};let n=!1,i=0,o,s;const a=()=>{if(n||r.operationContext.signal.aborted||!r.onViewportChange)return;const f=++i;iu(r.presentation).then(l=>{if(n||r.operationContext.signal.aborted||f!==i)return;const h=JSON.stringify(l);h!==o&&(o=h,r.onViewportChange?.(l))}).catch(()=>{})},c=WI({...r,onApplied:a}),d=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?d():(s=r.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[nr]:async(f,l)=>c.apply(f,l?.signal),[Ci]:async()=>(pe(r.operationContext.signal),iu(r.presentation)),[Li]:async f=>{if(pe(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return nu("viewport.setNavigationBarStyle 参数必须是对象");const l=f.foregroundStyle;if(l!=="light"&&l!=="dark")return nu("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await fe(()=>r.presentation.setNavigationBarStyle(l,e.operationContext),r.operationContext.signal)}},runDisplayRequest:c.runDisplayRequest,applyOrientation:(f,l)=>c.apply({orientation:f.mode,fullscreen:f.hideCapsule},l),notifyChange:()=>{o=void 0,a()},dispose:d}}function BA(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw Ee("INVALID_PARAMS","工作区卡片刷新参数必须是对象");const t=e;if(Object.keys(t).some(i=>i!=="gameAppId"&&i!=="cardIds"))throw Ee("INVALID_PARAMS","工作区卡片刷新包含未知参数");const{gameAppId:r,cardIds:n}=t;if(r!==void 0&&(typeof r!="string"||!/^[1-9][0-9]{0,9}$/.test(r)||Number(r)>2147483647))throw Ee("INVALID_PARAMS","工作区卡片游戏编号无效");if(n!==void 0&&(!Array.isArray(n)||n.length>3||n.some(i=>typeof i!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(i))||new Set(n).size!==n.length))throw Ee("INVALID_PARAMS","工作区卡片编号无效");return{...r===void 0?{}:{gameAppId:r},...n===void 0?{}:{cardIds:[...n]}}}function HA(e,t){return{[Ai]:async(r,n)=>{const i=Se(t,n.signal,n.requestId);if(pe(i.signal),!e)throw Ee("CAPABILITY_UNAVAILABLE","当前 Host 不支持工作区卡片");const o=BA(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 Ee("HOST_INVALID_RESPONSE","工作区卡片刷新回执无效");return{scheduled:s.scheduled}}}}const FA=new Map(zt.map(e=>[e.method,e]));function cs(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function $A(e){const t=Zl(e);return r=>t(r.requirement,r.method)}function VA(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 GA(e){const t=$A(e.runtimePermissions),r=qe(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??qA,c=e.onTrace?a():0,d=e.onTrace?Date.now():0,u=e.onTrace?s.requestId??`runtime_${++n}`:"";e.onTrace&&ds(e.onTrace,{callId:u,method:i,startedAt:d,outcome:"started"},()=>c,c);try{if(e.terminalSignal.aborted)throw cs("RUNTIME_DESTROYED","小程序 Runtime 已终止");$l(i,e.effectiveCapabilities);const f=FA.get(i);if(!f)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const l=t(f),h=!l.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,o)===!0,m=!l.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,o)===!0,g=!l.allowed&&r.valid&&r.permissions.user_game_data?.status==="enabled"&&e.allowsUserGameDataFileAccess?.(i,o)===!0;if(!l.allowed&&!h&&!m&&!g)throw cs(l.code,l.message,l.data);const I=e.handlers[i];if(!I)throw new Error(`Capability method ${i} 缺少 handler`);const E=async v=>{for(const j of e.policies??[]){const A=await j.evaluate({method:i,payload:o,capability:f});if(e.terminalSignal.aborted||v.aborted)throw su();if(!A.allowed)throw cs(A.code,A.message,A.data)}if(e.terminalSignal.aborted||v.aborted)throw su()},y=await VA(async()=>{if(i===nr){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,E)}return await E(e.terminalSignal),I(o,s)},void 0,s,e.terminalSignal);return e.onTrace&&ds(e.onTrace,ou(u,i,o,d,y),a,c),y}catch(f){throw e.onTrace&&ds(e.onTrace,ou(u,i,o,d,{status:"error",error:f}),a,c),f}}}}function qA(){return typeof performance>"u"?Date.now():performance.now()}function ds(e,t,r,n){if(!e)return;const i=r()-n,o=Date.now();try{e({...t,phase:"host",timestamp:o,durationMs:Math.max(0,Number.isFinite(i)?i:0)})}catch{}}function ou(e,t,r,n,i){const o=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:n,outcome:o,...i.status==="error"?{errorCode:QA(i.error)}:{},...YA(t,r,i)}}function QA(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function YA(e,t,r){if(e!=="network.request"||typeof t!="object"||t===null||!("url"in t)||typeof t.url!="string")return{};try{const n=new URL(t.url);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password)return{};const o=("method"in t&&typeof t.method=="string"?t.method:"GET").trim().toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(o))return{};const s=r.status==="handled"&&la(r.value)&&typeof r.value.status=="number"?r.value.status:void 0;return{network:{method:o,origin:n.origin,pathname:n.pathname,...s===void 0?{}:{responseStatus:s}}}}catch{return{}}}function la(e){return typeof e=="object"&&e!==null}function su(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function WA(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=pw(e.requestPolicy);let n;if(e.files)try{n=sw(e.files,t)}catch{}const i=af({store:n}),o=e.onRequestPolicyReport??(r.debugReport?ZA:void 0),s=r.enabled?fw({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Wa(e.files,e.miniProgramDetail),c=rI({registry:a,picker:e.picker,operationContext:t}),d=Fw({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode,authorizationContext:e.authorizationContext,identityTtlMs:r.identityTtlMs,requestGate:s,requestPolicyEnabled:r.enabled});let u,f,l,h,m,g,I=()=>{},E=()=>{};try{u=zA({operationContext:t,presentation:e.hostPresentation,onDisplayChange:S=>e.eventSink.postEvent("display_change",S),onViewportChange:S=>e.eventSink.postEvent("viewport_change",S)}),l=lA({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}),I=d.onEvent((S,O)=>e.eventSink.postEvent(S,O)),E=e.hostCompanion?.onSessionEvent?.(S=>{const O=ZE(S);!e.terminalSignal.aborted&&O&&e.eventSink.postEvent(O.type,O.payload)})??(()=>{}),h=DE({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const b=e.files&&e.transfer?Ja({files:e.files,transfer:e.transfer,registry:a,signal:t.signal}):void 0,y=UA({identity:e.identity,account:e.account,storage:e.storage,network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,fileDownloads:b,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(S,O){e.onUserDataTelemetry?.({name:S,payload:O})}}}}});g=y,m=LE({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:b,requestGate:s,requestPolicyEnabled:r.enabled});const v=H_({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});f=MI({registry:a,media:e.media,operationContext:t});const j=[{name:"gameSaves",handlers:Object.fromEntries(Object.entries(m.handlers).map(([S,O])=>[S,async(z,U)=>{const L=e.verifiedSdkVersion,C=L?Xa(L,"0.10.0-0"):void 0;if(C===void 0||C>=0)throw w("REQUEST_UNSUPPORTED","当前 SDK 不支持旧游戏存档入口,请使用 user.games.get(...).saves");return O(z,U)}]))},{name:"auth",handlers:Zw({authorization:d})},{name:"user",handlers:{..._A({user:l,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...Xy({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:j_({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:v.handlers},{name:"network",handlers:i_({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins,networkPolicy:e.networkPolicy})},{name:"workspaceCards",handlers:HA(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:q_({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:eI({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:ZI({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:S=>u.applyOrientation({mode:"portrait",hideCapsule:!1},S)}:{}})},{name:"cloud",handlers:h.handlers},{name:"userGameData",handlers:g.handlers},{name:"companion",handlers:GE({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],A=KA(j);let D=!1;const _=()=>{D||(D=!0,e.terminalSignal.removeEventListener("abort",_),u?.dispose(),f?.dispose(),h?.dispose(),m?.dispose(),g?.dispose(),I(),E(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?_():e.terminalSignal.addEventListener("abort",_,{once:!0});const T=new Set(["file.readText","file.readBytes","file.stat"]),N=(S,O)=>T.has(S)&&la(O)&&a.isCompanionAttachmentRef(O.target),x=new Set(["file.readText","file.readBytes","file.stat","file.exists"]),M=(S,O)=>x.has(S)&&la(O)&&a.isUserDataDownloadRef(O.target);return{get permissionBridge(){return y.permissionBridge},modules:j,handlers:A,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:N,allowsGameSaveAccess:m.allowsRead,allowsUserGameDataFileAccess:M,gameSaveDiagnostics:m.diagnostics,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...v.diagnostics?{storageDiagnostics:v.diagnostics}:{},...e.files?{sandboxDiagnostics:lI({registry:a,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},dispose:_}}catch(b){throw u?.dispose(),f?.dispose(),h?.dispose(),m?.dispose(),g?.dispose(),I(),E(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),b}}function ZA(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function KA(e){const t=new Map(zt.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[o,s]of Object.entries(i.handlers)){const a=o,c=t.get(a);if(!c)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${a}`);if(c!==i.name)throw new Error(`Capability method ${a} 应由 ${c} 拥有,不能注册到 ${i.name}`);if(r.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);r.set(a,s)}const n=zt.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==zt.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const JA="heybox-mini-dev:";function au(e){try{return XA(new URL(e))}catch{return!1}}function XA(e){return e.protocol===JA}function e0(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||t0(e)}function t0(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 r0=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function n0(e,t){const r=[],n=i0(e.environmentInfo,r),i=ui(n?.appVersion,"host.appVersion",r),o=s0(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:o0(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:ui(t.miniProgramId),version:ui(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function i0(e,t){if(e!=null){if(im(e))return e;t.push("environmentInfo")}}function o0(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function s0(e,t){if(e==null)return{name:"unknown",version:null};if(!im(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=r0.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:ui(e.version,"operatingSystem.version",t)}}function ui(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function im(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const a0="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",c0="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",d0="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",u0="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function l0(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?d0:a0,l.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const h=e.createElement("div");h.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${c};border-radius:11px;padding:0 7px 0 6px;`;const m=e.createElement("img");m.src=a?u0:c0,m.style.cssText="width:12px;height:12px;flex-shrink:0;";const g=e.createElement("span");g.textContent=t?.trim()||"小程序工坊",g.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const I=e.createElement("div");I.textContent="小黑盒工坊小程序",I.style.cssText=`margin-top:6px;color:${a?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,h.append(m,g),f.append(l,h),u.append(f,I),s.append(u),e.body.append(s);const E=()=>{s.remove(),n.removeEventListener("abort",E)};n.addEventListener("abort",E,{once:!0});try{return await fe(()=>Promise.all([l.decode(),m.decode()]),n),await fe(()=>new Promise(b=>{let y=o.requestAnimationFrame(()=>{y=o.requestAnimationFrame(()=>{n.removeEventListener("abort",v),b()})});const v=()=>o.cancelAnimationFrame(y);n.addEventListener("abort",v,{once:!0})}),n),E}catch(b){throw E(),b}}const f0=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"]),m0=new Set(["url","inline","eval","unknown"]),h0=/^\/(?:\:segment(?:\/\:segment)*)?$/,g0=/^[a-f0-9]{64}$/,p0=255,y0=160,w0=256;function E0(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!f0.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>w0||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!m0.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=I0(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>y0||!h0.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!g0.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 I0(e){if(e!==void 0&&!(typeof e!="string"||e.length>p0))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const zo=["android","ios","ohos","windows","macos","linux"],_0="0.9.0",A0=Object.freeze(["android","ios","ohos","windows","macos"]),om="该小程序暂不支持当前平台",D0="PLATFORM_UNSUPPORTED";function b0(e){return typeof e=="string"&&zo.includes(e)}function M0(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 S0(e){const t=e.manifest;if(!k0(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=du(e.sdkVersion)??du(t.sdkVersion);return v0(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:T0()}const r=sm(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function N0(e){const t=M0(e.operatingSystemName);if(!t)return Ar("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Ar("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:zo,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=S0({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Ar("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):cu(t,s)}if(r.effectivePlatforms===void 0)return Ar("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=sm(r.effectivePlatforms);if("reason"in n)return Ar("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=O0(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return cu(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function cu(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Ar("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Ar(e,t={}){return{status:"denied",reason:e,message:om,...t}}function T0(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:A0,platformsDeclared:!1,policy:"legacy_mobile_default"}}function sm(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(!b0(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(zo.filter(r=>t.has(r)))}}function v0(e){if(typeof e!="string"||!e.trim())return!1;const t=Xa(e.trim(),_0);return t!==void 0&&t>=0}function du(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function O0(e){return e==="explicit"||e==="legacy_mobile_default"}function k0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function P0(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:R0(i.pathname),sanitizedPathnameHash:$a(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function R0(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}const C0=1e4,L0=1e4,us=2e3,U0=2,x0="open-with-native-credential-policy",am="安全提示",cm="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class j0{nonce=$c();runtimeId=$c();terminalController=new AbortController;options;handshakeTimeout;ports;primitiveAvailability;effectiveCapabilities;identity;identityRef;iframe;iframeErrorListener;iframeLoadListener;bridgeServer=null;miniProgramSrc="";launchUrl="";startPromise=null;readyContext=null;resolveReady;rejectReady;terminalError;status="idle";stateValue="idle";handshakeTimeoutTimer;lifecycleDisposer;workspaceCardsDisposer;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;failureTransitionInProgress=!1;destroyRequestedDuringFailure=!1;sdkVersionDecision;platformGateDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;unexpectedDocumentLoadTimer;devDocumentDisposer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;networkPolicy;networkPolicyDisposer;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=Gl(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??C0,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??Ee("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??Ee("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(Z0(),this.startPromise=this.createReadyPromise(),this.setState("starting"),this.setStatus("starting"),this.launch().catch(t=>{this.failRuntime(t)}),this.startPromise)}destroy(){if(this.failureTransitionInProgress){this.destroyRequestedDuringFailure=!0;return}if(this.stateValue==="destroyed")return;const t=this.terminalError??Ee("RUNTIME_DESTROYED","小程序运行时已销毁");this.terminalError=t,this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.teardownIframe(),this.rejectReady?.(t)}show(){const t=this.hostVisible;this.hostVisible=!0,this.emitLifecycleEvent("show"),this.capabilityGraph?.notifyViewportChange(),!t&&this.stateValue==="ready"&&this.sdkVersionDecision?.heartbeatEnabled&&(this.documentRevalidationPending?this.preparedHistoryTraversalGeneration!==void 0?this.armDocumentRevalidationTimer(this.documentRevalidationGeneration,{waitingForDocument:!0}):this.resendDocumentRevalidationProbe():this.sendLocationProbe())}hide(){this.hostVisible=!1,this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.emitLifecycleEvent("hide")}prepareForHistoryTraversal(){if(this.stateValue!=="ready"||this.bridgeServer?.protocolVersion!==2||!this.sdkVersionDecision?.heartbeatEnabled)return()=>{};const t=this.beginDocumentRevalidation({deferProbe:!0});return this.isInactive()||t!==this.documentRevalidationGeneration?()=>{}:(this.preparedHistoryTraversalGeneration=t,()=>{this.preparedHistoryTraversalGeneration===t&&this.cancelPreparedHistoryTraversal()})}createReadyPromise(){return new Promise((t,r)=>{this.resolveReady=t,this.rejectReady=r})}async launch(){const t=await this.resolveRuntimeLaunchConfiguration();if(this.isInactive())return;if(this.runtimePermissions=dy(t.runtimePermissions),this.networkPolicy=ql(t.networkPolicy),this.networkPolicy?.enforcement==="restricted"){const s=t.canonicalIdentity?.miniProgramId?.trim();if(!s||!this.options.networkPolicyEnforcement)throw{code:"NETWORK_POLICY_UNSUPPORTED",message:"当前 Host 尚未具备严格网络策略执行能力,请更新 Host 后重新打开"};const a=await Gp(this.options.networkPolicyEnforcement,{policy:this.networkPolicy,miniProgramId:s,launchUrl:t.launchUrl,onInvalidated:()=>this.failRuntime({code:"NETWORK_POLICY_CHANGED",message:"网络权限已变更,请重新打开小程序"})},{signal:this.terminalController.signal});if(this.isInactive()){a();return}this.networkPolicyDisposer=a}this.runtimeFeatures=t.runtimeFeatures?Object.freeze({...t.runtimeFeatures}):void 0,this.miniProgramPresentation=t.miniProgramPresentation,this.locationBasePath=t.locationBasePath,this.anonymousStorageScope=t.anonymousStorageScope??this.options.anonymousStorageScope;const r=t.allowedHttpOrigins??this.options.allowedHttpOrigins;this.allowedHttpOrigins=r?Object.freeze([...r]):void 0,this.bindCanonicalIdentity(t.canonicalIdentity),this.sdkVersionDecision=Ky(t.sdkVersionPolicy);const n=n0(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=N0({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw X0(this.platformGateDecision);if(this.miniProgramDetail=eD(t),this.effectiveCapabilities=Vl(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),G0(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(Q0(i)),this.launchUrl=i,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const s=Ql(new URL(i),this.locationBasePath);this.devDocumentDisposer=cy({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=ey(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=Va(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:nr,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,ot(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&(n!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(n!=="display_change"||this.effectiveCapabilities[nr])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=WA({verifiedSdkVersion:this.sdkVersionDecision?.sdkVersion,diagnosticCapabilities:this.effectiveCapabilities,account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,media:this.ports.media,transfer:this.ports.transfer,storage:this.ports.storage,scopedStorage:this.ports.scopedStorage,storageDiagnostics:this.ports.storageDiagnostics,hostPresentation:this.ports.presentation,hostCompanion:this.ports.companion,hostProtocol:this.ports.protocol,...this.options.userDataPresentation===void 0?{}:{userDataPresentation:this.options.userDataPresentation},...this.options.onUserDataTelemetry===void 0?{}:{onUserDataTelemetry:this.options.onUserDataTelemetry},workspaceCards:this.ports.workspaceCards,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,networkPolicy:this.networkPolicy,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,prepareLongScreenshot:(n,i)=>Vp(this.iframe,n,i),prepareScreenshot:(n,i,o)=>{const s=this.sdkVersionDecision?.sdkVersion;return!s||(Xa(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):l0(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=GA({handlers:this.capabilityGraph.handlers,runDisplayRequest:this.capabilityGraph.runDisplayRequest,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,allowsGameSaveAccess:this.capabilityGraph.allowsGameSaveAccess,allowsUserGameDataFileAccess:this.capabilityGraph.allowsUserGameDataFileAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:u})=>{const f={type:"capability",phase:"host",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...u?{network:u}:{}};ot(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new hy({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,...this.options.onDevUploadSession?{onDevUploadSession:n=>{this.isInactive()||ot(this.options.onDevUploadSession,n)}}:{},...this.ports.workspaceCards?{getWorkspaceCardLaunchContext:()=>this.ports.workspaceCards.getLaunchContext()}:{},onHandshake:n=>this.handleBridgeHandshake(n),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:n=>{this.handleInternalBridgeEvent(n)},onResponsePosted:({method:n,outcome:i,errorCode:o})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:n,outcome:i,...o?{errorCode:o}:{}})}}),this.bridgeServer.start(),this.workspaceCardsDisposer=this.ports.workspaceCards?.onLaunchContextChange(()=>this.publishWorkspaceCardLaunchContext()),this.setStatus("bridge_started"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge_started"})}onIframeError(t=new Error("小程序 iframe 加载失败")){if(this.isInactive())return;const r=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(Ee("IFRAME_LOAD_ERROR",r,t))}emitLifecycleEvent(t){if(this.stateValue!=="ready"){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle_ignored",event:t,reason:this.isInactive()?"inactive":"not_ready"});return}this.bridgeServer?.postEvent(t,{timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle",method:t})}async resolveRuntimeLaunchConfiguration(){try{return await this.options.resolveLaunchConfiguration()}catch(t){throw V0(t)?t:dm(Ee("STARTUP_ERROR",t instanceof Error?t.message:"获取小程序启动配置失败"),t)}}bindCanonicalIdentity(t){const r=t?.miniProgramId?.trim();r&&(this.identity.miniProgramId=r);const n=t?.miniProgramVersion?.trim();n&&(this.identity.miniProgramVersion=n)}async normalizeLaunchUrl(t){try{const r=this.options.environment.getCurrentHref();return Xp(t,r,{allowPrivateNetwork:au(r)||uu(r)||await this.isDevRuntime()})}catch(r){throw Ee("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??W0)({message:cm,title:am,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Gc(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!au(r)&&!uu(r)}async closeAfterDevLaunchCancellation(){const t=Ee("LAUNCH_CANCELLED","小程序启动已取消");this.terminalError=t,this.destroyBridgeServer();const r=new AbortController;let n;try{n=Promise.resolve(this.ports.presentation.close({signal:r.signal}))}catch{lu(),n=Promise.resolve()}this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"launch_cancelled"}),this.rejectReady?.(t),await n.catch(()=>lu())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Wp),this.iframe.setAttribute("referrerpolicy",Zp),this.iframe.setAttribute("sandbox",Yl)}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{Jy(r,t?.sdkVersion)}catch(n){return this.failRuntime(n),!1}return!0}armHandshakeTimeout(){this.clearHandshakeTimeout(),!(this.handshakeTimeout<=0)&&(this.handshakeTimeoutTimer=setTimeout(()=>{this.stateValue==="ready"||this.isInactive()||(this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"handshake_timeout"}),this.failRuntime(Ee("SDK_HANDSHAKE_TIMEOUT","小程序 SDK 握手超时")))},this.handshakeTimeout))}clearHandshakeTimeout(){this.handshakeTimeoutTimer&&(clearTimeout(this.handshakeTimeoutTimer),this.handshakeTimeoutTimer=void 0)}sendLocationProbe(){if(this.isInactive()||!this.hostVisible||!this.sdkVersionDecision?.heartbeatEnabled||this.documentRevalidationPending)return;if(this.pendingProbeId&&(this.consecutiveHeartbeatMisses+=1,this.consecutiveHeartbeatMisses>=U0)){this.failRuntime(Ee("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Hn,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},us),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Hn})}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(Hn,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Hn})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&this.failRuntime(Ee("DOCUMENT_REVALIDATION_TIMEOUT",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时"))},r.waitingForDocument?L0:us))}clearDocumentRevalidationTimer(){this.documentRevalidationTimer&&(clearTimeout(this.documentRevalidationTimer),this.documentRevalidationTimer=void 0)}completeDocumentRevalidation(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.iframeHiddenForRevalidation&&this.iframe.style.visibility==="hidden"&&(this.iframe.style.visibility=this.iframeVisibilityBeforeRevalidation??""),this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1,this.hostVisible&&this.sdkVersionDecision?.heartbeatEnabled&&(this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},us)),this.traceDocumentValidation()}traceDocumentValidation(){this.isInactive()||this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"document_validation",documentVerifying:this.documentRevalidationPending,message:this.documentRevalidationPending?"当前文档正在验证":"当前文档验证等待已结束"})}clearDocumentRevalidation(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1}cancelPreparedHistoryTraversal(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.iframeHiddenForRevalidation&&this.iframe.style.visibility==="hidden"&&(this.iframe.style.visibility=this.iframeVisibilityBeforeRevalidation??""),this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1,this.hostVisible&&this.sdkVersionDecision?.heartbeatEnabled&&this.sendLocationProbe(),this.traceDocumentValidation()}handleDuplicateBridgeHandshake(){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"}),this.documentRevalidationPending&&this.resendDocumentRevalidationProbe()}handleInternalBridgeEvent(t){if(t.method===vh){this.handleCspViolation(t.payload);return}if(t.method!==Th)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(Ee("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Wl(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(Ee("URL_OUT_OF_SCOPE","小程序页面地址超出允许范围"));return}n.probeId!==void 0?(this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.documentRevalidationPending&&this.completeDocumentRevalidation()):this.documentRevalidationPending&&!this.pendingProbeId&&(this.preparedHistoryTraversalGeneration=void 0,this.sendDocumentRevalidationProbe())}}handleCspViolation(t){const r=E0(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=P0(t,r,this.sdkVersionDecision?.sdkVersion);this.emitSecurityViolation(n)}scheduleUnexpectedDocumentLoadFailure(){this.clearUnexpectedDocumentLoadFailure(),this.unexpectedDocumentLoadTimer=setTimeout(()=>{this.unexpectedDocumentLoadTimer=void 0,this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(Ee("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 发生未授权文档加载"))},50)}clearUnexpectedDocumentLoadFailure(){this.unexpectedDocumentLoadTimer&&(clearTimeout(this.unexpectedDocumentLoadTimer),this.unexpectedDocumentLoadTimer=void 0)}traceSecurityPolicy(t){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"security",sandboxPolicyVersion:Yp,launchUrlType:Gc(t),networkPolicy:x0})}failRuntime(t){const r=z0(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,B0(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 z0(e){const t=Va(e);return ho(e)&&"cause"in e&&dm(t,e.cause),t}function dm(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function B0(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{},...e.cause!==void 0?{cause:$0(e.cause)}:{}}}const ls=(()=>{const e=Object.getOwnPropertyDescriptor(new Error,"stack")?.get,t=Object.getOwnPropertyDescriptor(new Error,"stack")?.get;return typeof e=="function"&&e===t?e:void 0})(),H0=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function F0(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return;if("value"in r)return r.value;if(t!=="stack"||!ls||r.get!==ls)return;const n=Object.getPrototypeOf(e);if(H0.has(n)){for(const i of["name","message"]){const o=Object.getOwnPropertyDescriptor(e,i),s=Object.getOwnPropertyDescriptor(n,i)??Object.getOwnPropertyDescriptor(Error.prototype,i);if(o&&!("value"in o)||s&&!("value"in s))return}return ls.call(e)}}function $0(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=F0(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 V0(e){return ho(e)&&typeof e.code=="string"&&typeof e.message=="string"}function ho(e){return!!e&&typeof e=="object"}function ot(e,t){try{e?.(t)}catch{}}function G0(e,t,r){try{e?.(t,r)}catch{}}function uu(e){try{const t=new URL(e);return t.protocol==="http:"&&e0(t.hostname)}catch{return!1}}function q0(e){try{return new URL(e).origin}catch{return}}function Q0(e){return Kp()?"*":q0(e)}function Y0(e){return`${am}
|
|
6
|
+
|
|
7
|
+
${cm}
|
|
8
|
+
|
|
9
|
+
URL: ${e}`}function W0(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(Y0(e.url))}function lu(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function Z0(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,r=typeof window>"u"?void 0:window,n=Object.freeze({protocolVersion:gl,knownMethodCount:zt.length,supportsFileCreate:zt.some(i=>i.method===En),system:K0(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:Ir(e?.hardwareConcurrency),maxTouchPoints:Ir(e?.maxTouchPoints),screen:{width:Ir(t?.width),height:Ir(t?.height)},viewport:{width:Ir(r?.innerWidth),height:Ir(r?.innerHeight),devicePixelRatio:J0(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function K0(e="",t=""){const r=`${t} ${e}`.toLowerCase();return/iphone|ipad|ipod/.test(r)?"ios":r.includes("android")?"android":/win32|win64|windows/.test(r)?"windows":/darwin|macintosh|macintel|mac os/.test(r)?"macos":/linux|x11/.test(r)?"linux":"unknown"}function Ir(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function J0(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function X0(e){return Ee(D0,om,{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 eD(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 tD(e){if(!ho(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!ho(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 j0(e)}function rD(e={}){return async(t,r,n)=>{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");const i=e.indexedDB??globalThis.indexedDB,o=e.crypto??globalThis.crypto;if(!i||!o?.getRandomValues)throw new Error("Host 缺少持久化账号标识能力");const s=await new Promise((a,c)=>{const d=i.open("heybox-mini-program-private-account-v1",1);let u=!1;const f=()=>n.signal.removeEventListener("abort",h),l=m=>{u||(u=!0,f(),c(m))},h=()=>l(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{u?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>l(d.error),d.onblocked=()=>l(new Error("账号存储被阻塞")),d.onsuccess=()=>{u?d.result.close():(u=!0,f(),a(d.result))},n.signal.addEventListener("abort",h,{once:!0}),n.signal.aborted&&h()});try{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");return await new Promise((a,c)=>{const d=s.transaction("accounts","readwrite"),u=d.objectStore("accounts"),f=JSON.stringify([t,r]);let l;const h=()=>{try{d.abort()}catch{}m(),c(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",h,{once:!0});const m=()=>n.signal.removeEventListener("abort",h);d.oncomplete=()=>{m(),a(l)},d.onabort=d.onerror=()=>{m(),c(d.error??new Error("账号存储事务失败"))};const g=u.get(f);g.onsuccess=()=>{try{if(typeof g.result=="string"&&/^ak_[0-9a-f]{64}$/.test(g.result))l=g.result;else{const I=o.getRandomValues(new Uint8Array(32));l=`ak_${Array.from(I,E=>E.toString(16).padStart(2,"0")).join("")}`,u.put(l,f)}}catch{d.abort()}}})}finally{s.close()}}}const nD=/^(?: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,iD=new Set(["origin","referer","user-agent"]);function oD(e,t){return _p({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=sD(r),a=await e.authenticatedRequest(s,o);return dD(a)})}).network}function sD(e){const t=aD(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function aD(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!cD(t)))}function cD(e){const t=e.trim().toLowerCase();return iD.has(t)}function dD(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:uD(e.headers)??{}}}function uD(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!lD(t)))}function lD(e){const t=e.trim().toLowerCase();return nD.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function fD(e,t,r){const n=yD(e.presentation,t);return{account:gD(e,t,r),network:oD(e,t),...e.storage===void 0?{}:{storage:pD(e,t)},...e.storage===void 0?{}:mD(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function mD(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 hD(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 gD(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??rD();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 pD(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 yD(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)=>Rp(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 wD(){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 Jn(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 Jn(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(Jn(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 Jn(f.reason);return u}finally{for(const{listener:u,source:f}of c)f.removeEventListener("abort",u)}}}}function Jn(e){return new DOMException("Web Host operation aborted","AbortError")}async function ED(e){const t=wD(),r=new Set;let n=!1;const i=l=>{if(n||t.signal.aborted)return fs(l),()=>{};let h=!0;const m=()=>{h&&(h=!1,r.delete(m),fs(l))};return r.add(m),m},o=()=>s(e.signal.reason),s=l=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(l);for(const h of[...r])h();e.onDispose&&fs(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=fD(e,t,i);a.storage?.getRaw&&a.storage.setRaw&&(a.scopedStorage=Qf({storage:a.storage,diagnostics:a.storageDiagnostics,coordinationKey:e.storage.storage,lock:Yf,resolveScope:async()=>qf((await f()).configuration)}));const c=Gl(a,{hostCapabilities:e.hostCapabilities,hasUserDataPresentation:e.userDataPresentation!==void 0,hasUserDataSettings:e.userDataPresentation?.openDataPermissions!==void 0}),d=hD(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:ID(e.authPresentation,t)},...e.userDataPresentation===void 0?{}:{userDataPresentation:_D(e.userDataPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function fs(e){try{e()}catch{}}function ID(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 _D(e,t){return{...e.openDataPermissions?{openDataPermissions:r=>t.run(r.signal,n=>e.openDataPermissions({...r,signal:n}))}:{},confirmDataPermission:r=>t.run(r.signal,n=>e.confirmDataPermission({...r,signal:n}))}}var _r={},ms,fu;function AD(){return fu||(fu=1,ms=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),ms}var hs={},kt={},mu;function cr(){if(mu)return kt;mu=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return kt.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},kt.getSymbolTotalCodewords=function(n){return t[n]},kt.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},kt.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},kt.isKanjiModeEnabled=function(){return typeof e<"u"},kt.toSJIS=function(n){return e(n)},kt}var gs={},hu;function ac(){return hu||(hu=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,i){if(e.isValid(n))return n;try{return t(n)}catch{return i}}})(gs)),gs}var ps,gu;function DD(){if(gu)return ps;gu=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},ps=e,ps}var ys,pu;function bD(){if(pu)return ys;pu=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,i){const o=t*this.size+r;this.data[o]=n,i&&(this.reservedBit[o]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},ys=e,ys}var ws={},yu;function MD(){return yu||(yu=1,(function(e){const t=cr().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const i=Math.floor(n/7)+2,o=t(n),s=o===145?26:Math.ceil((o-13)/(2*i-2))*2,a=[o-7];for(let c=1;c<i-1;c++)a[c]=a[c-1]-s;return a.push(6),a.reverse()},e.getPositions=function(n){const i=[],o=e.getRowColCoords(n),s=o.length;for(let a=0;a<s;a++)for(let c=0;c<s;c++)a===0&&c===0||a===0&&c===s-1||a===s-1&&c===0||i.push([o[a],o[c]]);return i}})(ws)),ws}var Es={},wu;function SD(){if(wu)return Es;wu=1;const e=cr().getSymbolSize,t=7;return Es.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},Es}var Is={},Eu;function ND(){return Eu||(Eu=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,d=null,u=null;for(let f=0;f<o;f++){a=c=0,d=u=null;for(let l=0;l<o;l++){let h=i.get(f,l);h===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=h,a=1),h=i.get(l,f),h===u?c++:(c>=5&&(s+=t.N1+(c-5)),u=h,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const d=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(d===4||d===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let d=0;d<o;d++){a=c=0;for(let u=0;u<o;u++)a=a<<1&2047|i.get(d,u),u>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(u,d),u>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let d=0;d<s;d++){o(d),e.applyMask(d,i);const u=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(d,i),u<c&&(c=u,a=d)}return a}})(Is)),Is}var Xn={},Iu;function um(){if(Iu)return Xn;Iu=1;const e=ac(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Xn.getBlocksCount=function(i,o){switch(o){case e.L:return t[(i-1)*4+0];case e.M:return t[(i-1)*4+1];case e.Q:return t[(i-1)*4+2];case e.H:return t[(i-1)*4+3];default:return}},Xn.getTotalCodewordsCount=function(i,o){switch(o){case e.L:return r[(i-1)*4+0];case e.M:return r[(i-1)*4+1];case e.Q:return r[(i-1)*4+2];case e.H:return r[(i-1)*4+3];default:return}},Xn}var _s={},nn={},_u;function TD(){if(_u)return nn;_u=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let i=0;i<255;i++)e[i]=n,t[n]=i,n<<=1,n&256&&(n^=285);for(let i=255;i<512;i++)e[i]=e[i-255]})(),nn.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},nn.exp=function(n){return e[n]},nn.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},nn}var Au;function vD(){return Au||(Au=1,(function(e){const t=TD();e.mul=function(n,i){const o=new Uint8Array(n.length+i.length-1);for(let s=0;s<n.length;s++)for(let a=0;a<i.length;a++)o[s+a]^=t.mul(n[s],i[a]);return o},e.mod=function(n,i){let o=new Uint8Array(n);for(;o.length-i.length>=0;){const s=o[0];for(let c=0;c<i.length;c++)o[c]^=t.mul(i[c],s);let a=0;for(;a<o.length&&o[a]===0;)a++;o=o.slice(a)}return o},e.generateECPolynomial=function(n){let i=new Uint8Array([1]);for(let o=0;o<n;o++)i=e.mul(i,new Uint8Array([1,t.exp(o)]));return i}})(_s)),_s}var As,Du;function OD(){if(Du)return As;Du=1;const e=vD();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(n.length+this.degree);i.set(n);const o=e.mod(i,this.genPoly),s=this.degree-o.length;if(s>0){const a=new Uint8Array(this.degree);return a.set(o,s),a}return o},As=t,As}var Ds={},bs={},Ms={},bu;function lm(){return bu||(bu=1,Ms.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Ms}var yt={},Mu;function fm(){if(Mu)return yt;Mu=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
|
|
10
|
+
]))+`;yt.KANJI=new RegExp(r,"g"),yt.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),yt.BYTE=new RegExp(n,"g"),yt.NUMERIC=new RegExp(e,"g"),yt.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return yt.testKanji=function(c){return i.test(c)},yt.testNumeric=function(c){return o.test(c)},yt.testAlphanumeric=function(c){return s.test(c)},yt}var Su;function dr(){return Su||(Su=1,(function(e){const t=lm(),r=fm();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(o,s){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!t.isValid(s))throw new Error("Invalid version: "+s);return s>=1&&s<10?o.ccBits[0]:s<27?o.ccBits[1]:o.ccBits[2]},e.getBestModeForData=function(o){return r.testNumeric(o)?e.NUMERIC:r.testAlphanumeric(o)?e.ALPHANUMERIC:r.testKanji(o)?e.KANJI:e.BYTE},e.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},e.isValid=function(o){return o&&o.bit&&o.ccBits};function n(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+i)}}e.from=function(o,s){if(e.isValid(o))return o;try{return n(o)}catch{return s}}})(bs)),bs}var Nu;function kD(){return Nu||(Nu=1,(function(e){const t=cr(),r=um(),n=ac(),i=dr(),o=lm(),s=7973,a=t.getBCHDigit(s);function c(l,h,m){for(let g=1;g<=40;g++)if(h<=e.getCapacity(g,m,l))return g}function d(l,h){return i.getCharCountIndicator(l,h)+4}function u(l,h){let m=0;return l.forEach(function(g){const I=d(g.mode,h);m+=I+g.getBitsLength()}),m}function f(l,h){for(let m=1;m<=40;m++)if(u(l,m)<=e.getCapacity(m,h,i.MIXED))return m}e.from=function(h,m){return o.isValid(h)?parseInt(h,10):m},e.getCapacity=function(h,m,g){if(!o.isValid(h))throw new Error("Invalid QR Code version");typeof g>"u"&&(g=i.BYTE);const I=t.getSymbolTotalCodewords(h),E=r.getTotalCodewordsCount(h,m),b=(I-E)*8;if(g===i.MIXED)return b;const y=b-d(g,h);switch(g){case i.NUMERIC:return Math.floor(y/10*3);case i.ALPHANUMERIC:return Math.floor(y/11*2);case i.KANJI:return Math.floor(y/13);case i.BYTE:default:return Math.floor(y/8)}},e.getBestVersionForData=function(h,m){let g;const I=n.from(m,n.M);if(Array.isArray(h)){if(h.length>1)return f(h,I);if(h.length===0)return 1;g=h[0]}else g=h;return c(g.mode,g.getLength(),I)},e.getEncodedBits=function(h){if(!o.isValid(h)||h<7)throw new Error("Invalid QR Code version");let m=h<<12;for(;t.getBCHDigit(m)-a>=0;)m^=s<<t.getBCHDigit(m)-a;return h<<12|m}})(Ds)),Ds}var Ss={},Tu;function PD(){if(Tu)return Ss;Tu=1;const e=cr(),t=1335,r=21522,n=e.getBCHDigit(t);return Ss.getEncodedBits=function(o,s){const a=o.bit<<3|s;let c=a<<10;for(;e.getBCHDigit(c)-n>=0;)c^=t<<e.getBCHDigit(c)-n;return(a<<10|c)^r},Ss}var Ns={},Ts,vu;function RD(){if(vu)return Ts;vu=1;const e=dr();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let i,o,s;for(i=0;i+3<=this.data.length;i+=3)o=this.data.substr(i,3),s=parseInt(o,10),n.put(s,10);const a=this.data.length-i;a>0&&(o=this.data.substr(i),s=parseInt(o,10),n.put(s,a*3+1))},Ts=t,Ts}var vs,Ou;function CD(){if(Ou)return vs;Ou=1;const e=dr(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(i){let o;for(o=0;o+2<=this.data.length;o+=2){let s=t.indexOf(this.data[o])*45;s+=t.indexOf(this.data[o+1]),i.put(s,11)}this.data.length%2&&i.put(t.indexOf(this.data[o]),6)},vs=r,vs}var Os,ku;function LD(){if(ku)return Os;ku=1;const e=dr();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,i=this.data.length;n<i;n++)r.put(this.data[n],8)},Os=t,Os}var ks,Pu;function UD(){if(Pu)return ks;Pu=1;const e=dr(),t=cr();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(i){return i*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let i;for(i=0;i<this.data.length;i++){let o=t.toSJIS(this.data[i]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+`
|
|
11
|
+
Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},ks=r,ks}var Ps={exports:{}},Ru;function xD(){return Ru||(Ru=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,d,u,f,l,h,m,g,I;!a.empty();){c=a.pop(),d=c.value,f=c.cost,l=r[d]||{};for(u in l)l.hasOwnProperty(u)&&(h=l[u],m=f+h,g=s[u],I=typeof s[u]>"u",(I||g>m)&&(s[u]=m,a.push(u,m),o[u]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var E=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(E)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var i=[],o=n;o;)i.push(o),r[o],o=r[o];return i.reverse(),i},find_path:function(r,n,i){var o=t.single_source_shortest_paths(r,n,i);return t.extract_shortest_path_from_predecessor_list(o,i)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,i={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);return i.queue=[],i.sorter=r.sorter||n.default_sorter,i},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var i={value:r,cost:n};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Ps)),Ps.exports}var Cu;function jD(){return Cu||(Cu=1,(function(e){const t=dr(),r=RD(),n=CD(),i=LD(),o=UD(),s=fm(),a=cr(),c=xD();function d(E){return unescape(encodeURIComponent(E)).length}function u(E,b,y){const v=[];let j;for(;(j=E.exec(y))!==null;)v.push({data:j[0],index:j.index,mode:b,length:j[0].length});return v}function f(E){const b=u(s.NUMERIC,t.NUMERIC,E),y=u(s.ALPHANUMERIC,t.ALPHANUMERIC,E);let v,j;return a.isKanjiModeEnabled()?(v=u(s.BYTE,t.BYTE,E),j=u(s.KANJI,t.KANJI,E)):(v=u(s.BYTE_KANJI,t.BYTE,E),j=[]),b.concat(y,v,j).sort(function(D,_){return D.index-_.index}).map(function(D){return{data:D.data,mode:D.mode,length:D.length}})}function l(E,b){switch(b){case t.NUMERIC:return r.getBitsLength(E);case t.ALPHANUMERIC:return n.getBitsLength(E);case t.KANJI:return o.getBitsLength(E);case t.BYTE:return i.getBitsLength(E)}}function h(E){return E.reduce(function(b,y){const v=b.length-1>=0?b[b.length-1]:null;return v&&v.mode===y.mode?(b[b.length-1].data+=y.data,b):(b.push(y),b)},[])}function m(E){const b=[];for(let y=0;y<E.length;y++){const v=E[y];switch(v.mode){case t.NUMERIC:b.push([v,{data:v.data,mode:t.ALPHANUMERIC,length:v.length},{data:v.data,mode:t.BYTE,length:v.length}]);break;case t.ALPHANUMERIC:b.push([v,{data:v.data,mode:t.BYTE,length:v.length}]);break;case t.KANJI:b.push([v,{data:v.data,mode:t.BYTE,length:d(v.data)}]);break;case t.BYTE:b.push([{data:v.data,mode:t.BYTE,length:d(v.data)}])}}return b}function g(E,b){const y={},v={start:{}};let j=["start"];for(let A=0;A<E.length;A++){const D=E[A],_=[];for(let T=0;T<D.length;T++){const N=D[T],x=""+A+T;_.push(x),y[x]={node:N,lastCount:0},v[x]={};for(let M=0;M<j.length;M++){const S=j[M];y[S]&&y[S].node.mode===N.mode?(v[S][x]=l(y[S].lastCount+N.length,N.mode)-l(y[S].lastCount,N.mode),y[S].lastCount+=N.length):(y[S]&&(y[S].lastCount=N.length),v[S][x]=l(N.length,N.mode)+4+t.getCharCountIndicator(N.mode,b))}}j=_}for(let A=0;A<j.length;A++)v[j[A]].end=0;return{map:v,table:y}}function I(E,b){let y;const v=t.getBestModeForData(E);if(y=t.from(b,v),y!==t.BYTE&&y.bit<v.bit)throw new Error('"'+E+'" cannot be encoded with mode '+t.toString(y)+`.
|
|
12
|
+
Suggested mode is: `+t.toString(v));switch(y===t.KANJI&&!a.isKanjiModeEnabled()&&(y=t.BYTE),y){case t.NUMERIC:return new r(E);case t.ALPHANUMERIC:return new n(E);case t.KANJI:return new o(E);case t.BYTE:return new i(E)}}e.fromArray=function(b){return b.reduce(function(y,v){return typeof v=="string"?y.push(I(v,null)):v.data&&y.push(I(v.data,v.mode)),y},[])},e.fromString=function(b,y){const v=f(b,a.isKanjiModeEnabled()),j=m(v),A=g(j,y),D=c.find_path(A.map,"start","end"),_=[];for(let T=1;T<D.length-1;T++)_.push(A.table[D[T]].node);return e.fromArray(h(_))},e.rawSplit=function(b){return e.fromArray(f(b,a.isKanjiModeEnabled()))}})(Ns)),Ns}var Lu;function zD(){if(Lu)return hs;Lu=1;const e=cr(),t=ac(),r=DD(),n=bD(),i=MD(),o=SD(),s=ND(),a=um(),c=OD(),d=kD(),u=PD(),f=dr(),l=jD();function h(A,D){const _=A.size,T=o.getPositions(D);for(let N=0;N<T.length;N++){const x=T[N][0],M=T[N][1];for(let S=-1;S<=7;S++)if(!(x+S<=-1||_<=x+S))for(let O=-1;O<=7;O++)M+O<=-1||_<=M+O||(S>=0&&S<=6&&(O===0||O===6)||O>=0&&O<=6&&(S===0||S===6)||S>=2&&S<=4&&O>=2&&O<=4?A.set(x+S,M+O,!0,!0):A.set(x+S,M+O,!1,!0))}}function m(A){const D=A.size;for(let _=8;_<D-8;_++){const T=_%2===0;A.set(_,6,T,!0),A.set(6,_,T,!0)}}function g(A,D){const _=i.getPositions(D);for(let T=0;T<_.length;T++){const N=_[T][0],x=_[T][1];for(let M=-2;M<=2;M++)for(let S=-2;S<=2;S++)M===-2||M===2||S===-2||S===2||M===0&&S===0?A.set(N+M,x+S,!0,!0):A.set(N+M,x+S,!1,!0)}}function I(A,D){const _=A.size,T=d.getEncodedBits(D);let N,x,M;for(let S=0;S<18;S++)N=Math.floor(S/3),x=S%3+_-8-3,M=(T>>S&1)===1,A.set(N,x,M,!0),A.set(x,N,M,!0)}function E(A,D,_){const T=A.size,N=u.getEncodedBits(D,_);let x,M;for(x=0;x<15;x++)M=(N>>x&1)===1,x<6?A.set(x,8,M,!0):x<8?A.set(x+1,8,M,!0):A.set(T-15+x,8,M,!0),x<8?A.set(8,T-x-1,M,!0):x<9?A.set(8,15-x-1+1,M,!0):A.set(8,15-x-1,M,!0);A.set(T-8,8,1,!0)}function b(A,D){const _=A.size;let T=-1,N=_-1,x=7,M=0;for(let S=_-1;S>0;S-=2)for(S===6&&S--;;){for(let O=0;O<2;O++)if(!A.isReserved(N,S-O)){let z=!1;M<D.length&&(z=(D[M]>>>x&1)===1),A.set(N,S-O,z),x--,x===-1&&(M++,x=7)}if(N+=T,N<0||_<=N){N-=T,T=-T;break}}}function y(A,D,_){const T=new r;_.forEach(function(O){T.put(O.mode.bit,4),T.put(O.getLength(),f.getCharCountIndicator(O.mode,A)),O.write(T)});const N=e.getSymbolTotalCodewords(A),x=a.getTotalCodewordsCount(A,D),M=(N-x)*8;for(T.getLengthInBits()+4<=M&&T.put(0,4);T.getLengthInBits()%8!==0;)T.putBit(0);const S=(M-T.getLengthInBits())/8;for(let O=0;O<S;O++)T.put(O%2?17:236,8);return v(T,A,D)}function v(A,D,_){const T=e.getSymbolTotalCodewords(D),N=a.getTotalCodewordsCount(D,_),x=T-N,M=a.getBlocksCount(D,_),S=T%M,O=M-S,z=Math.floor(T/M),U=Math.floor(x/M),L=U+1,C=z-U,H=new c(C);let F=0;const G=new Array(M),K=new Array(M);let p=0;const R=new Uint8Array(A.buffer);for(let ie=0;ie<M;ie++){const ue=ie<O?U:L;G[ie]=R.slice(F,F+ue),K[ie]=H.encode(G[ie]),F+=ue,p=Math.max(p,ue)}const B=new Uint8Array(T);let Q=0,X,ne;for(X=0;X<p;X++)for(ne=0;ne<M;ne++)X<G[ne].length&&(B[Q++]=G[ne][X]);for(X=0;X<C;X++)for(ne=0;ne<M;ne++)B[Q++]=K[ne][X];return B}function j(A,D,_,T){let N;if(Array.isArray(A))N=l.fromArray(A);else if(typeof A=="string"){let z=D;if(!z){const U=l.rawSplit(A);z=d.getBestVersionForData(U,_)}N=l.fromString(A,z||40)}else throw new Error("Invalid data");const x=d.getBestVersionForData(N,_);if(!x)throw new Error("The amount of data is too big to be stored in a QR Code");if(!D)D=x;else if(D<x)throw new Error(`
|
|
13
|
+
The chosen QR Code version cannot contain this amount of data.
|
|
14
|
+
Minimum version required to store current data is: `+x+`.
|
|
15
|
+
`);const M=y(D,_,N),S=e.getSymbolSize(D),O=new n(S);return h(O,D),m(O),g(O,D),E(O,_,0),D>=7&&I(O,D),b(O,M),isNaN(T)&&(T=s.getBestMask(O,E.bind(null,O,_))),s.applyMask(T,O),E(O,_,T),{modules:O,version:D,errorCorrectionLevel:_,maskPattern:T,segments:N}}return hs.create=function(D,_){if(typeof D>"u"||D==="")throw new Error("No input text");let T=t.M,N,x;return typeof _<"u"&&(T=t.from(_.errorCorrectionLevel,t.M),N=d.from(_.version),x=s.from(_.maskPattern),_.toSJISFunc&&e.setToSJISFunction(_.toSJISFunc)),j(D,N,T,x)},hs}var Rs={},Cs={},Uu;function mm(){return Uu||(Uu=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),d=Math.floor((s+o.margin*2)*c),u=o.margin*c,f=[o.color.light,o.color.dark];for(let l=0;l<d;l++)for(let h=0;h<d;h++){let m=(l*d+h)*4,g=o.color.light;if(l>=u&&h>=u&&l<d-u&&h<d-u){const I=Math.floor((l-u)/c),E=Math.floor((h-u)/c);g=f[a[I*s+E]?1:0]}n[m++]=g.r,n[m++]=g.g,n[m++]=g.b,n[m]=g.a}}})(Cs)),Cs}var xu;function BD(){return xu||(xu=1,(function(e){const t=mm();function r(i,o,s){i.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=s,o.width=s,o.style.height=s+"px",o.style.width=s+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(o,s,a){let c=a,d=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(d=n()),c=t.getOptions(c);const u=t.getImageWidth(o.modules.size,c),f=d.getContext("2d"),l=f.createImageData(u,u);return t.qrToImageData(l.data,o,c),r(f,d,u),f.putImageData(l,0,0),d},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const d=e.render(o,s,c),u=c.type||"image/png",f=c.rendererOpts||{};return d.toDataURL(u,f.quality)}})(Rs)),Rs}var Ls={},ju;function HD(){if(ju)return Ls;ju=1;const e=mm();function t(i,o){const s=i.a/255,a=o+'="'+i.hex+'"';return s<1?a+" "+o+'-opacity="'+s.toFixed(2).slice(1)+'"':a}function r(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function n(i,o,s){let a="",c=0,d=!1,u=0;for(let f=0;f<i.length;f++){const l=Math.floor(f%o),h=Math.floor(f/o);!l&&!d&&(d=!0),i[f]?(u++,f>0&&l>0&&i[f-1]||(a+=d?r("M",l+s,.5+h+s):r("m",c,0),c=0,d=!1),l+1<o&&i[f+1]||(a+=r("h",u),u=0)):c++}return a}return Ls.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,u=o.modules.data,f=d+c.margin*2,l=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(c.color.dark,"stroke")+' d="'+n(u,d,c.margin)+'"/>',m='viewBox="0 0 '+f+" "+f+'"',I='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+m+' shape-rendering="crispEdges">'+l+h+`</svg>
|
|
16
|
+
`;return typeof a=="function"&&a(null,I),I},Ls}var zu;function FD(){if(zu)return _r;zu=1;const e=AD(),t=zD(),r=BD(),n=HD();function i(o,s,a,c,d){const u=[].slice.call(arguments,1),f=u.length,l=typeof u[f-1]=="function";if(!l&&!e())throw new Error("Callback required as last argument");if(l){if(f<2)throw new Error("Too few arguments provided");f===2?(d=a,a=s,s=c=void 0):f===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=s,s=c=void 0):f===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(h,m){try{const g=t.create(a,c);h(o(g,s,c))}catch(g){m(g)}})}try{const h=t.create(a,c);d(null,o(h,s,c))}catch(h){d(h)}}return _r.create=t.create,_r.toCanvas=i.bind(null,r.render),_r.toDataURL=i.bind(null,r.renderToDataURL),_r.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),_r}var Bu=FD();function $D(e){const t=`hb-game-saves-${crypto.randomUUID()}`,r=c=>`hb-sdk:game-save-cache:${c}`;let n,i;const o=new Promise((c,d)=>{n=c,i=d});let s;const a=new Promise(c=>{s=c});return e.signal.addEventListener("abort",s,{once:!0}),e.signal.aborted&&s(),e.locks.request(r(t),async()=>{let c;try{c=await e.getRoot();const d=await e.locks.request("hb-sdk:game-save-cache:gc",async()=>{e.signal.throwIfAborted();for await(const[u,f]of c)f.kind!=="directory"||!/^hb-game-saves-[a-f0-9-]{36}$/.test(u)||await e.locks.request(r(u),{ifAvailable:!0},async l=>{l&&await Hu(c,u)});return e.signal.throwIfAborted(),c.getDirectoryHandle(t,{create:!0})});e.signal.throwIfAborted(),n(d),await a}catch(d){i(d)}finally{e.signal.removeEventListener("abort",s),c&&await Hu(c,t).catch(()=>{})}}).catch(i),o.catch(()=>{}),o}async function Hu(e,t){for(let r=0;;r++)try{await e.removeEntry(t,{recursive:!0});return}catch(n){if(n instanceof DOMException&&n.name==="NotFoundError")return;if(!(n instanceof DOMException)||n.name!=="NoModificationAllowedError"||r>=4)throw n;await new Promise(i=>setTimeout(i,25*(r+1)))}}const Us=8*1024*1024,VD=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),GD="/__hb_sdk__/game-save-download",Ve=(e,t)=>({code:e,message:t});function qD(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=$D({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 Ve("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存");return m.slice(15)}async function u(m,g){a(g);const I=d(m);try{return await(await c()).getFileHandle(I)}catch(E){throw E instanceof DOMException&&E.name==="NotFoundError"?Ve("FILE_NOT_FOUND","存档缓存不存在"):E}}function f(m){const g={kind:"file",mode:"readwrite",name:m.split("/").at(-1),async create(I,E){a(E);const b=d(m),y=await c();if(I.exclusive)try{throw await y.getFileHandle(b),Ve("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(v){if(!(v instanceof DOMException&&v.name==="NotFoundError"))throw v}a(E),await y.getFileHandle(b,{create:!0}),a(E)},async remove(I){a(I);const E=d(m);if(i)try{await(await i).removeEntry(E)}catch(b){if(!(b instanceof DOMException&&b.name==="NotFoundError"))throw b}},async read(I){const E=await(await u(m,I)).getFile();if(E.size>Us)throw Ve("FILE_TOO_LARGE","存档文件超过 8 MiB");const b=new Uint8Array(await E.arrayBuffer());try{return a(I),b}catch(y){throw b.fill(0),y}},async write(){throw Ve("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(I){const E=await(await u(m,I)).getFile();return a(I),{kind:"file",size:E.size,modifiedAt:E.lastModified}}};return o.set(g,m),g}const l=async()=>{throw Ve("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},h={kind:"directory",mode:"readwrite",name:"",file:f,directory(m){return{...h,name:m,async create(g,I){if(a(I),m!==".hb-game-saves")return l();await c(),a(I)}}},create:l,stat:l,list:l};return{files:{sandbox:h},transfer:{network:{async open(m,g){if(a(g),!Bl(m))throw Ve("METHOD_FORBIDDEN","仅支持受控存档下载");const I=await(e.fetch??fetch)(GD,{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([g.signal,e.signal,AbortSignal.timeout(6e4)])});if(!I.ok){const E=await I.json().catch(()=>({}));throw Ve(E.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return s.add(I),{status:I.status,headers:Object.fromEntries(Array.from(I.headers).filter(([E])=>VD.has(E)).map(([E,b])=>[E,[b]])),body:I}},async release(m){s.delete(m),await m.body?.cancel()}},files:{async writeResource(m,g,I,E){let b,y;try{a(E);const v=o.get(m);if(!v||!s.delete(g))throw Ve("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(I.mode!=="replace-existing")throw Ve("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(b=await(await u(v,E)).createWritable(),!g.body)throw Ve("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");y=g.body.getReader();let A=0;for(;;){a(E);const D=await y.read().catch(_=>{throw a(E),Ve(_ instanceof DOMException&&_.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(a(E),D.done)break;if(A+=D.value.byteLength,A>Math.min(I.maxBytes??Us,Us))throw Ve("FILE_TOO_LARGE","存档文件超过 8 MiB");await b.write(new Uint8Array(D.value)),E.onProgress(A)}if(I.expectedBytes!==void 0&&A!==I.expectedBytes)throw Ve("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return a(E),await b.close(),b=void 0,{committedBytes:A}}catch(v){throw v instanceof DOMException&&v.name==="QuotaExceededError"?Ve("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):v}finally{await y?.cancel().catch(()=>{}),y||await g.body?.cancel().catch(()=>{}),await b?.abort().catch(()=>{}),s.delete(g)}}}}}}function wt(e,t){throw{code:e,message:t}}function QD(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(),wt("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:c,browser:d}=a,u=Gg(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(),wt("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态")),(d.source!=="remote"||d.miniProgramId!==c.miniProgramId||d.devSessionId!==u.session_id||d.contextRevision!==u.revision||c.devSessionId!==u.session_id||c.contextRevision!==u.revision)&&(i(),wt("AUTHORIZATION_CONTEXT_CHANGED","开发快照正在更新,请稍后重试"));const f={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:f,key:JSON.stringify([a.userId,a.accountRevision,f]),expiresAt:c.expiresAt}}async function s(a,c){const d=c.signal;let u;try{u=await e.request({source:"runtime-private",credentials:"heybox-session",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:"heybox.user_miniprogram.runtime.auth.context.post",path:"/user_miniprogram/runtime/auth/context",channel:"api"},method:"POST",bodyEncoding:"form",data:a.body,timeout:1e4},c)}catch(g){d.throwIfAborted();const I=g&&typeof g=="object"&&"code"in g?String(g.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(I)&&wt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(I)||g instanceof DOMException&&["AbortError","TimeoutError"].includes(g.name))throw g;wt("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted(),o().key!==a.key&&wt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const f=u.data;(u.status===401||f?.status==="login"||f?.status==="relogin")&&wt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(u.status!==200||f?.status!=="ok")&&wt("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const l=f.result,h=Number(l?.expires_at)*1e3;(typeof l?.token!="string"||!l.token.trim()||!Number.isSafeInteger(l?.expires_at)||!Number.isSafeInteger(h)||h<=t()||!["legacy","local","server"].includes(String(l.user_data_mode)))&&wt("INVALID_RESPONSE","开发运行授权响应无效");const m={token:l.token,expiresAt:Math.min(h,a.expiresAt),steamAccount:l.steam_account===!0,userDataMode:l.user_data_mode};return r={key:a.key,value:m},m}return{async get(a){const c=AbortSignal.any([a.signal,e.signal]);c.throwIfAborted(),await e.refreshAccount(c),c.throwIfAborted();const d=o();if(r?.key===d.key&&r.value.expiresAt>t()+3e4)return r.value;i();let u=n.get(d.key);if(!u||u.controller.signal.aborted){const l=new AbortController,h=s(d,{...a,signal:AbortSignal.any([l.signal,e.signal])});u={promise:h,controller:l,users:0},n.set(d.key,u);const m=u;h.finally(()=>{n.get(d.key)===m&&n.delete(d.key)}).catch(()=>{})}u.users++;let f;try{const l=await Promise.race([u.promise,new Promise((h,m)=>{f=()=>m(c.reason),c.addEventListener("abort",f,{once:!0}),c.aborted&&f()})]);return c.throwIfAborted(),o().key!==d.key&&wt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),l}finally{c.removeEventListener("abort",f),--u.users===0&&u.controller.abort()}}}}const YD="/__hb_sdk__/dev-context";function Fu(e,t){return vn(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId:void 0,developmentSnapshot:typeof e.developmentSnapshot=="string"?e.developmentSnapshot:void 0,developmentSnapshotDigest:typeof e.developmentSnapshotDigest=="string"?e.developmentSnapshotDigest:void 0,localDevLaunchToken:typeof e.localDevLaunchToken=="string"?e.localDevLaunchToken:void 0,runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,publishedRuntimePermissions:e.publishedRuntimePermissions,warning:typeof e.warning=="string"?e.warning:void 0,declaredPermissions:vn(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 ln(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Tl(e.localDevGrant);return!r.valid||!e.devSessionId?.trim()||!Number.isSafeInteger(e.contextRevision)||e.contextRevision!==r.grant.revision||!e.expiresAt||!Number.isFinite(e.expiresAt)||e.source!=="remote"&&e.expiresAt<=t?{...e,localDevGrant:void 0,warning:"本地临时授权无效或已过期,已降权"}:{...e,...e.expiresAt<=t?{source:"anonymous",localDevLaunchToken:void 0,expiresAt:t+3e4}:{},localDevGrant:eg({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 WD(e){if(!vn(e)||!$u(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!vn(t)||!$u(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const ZD={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Bo(e){const t=qe(e.localDevGrant?Fa({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}}:JD()}function hm(e,t,r){return r?.localDevGrant?Fa({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:gm(e,t,t.networkRequest.useOfficialDomain)}function KD(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=Bo({...e,localDevGrant:void 0});return gm(e.runtimePermissions,t,!1)}function JD(){return{networkRequest:{...ZD.networkRequest}}}function gm(e,t,r){const n=qe(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of sr){const a=n.permissions[s];a&&i.push(s==="network"?{key:s,status:t.networkRequest.status,config:{useOfficialDomain:r}}:s==="user_game_data"?{key:s,status:a.status,config:{resources:a.config.resources}}:{key:s,status:a.status,config:{}})}const o=vn(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 vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function $u(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function XD(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 eb(e){return XD({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 tb(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,o;return{schedule:s,reset(){n=t,a()},dispose(){i||(i=!0,a())}};function s(){i||e.isDisposed()||(a(),o=e.timers.setTimeout(async()=>{o=void 0;let c;try{c=await e.invalidate()}catch{c={ok:!1}}if(!(i||e.isDisposed())){if(c.ok){n=t,e.connectEvents();return}n=Math.min(n*2,r),s()}},n))}function a(){o!==void 0&&e.timers.clearTimeout(o),o=void 0}}const xs=new WeakMap;function cc(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}const{root:n,signal:i}=e;xs.set(n,document.activeElement);const o=[...n.querySelectorAll("button[data-action]")];n.dataset.hostDialog="true",n.style.zIndex="40";const s=()=>[...document.querySelectorAll("[data-host-dialog]")].at(-1);n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-label",e.title);let a;const c=()=>{i?.removeEventListener("abort",u),document.removeEventListener("keydown",l);const m=s()===n;if(n.remove(),m){const g=s();g&&(g.inert=!1,g.removeAttribute("aria-hidden"));let I=xs.get(n)??null;for(;I instanceof HTMLElement&&!I.isConnected;){const E=I.closest("[data-host-dialog]");I=E?xs.get(E)??null:null}I instanceof HTMLElement&&(!g||g.contains(I))?I.focus():g?.querySelector("button")?.focus()}},d=Qm({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 g=o[0],I=o.at(-1);m.shiftKey&&document.activeElement===g?(m.preventDefault(),I.focus()):!m.shiftKey&&document.activeElement===I&&(m.preventDefault(),g.focus())}if(!d.active)return;if(i?.aborted){u();return}for(const m of o)m.addEventListener("click",()=>f(m.dataset.action));n.addEventListener("click",m=>{m.target===n&&e.cancelAction&&f(e.cancelAction)}),n.dataset.interactionId=d.interactionId;const h=s();h&&(h.inert=!0,h.setAttribute("aria-hidden","true")),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n),i?.addEventListener("abort",u,{once:!0}),document.addEventListener("keydown",l),o[0]?.focus(),i?.aborted&&u()})}function et(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}const Vu="hb-sdk-action-dialog-style";async function Ho(e){await pm(e)}async function rb(e){return await pm({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function pm(e){ab();const t=document.createElement("div");return t.className="hb-sdk-action-dialog",t.innerHTML=`
|
|
17
|
+
<div class="hb-sdk-action-dialog__panel">
|
|
18
|
+
<h2>${et(e.title)}</h2>
|
|
19
|
+
<pre class="hb-sdk-action-dialog__detail">${et(e.detail)}</pre>
|
|
20
|
+
<div class="hb-sdk-action-dialog__actions">
|
|
21
|
+
${e.confirmation?'<button type="button" data-action="cancel">取消</button>':""}
|
|
22
|
+
<button type="button" class="primary" data-action="confirm">${e.confirmation?"关注":"确定"}</button>
|
|
23
|
+
</div>
|
|
24
|
+
</div>`,await cc({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 nb(e,t){await Ho({method:"navigation.openAppPage",title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+Ur(e.params)].join(`
|
|
25
|
+
`),signal:t.signal,callId:t.requestId})}async function ib(e,t){await Ho({method:"navigation.openAppPage",title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+Ur(e.extra)].join(`
|
|
26
|
+
`),signal:t.signal,callId:t.requestId})}async function ob(e,t){await Ho({method:"share.showShareMenu",title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+Ur(e.channel),"post: "+Ur(e.post)].join(`
|
|
27
|
+
`),signal:t.signal,callId:t.requestId})}async function sb(e,t){await Ho({method:"share.screenshot",title:"截图分享",detail:["rect: "+Ur(e.rect),"post: "+Ur(e.post)].join(`
|
|
28
|
+
`),signal:t.signal,callId:t.requestId})}function Ur(e){return JSON.stringify(e,null,2)}function ab(){if(document.getElementById(Vu))return;const e=document.createElement("style");e.id=Vu,e.textContent=`
|
|
29
|
+
.hb-sdk-action-dialog {
|
|
30
|
+
position: absolute;
|
|
31
|
+
inset: 0;
|
|
32
|
+
display: grid;
|
|
33
|
+
place-items: center;
|
|
34
|
+
padding: 24px;
|
|
35
|
+
background: rgba(15, 23, 42, 0.45);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
.hb-sdk-action-dialog__panel {
|
|
39
|
+
width: min(420px, 100%);
|
|
40
|
+
border-radius: 12px;
|
|
41
|
+
padding: 20px;
|
|
42
|
+
background: #fff;
|
|
43
|
+
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
.hb-sdk-action-dialog__panel h2 {
|
|
47
|
+
margin: 0 0 8px;
|
|
48
|
+
font-size: 18px;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
.hb-sdk-action-dialog__detail {
|
|
52
|
+
margin: 0 0 16px;
|
|
53
|
+
max-height: 40vh;
|
|
54
|
+
overflow: auto;
|
|
55
|
+
color: #1f2933;
|
|
56
|
+
font-family: inherit;
|
|
57
|
+
font-size: 12px;
|
|
58
|
+
line-height: 1.6;
|
|
59
|
+
white-space: pre-wrap;
|
|
60
|
+
overflow-wrap: anywhere;
|
|
61
|
+
word-break: break-word;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
.hb-sdk-action-dialog__actions {
|
|
65
|
+
display: flex;
|
|
66
|
+
justify-content: flex-end;
|
|
67
|
+
gap: 8px;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
.hb-sdk-action-dialog__actions button {
|
|
71
|
+
min-height: 36px;
|
|
72
|
+
border: 1px solid #cad5e2;
|
|
73
|
+
border-radius: 6px;
|
|
74
|
+
padding: 0 12px;
|
|
75
|
+
background: #fff;
|
|
76
|
+
cursor: pointer;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
.hb-sdk-action-dialog__actions .primary {
|
|
80
|
+
border-color: #2563eb;
|
|
81
|
+
color: #fff;
|
|
82
|
+
background: #2563eb;
|
|
83
|
+
}
|
|
84
|
+
`,document.head.appendChild(e)}const cb={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};async function db(e){const t=document.createElement("div");return t.className="hb-sdk-auth-dialog",t.innerHTML=`
|
|
85
|
+
<div class="hb-sdk-auth-dialog__panel">
|
|
86
|
+
<h2>授权请求</h2>
|
|
87
|
+
<p class="hb-sdk-auth-dialog__app">${et(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
|
|
88
|
+
<ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(n=>`<li>${et(cb[n]||n)}</li>`).join("")}</ul>
|
|
89
|
+
${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${et(e.userProfile.nickname)}</p>`:""}
|
|
90
|
+
<div class="hb-sdk-auth-dialog__actions">
|
|
91
|
+
<button type="button" data-action="deny">拒绝</button>
|
|
92
|
+
<button type="button" class="primary" data-action="allow">允许</button>
|
|
93
|
+
</div>
|
|
94
|
+
</div>
|
|
95
|
+
`,await cc({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function ub(e){const t=e.miniProgramName?.trim();return{launchUrl:e.launchUrl,...e.locationBasePath!==void 0?{locationBasePath:e.locationBasePath}:{},...t?{miniProgramPresentation:{name:t}}:{},sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:wc,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:zo},sdkVersion:wc},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const Gu="hb-sdk-user-data-dialog-style",lb=new Map(tr.map(e=>[e.key,e.name]));function fb(e){return(Rt(e)?lb.get(e):void 0)??"游戏资料"}function mb(e){return e==="upload"?"可上传":"无网络权限"}async function hb(e){pb();const t=e.miniProgramName?.trim()||"当前小程序",r=fb(e.resource),n=`“${t}”想读取你的${r}`,i=mb(e.egress),o=fp[e.egress],s=e.egress==="upload"?"↑":"⊘",a=document.createElement("div");a.className="hb-sdk-user-data-dialog",a.innerHTML=`
|
|
96
|
+
<div class="hb-sdk-user-data-dialog__panel">
|
|
97
|
+
<h2>${et(n)}</h2>
|
|
98
|
+
<dl class="hb-sdk-user-data-dialog__meta">
|
|
99
|
+
<dt>范围</dt><dd>${et(e.scopeText)}</dd>
|
|
100
|
+
<dt>用途</dt><dd>${et(e.purposeText)}</dd>
|
|
101
|
+
</dl>
|
|
102
|
+
<p class="hb-sdk-user-data-dialog__egress" data-egress="${et(e.egress)}">
|
|
103
|
+
<span class="hb-sdk-user-data-dialog__egress-label" aria-hidden="true">${et(s)}</span>
|
|
104
|
+
<span class="hb-sdk-user-data-dialog__egress-tag">${et(i)}</span>
|
|
105
|
+
<span>${et(o)}</span>
|
|
106
|
+
</p>
|
|
107
|
+
<p class="hb-sdk-user-data-dialog__mock-note">Browser Mock:不会写入真实设备许可,也不会触发来源登录。</p>
|
|
108
|
+
<div class="hb-sdk-user-data-dialog__actions">
|
|
109
|
+
<button type="button" data-action="deny">拒绝</button>
|
|
110
|
+
<button type="button" data-action="session">本次使用允许</button>
|
|
111
|
+
${e.canPersist===!1?"":'<button type="button" class="primary" data-action="persistent">在此设备上始终允许</button>'}
|
|
112
|
+
</div>
|
|
113
|
+
</div>
|
|
114
|
+
`;const c=await cc({root:a,title:n,method:"user.dataPermission.confirm",mode:"browser",signal:e.signal,cancelAction:"cancelled"});return{decision:gb(c)}}function gb(e){return e==="deny"||e==="session"||e==="persistent"?e:"cancelled"}function pb(){if(document.getElementById(Gu))return;const e=document.createElement("style");e.id=Gu,e.textContent=`
|
|
115
|
+
.hb-sdk-user-data-dialog {
|
|
116
|
+
position: absolute;
|
|
117
|
+
inset: 0;
|
|
118
|
+
display: grid;
|
|
119
|
+
place-items: center;
|
|
120
|
+
padding: 24px;
|
|
121
|
+
background: rgba(15, 23, 42, 0.45);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
.hb-sdk-user-data-dialog__panel {
|
|
125
|
+
width: min(440px, 100%);
|
|
126
|
+
border-radius: 12px;
|
|
127
|
+
padding: 20px;
|
|
128
|
+
background: #fff;
|
|
129
|
+
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
.hb-sdk-user-data-dialog__panel h2 {
|
|
133
|
+
margin: 0 0 12px;
|
|
134
|
+
font-size: 17px;
|
|
135
|
+
line-height: 1.45;
|
|
136
|
+
color: #1f2933;
|
|
137
|
+
overflow-wrap: anywhere;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
.hb-sdk-user-data-dialog__meta {
|
|
141
|
+
display: grid;
|
|
142
|
+
grid-template-columns: auto 1fr;
|
|
143
|
+
gap: 4px 10px;
|
|
144
|
+
margin: 0 0 12px;
|
|
145
|
+
font-size: 12px;
|
|
146
|
+
line-height: 1.6;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
.hb-sdk-user-data-dialog__meta dt {
|
|
150
|
+
color: #7b8794;
|
|
151
|
+
white-space: nowrap;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
.hb-sdk-user-data-dialog__meta dd {
|
|
155
|
+
white-space: pre-wrap;
|
|
156
|
+
margin: 0;
|
|
157
|
+
color: #1f2933;
|
|
158
|
+
overflow-wrap: anywhere;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
.hb-sdk-user-data-dialog__egress {
|
|
162
|
+
display: flex;
|
|
163
|
+
flex-wrap: wrap;
|
|
164
|
+
align-items: baseline;
|
|
165
|
+
gap: 6px;
|
|
166
|
+
margin: 0 0 10px;
|
|
167
|
+
padding: 10px 12px;
|
|
168
|
+
border: 1px solid #cad5e2;
|
|
169
|
+
border-radius: 8px;
|
|
170
|
+
font-size: 12px;
|
|
171
|
+
line-height: 1.6;
|
|
172
|
+
color: #1f2933;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
.hb-sdk-user-data-dialog__egress[data-egress="upload"] {
|
|
176
|
+
border-color: #e0b34d;
|
|
177
|
+
background: #fff8e6;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
.hb-sdk-user-data-dialog__egress[data-egress="no_network"] {
|
|
181
|
+
border-color: #9fb3c8;
|
|
182
|
+
background: #f2f6fa;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
.hb-sdk-user-data-dialog__egress-label {
|
|
186
|
+
font-weight: 700;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
.hb-sdk-user-data-dialog__egress-tag {
|
|
190
|
+
font-weight: 700;
|
|
191
|
+
white-space: nowrap;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
.hb-sdk-user-data-dialog__mock-note {
|
|
195
|
+
margin: 0 0 16px;
|
|
196
|
+
font-size: 11px;
|
|
197
|
+
line-height: 1.6;
|
|
198
|
+
color: #7b8794;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
.hb-sdk-user-data-dialog__actions {
|
|
202
|
+
display: flex;
|
|
203
|
+
flex-wrap: wrap;
|
|
204
|
+
justify-content: flex-end;
|
|
205
|
+
gap: 8px;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
.hb-sdk-user-data-dialog__actions button {
|
|
209
|
+
min-height: 36px;
|
|
210
|
+
border: 1px solid #cad5e2;
|
|
211
|
+
border-radius: 6px;
|
|
212
|
+
padding: 0 12px;
|
|
213
|
+
background: #fff;
|
|
214
|
+
color: #1f2933;
|
|
215
|
+
cursor: pointer;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
.hb-sdk-user-data-dialog__actions .primary {
|
|
219
|
+
border-color: #2563eb;
|
|
220
|
+
color: #fff;
|
|
221
|
+
background: #2563eb;
|
|
222
|
+
}
|
|
223
|
+
`,document.head.appendChild(e)}const yb=["ready","no_data","updating","user_login","source_invalid","source_link_required","unavailable","failed","unknown"];function wb(e){switch(e){case"ready":return"ready";case"no_data":return"empty";case"updating":return"updating";case"user_login":case"source_invalid":case"source_link_required":return"blocked";case"unavailable":case"failed":return"unavailable";case"unknown":return"unknown"}}function Eb(e){let t,r,n="",i=0,o=0,s="undecided",a="ready",c,d="";const u=new Set,f=new Set,l=()=>{for(const g of f)g()},h=async()=>{const g=t,I=JSON.stringify(e.resolveScope()),E=++i;if(!g){r=void 0,c=void 0,l();return}try{const b=await g.getSnapshot();if(E!==i||t!==g||I!==JSON.stringify(e.resolveScope()))return;r=b,n=I,c=void 0}catch(b){if(E!==i||t!==g||I!==JSON.stringify(e.resolveScope()))return;d=I,c=b instanceof Error?b.message:"许可状态不可用"}l()},m=async g=>{const I=t,E=JSON.stringify(e.resolveScope());if(!I)return;i++;const b=++o;try{if(await g(I),b!==o||t!==I||E!==JSON.stringify(e.resolveScope()))return;await h()}catch(y){if(b!==o||t!==I||E!==JSON.stringify(e.resolveScope()))return;d=E,c=y instanceof Error?y.message:"许可设置失败",l()}};return{bind(g){o++,c=void 0,t=g,r=void 0,h()},refresh:h,snapshot(){const g=e.declared?.()??{resources:Lt,source:"mock-default"},I=JSON.stringify(e.resolveScope());return{scenario:s,dataScenario:a,egressTier:e.egressTier(),declaredSource:g.source,permissionStateReady:r!==void 0&&n===I,stateError:d===I?c:void 0,simulatedSession:[...u].filter(E=>r?.resources.find(b=>b.resource===E)?.sessionAllowed),resources:tr.map(E=>{const b=(n===I?r:void 0)?.resources.find(v=>v.resource===E.key),y=b?.allowed===!0;return{resource:E.key,name:E.name,declared:g.resources.includes(E.key),decision:b?.decision??"ask",revision:b?.revision??0,sessionAllowed:b?.sessionAllowed??!1,sessionSimulated:u.has(E.key)&&b?.sessionAllowed===!0,licensed:y,...y?{sourceStatus:wb(a)}:{}}})}},subscribe(g){return f.add(g),()=>f.delete(g)},setScenario(g){if(s=g,yb.includes(g)){a=g,l();return}if(g==="cancelled"){l();return}if(g==="revoked"){u.clear(),m(E=>E.revokeSession());return}if(g==="reset"||g==="undecided"){u.clear(),m(E=>E.resetAll());return}const I=g;u.clear(),m(async E=>{I==="session"&&await E.resetAll();for(const b of e.declared?.().resources??[])await E.setDecision({resource:b,decision:I==="denied"?"deny":"allow",scope:I==="session"?"session":"persistent"}),I==="session"&&u.add(b)})},revokeSession(){return m(g=>g.revokeSession())},clearSession(){o++,c=void 0,u.clear(),t=void 0,r=void 0,l()},resetAll(){return m(g=>g.resetAll())},dispose(){u.clear(),t=void 0,r=void 0,f.clear()}}}function Ib(e){const t=qe(e.runtimePermissions);let r={};return t.valid&&t.permissions.user_game_data?.status==="enabled"?r=Sn(t.permissions.user_game_data.config.resources):e.runtimePermissions===void 0&&e.declaredPermissions?.user_game_data?.enabled&&(r=Sn(e.declaredPermissions.user_game_data.resources)),{resources:Kh(r),source:"manifest"}}function _b(e){return async t=>{if(t.source!=="runtime-private"||t.target.kind!=="heybox-api"||!t.target.path.startsWith("/user_miniprogram/runtime/user_game_data/"))return;const r=t.data,n=typeof r?.resource=="string"?Oo(r.resource):void 0;if(!n)return{status:400,headers:{},data:{status:"failed",result:{error_code:"USER_GAME_DATA_TARGET_UNSUPPORTED"}}};const i=r?.operation==="list"?"list":"get",o=e();if(["source_invalid","source_link_required","user_login"].includes(o))return{status:400,headers:{},data:{status:"failed",result:{error_code:o==="source_invalid"?"USER_DATA_SOURCE_LOGIN_REQUIRED":"USER_DATA_SOURCE_NOT_LINKED",message:"Mock 来源条件尚未满足"}}};if(o==="failed"||o==="unavailable"||o==="unknown")return{status:503,headers:{},data:{status:"failed",result:{error_code:o==="failed"?"UPSTREAM_FAILED":"REQUEST_UNSUPPORTED",message:"Mock 数据源不可用"}}};const s=t.target.path.split("/").at(-1);if(s==="sync"||s==="sync_status")return{status:200,headers:{},data:{status:"ok",result:{task_id:"mock-task",state:s==="sync"?"syncing":"succeeded"}}};if(s==="file")return{status:400,headers:{},data:{status:"failed",result:{error_code:"FILE_NOT_FOUND",message:"Mock 列表没有可下载文件"}}};const a=n.queries[i];if(!a)return{status:400,headers:{},data:{status:"failed",result:{error_code:"REQUEST_UNSUPPORTED"}}};const c=o==="no_data"||o==="updating"?{status:"empty",reason:o==="no_data"?"no_data":"not_ready",message:"Mock 资料尚未就绪"}:{status:"ready",data:op(a.schema)};return{status:200,headers:{},data:{status:"ok",result:{...c,resource:n.key,operation:i,schema_version:a.version,disclosure_revision:n.disclosureRevision}}}}}const Ab=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"]}),Db="host.userDataTelemetry",qu=80;function bb(e){return{method:Db,detail:{...e.payload,eventName:e.name,message:Mb(e)}}}function Mb(e){const t=Ab[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}: ${ym(i)}`)}return[e.name,...r].join(" · ")}function ym(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=>ym(r)).join(",");else try{t=JSON.stringify(e)??""}catch{t="[无法序列化]"}return t.length>qu?`${t.slice(0,qu)}…`:t}const Sb=44;function Nb(e){const t=()=>e.isCapsuleHidden?.()?0:Sb,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:Jm,showLoading:Km,hideLoading:Zm,vibrate:Wm,openAppPage:nb,openWindow:ib,showShareMenu:ob,captureAndShare:sb,setScreenshotChromeHidden:Ym}}const Qu=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],ei=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Yu={"launch-only":[],stdio:["stdio"],full:["stdio","attachments","notifications"],"prepare-fail":[],"prepare-cancel":[],"launch-cancel":[],"os-blocked":[],"normal-exit":["stdio"],crash:["stdio"],"output-limit":["stdio"]};class Tb{port;presentation;now;schedule;clearSchedule;onDiagnostic;preparations=new Map;sessions=new Map;eventSink;sessionEventListeners=new Set;nextSessionId=0;constructor(t={}){this.now=t.now??Date.now,this.schedule=t.schedule??((r,n)=>setTimeout(r,n)),this.clearSchedule=t.clearSchedule??(r=>clearTimeout(r)),this.onDiagnostic=t.onDiagnostic??(()=>{}),this.port={getInfo:async r=>this.getInfo(r),getPreparationStatus:async r=>this.getPreparationStatus(r),prepare:(r,n)=>this.prepare(r,n),cancelPreparation:async r=>this.cancelPreparation(r),getActiveSession:async r=>this.getActiveSession(r),launch:async r=>this.launch(r),write:async r=>this.write(r),closeStdin:async r=>this.closeStdin(r),terminate:async r=>this.terminate(r),ackOutput:async r=>this.ackOutput(r),openAttachment:async r=>this.openAttachment(r),showNotification:async r=>this.showNotification(r),onSessionEvent:r=>(this.sessionEventListeners.add(r),()=>this.sessionEventListeners.delete(r))},this.presentation={confirmCompanionOperation:async({action:r,companion:n})=>{const i=n.alias===`${r}-cancel`;return this.diagnostic(`authorization.${i?"cancelled":"granted"}`,n.alias,{action:r}),i?{status:"cancelled"}:{status:"granted"}}}}bindEventSink(t){this.eventSink=t,this.diagnostic(t?"runtime.connected":"runtime.disconnected")}reset(t){const r=t?[t]:[...Qu];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(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:Yu[r],archiveBytes:12,signatureStatus:"unsigned"}}getPreparationStatus(t){const r=this.readAlias(t);return this.preparations.get(r)?.status??{state:"not-prepared"}}prepare(t,r){const n=this.readAlias(t),i=this.preparations.get(n);if(i?.status.state==="ready")return Promise.resolve(this.getInfo(n));if(i?.operation)return i.operation.listeners.add(r.onProgress),this.diagnostic("prepare.joined",n),r.onProgress(i.status.state==="preparing"?i.status.progress:ei[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:ei[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),ei.forEach((u,f)=>{const l=this.schedule(()=>{if(c.timers.delete(l),!c.cancelled){d.status={state:"preparing",progress:u};try{c.listeners.forEach(h=>h(u))}catch(h){c.cancelled=!0;for(const m of c.timers)this.clearSchedule(m);d.operation=void 0,d.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",n,{message:h instanceof Error?h.message:String(h)}),c.reject(h);return}if(this.diagnostic("prepare.progress",n,{phase:u.phase}),f===ei.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(Ph,{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:Yu[r],state:"running",controllerGeneration:1},o={snapshot:i,stdinClosed:!1,exited:!1,queuedOutput:[]};return this.sessions.set(r,o),this.diagnostic("session.launched",r,{capabilities:[...i.capabilities],sessionId:i.id}),i.capabilities.includes("stdio")&&this.schedule(()=>{this.queueOutput(o,"stdout",1,`fake:ready
|
|
224
|
+
`),this.queueOutput(o,"stderr",1,`fake:diagnostic
|
|
225
|
+
`)},20),r==="normal-exit"&&this.schedule(()=>this.requestExit(o,{reason:"exited",exitCode:0}),40),r==="crash"&&this.schedule(()=>this.requestExit(o,{reason:"crashed",exitCode:1}),40),r==="output-limit"&&this.schedule(()=>this.requestExit(o,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("stdio"))throw 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
|
|
226
|
+
`);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(Oh,{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(kh,{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(!Qu.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 vb=Object.freeze({[wo]:!0,[Eo]:!0,[Io]:!0,[_o]:!0,[Ao]:!0,[Do]:!0,[bo]:!0,[Mo]:!0,[So]:!0,[No]:!0,[To]:!0,[vo]:!0,[An]:!0,[_n]:!0,[Dn]:!0});function Ob(e){return new Tb(e)}function ze(e,t){return Object.assign(new Error(t),{code:e})}const kb=/^[A-Za-z0-9_-]{22}$/,Pb="https://api.xiaoheihe.cn/open_inapp/";function Rb(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(!kb.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 Cb(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`${Pb}#${r}`}function Lb(e={}){const t=e.source??Hb(e.document??document),r=e.readMetadata??Fb,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(cn(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 Ub(t,d);if(cn(u.signal),d.source==="camera"&&f.length!==1)throw ve("MEDIA_PREPARE_FAILED","相机模拟必须恰好返回 1 项");const l=[];try{for(const h of f)cn(u.signal),l.push(await jb(h,d,u.signal,r,n,o,s));cn(u.signal)}catch(h){for(const m of l)a(o.get(m.file));throw h}return l},release(d){for(const u of d)a(o.get(u.file))}}}async function Ub(e,t){const r=await e.pickAlbum({accept:xb(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 xb(e){switch(e){case"image":return"image/*";case"video":return"video/*";default:return"image/*,video/*"}}async function jb(e,t,r,n,i,o,s){const a=zb(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);cn(r);const d=Wu(c.width),u=Wu(c.height);if(d===void 0||u===void 0)throw ve("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的显示尺寸`);if(a==="video"){if(Zu(c.durationMs)===void 0)throw ve("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的视频时长`)}else if(c.durationMs!==void 0)throw ve("MEDIA_PREPARE_FAILED",`图片 ${e.name} 不应携带视频时长`);const f=i(e);if(!f)throw ve("MEDIA_PREVIEW_UNAVAILABLE","无法提供受控媒体预览");const l=Bb(e);o.set(l,f),s.add(f);const h={type:a,mimeType:e.type,size:e.size,width:d,height:u,previewUrl:f,file:l};return a==="video"?{...h,durationMs:Zu(c.durationMs)}:h}function zb(e){if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video"}function Bb(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 Hb(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"?Qb():qb()}}}async function Fb(e){return e.type.startsWith("video/")?Vb(e):$b(e)}async function $b(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 Vb(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 Gb(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 Gb(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 qb(){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 Qb(){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:Yb(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 Wb(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 Yb(e){for(const t of["video/webm;codecs=vp8","video/webm","video/mp4"])if(e.isTypeSupported?.(t))return t;return"video/webm"}async function Wb(e,t,r){for(;r();){const n=Math.min(1,Date.now()%900/900);e.fillStyle="#101820",e.fillRect(0,0,t.width,t.height),e.fillStyle=`rgb(${Math.round(40+n*180)}, 120, ${Math.round(200-n*120)})`,e.fillRect(0,t.height*(1-n),t.width,8),e.fillStyle="#ffffff",e.font="18px sans-serif",e.fillText("模拟拍摄中",24,t.height/2),await new Promise(i=>setTimeout(i,60))}}function cn(e){if(e.aborted){const t=new Error("Browser Dev Host 媒体选择已取消");throw t.name="AbortError",t}}function ve(e,t){const r=new Error(t);return r.name="BrowserDevMediaError",r.code=e,r}function Wu(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:void 0}function Zu(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function Zb(e){const t=qe(e.runtimePermissions),r=Fa({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=qe(e.publishedRuntimePermissions),o=qe(r.runtimePermissions);for(const s of Ha){const a=s.key,c={network:"Network",companion:"Companion",appProtocol:"AppProtocol"}[a]??s.name;if(!e.declaredPermissions?.[a]?.enabled)continue;const d=t.valid&&t.permissions[a]?.status==="enabled",u=r.temporaryPermissionKeys.some(f=>f===a);n.push({key:a,label:c,state:s.access==="declaration"?"declared":d?"approved":u?"temporary":"unavailable",facts:{platformApproval:s.access==="declaration"?null:d,temporary:u,effective:o.permissions[a]?.status==="enabled",online:i.valid?i.permissions[a]?.status??"missing":"unknown"},...u?{releaseDifference:"本次使用临时授权,发布后仍需平台批准。"}:i.valid&&!i.permissions[a]?{releaseDifference:"线上快照尚未包含该权限,需发布包含声明的新版本。"}:{},...a==="appProtocol"?{highestRisk:!0}:{},...s.access!=="declaration"&&!d&&!u?{reason:a==="appProtocol"?"最高危险权限:可执行任意协议并绕过其他 SDK 能力权限;当前没有有效临时授权,线上未批准":"没有有效的本地临时授权,线上未批准"}:{}})}if(e.declaredPermissions?.network?.useOfficialDomain){const s=t.valid&&t.permissions.network?.status==="enabled"&&t.permissions.network.config.useOfficialDomain===!0;n.push({key:"network.useOfficialDomain",label:"官方域名",state:s?"approved":"unavailable",...s?{}:{reason:"不支持本地临时授权,获得线上批准后才能使用"}})}return n}function Kt(e){return JSON.stringify({source:e.source,miniProgramId:e.miniProgramId,devSessionId:e.devSessionId,contextRevision:e.contextRevision,declaredPermissions:e.declaredPermissions,runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant,companionManifestSha256:e.companionManifestSha256})}const Ku="__hb_sdk_mini_dev_console_installed__",Kb=["log","debug","info","warn","error"];function Jb(e,t=console){if(t[Ku])return;let r=!1;for(const n of Kb){const i=t[n];if(typeof i!="function")continue;const o=function(...s){try{e(n,s)}catch{}return i.apply(this,s)};try{t[n]=o,r=!0}catch{break}}r&&(t[Ku]=!0)}const fa=1,Ju=64*1024,Xb=64,eM=/^[A-Za-z0-9_-]{22}$/;class Ke extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function tM(e,t=!1){const r=nM(e,t);switch(ma(r,"Server message"),iM(r),r.type){case"grant":return fn(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),mn(r.connectionEpoch,"connectionEpoch"),Jt(r.nextClientSequence,"nextClientSequence"),Jt(r.nextServerSequence,"nextServerSequence"),Xu(r.snapshot),r;case"event":return fn(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),mn(r.connectionEpoch,"connectionEpoch"),Jt(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&Ft("event must be account.changed or status.changed"),Xu(r.snapshot),r;case"heartbeat":return fn(r,["version","type","connectionEpoch","sequence"],"heartbeat"),mn(r.connectionEpoch,"connectionEpoch"),Jt(r.sequence,"sequence"),r;default:return Ft("Unknown server message type")}}function rM(e){const t=e.connectionEpoch;mn(t,"connectionEpoch"),Jt(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(mn(n.connectionEpoch,"connectionEpoch"),Jt(n.sequence,"sequence"),n.connectionEpoch!==t)throw new Ke("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new Ke("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new Ke("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function nM(e,t){if(t)throw new Ke("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new Ke("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Ju)throw new Ke("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Ju)throw new Ke("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return oM(e),JSON.parse(e)}catch(r){throw r instanceof Ke?r:new Ke("INVALID_JSON","Channel frame must contain strict JSON")}}function Xu(e){ma(e,"snapshot"),fn(e,["account","permissions"],"snapshot"),ma(e.account,"snapshot.account"),fn(e.account,["revision"],"snapshot.account"),Jt(e.account.revision,"snapshot.account.revision"),WD(e.permissions)||Ft("snapshot.permissions is invalid")}function iM(e){e.version!==fa&&Ft("version must be 1")}function ma(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Ft(`${t} must be a plain JSON object`)}function fn(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)))&&Ft(`${r} fields are invalid`)}function Jt(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Ft(`${t} must be a non-negative safe integer`)}function mn(e,t){(typeof e!="string"||!eM.test(e))&&Ft(`${t} must be a 22-character base64url value`)}function Ft(e){throw new Ke("INVALID_MESSAGE",e)}function oM(e){new sM(e).scan()}class sM{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>=Xb)throw new Ke("INVALID_JSON","Channel JSON exceeds maximum nesting depth");return r==="{"?this.scanObject(t):this.scanArray(t)}if(r==='"'){this.scanString();return}this.scanPrimitive()}scanObject(t){this.position+=1,this.skipWhitespace();const r=new Set;if(!this.consume("}"))for(;;){if(this.source[this.position]!=='"')throw new SyntaxError("JSON object key must be a string");const n=this.scanString(),i=JSON.parse(n);if(typeof i!="string")throw new SyntaxError("JSON object key must be a string");if(r.has(i))throw new Ke("INVALID_JSON","Channel JSON contains a duplicate key");if(r.add(i),this.skipWhitespace(),!this.consume(":"))throw new SyntaxError("Missing JSON object colon");if(this.skipWhitespace(),this.scanValue(t+1),this.skipWhitespace(),this.consume("}"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON object comma");this.skipWhitespace()}}scanArray(t){if(this.position+=1,this.skipWhitespace(),!this.consume("]"))for(;;){if(this.scanValue(t+1),this.skipWhitespace(),this.consume("]"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON array comma");this.skipWhitespace()}}scanString(){const t=this.position;for(this.position+=1;this.position<this.source.length;){const r=this.source[this.position];if(r==='"')return this.position+=1,this.source.slice(t,this.position);r==="\\"?this.position+=2:this.position+=1}throw new SyntaxError("Unterminated JSON string")}scanPrimitive(){const t=this.position;for(;this.position<this.source.length&&!/[\s,\]}]/.test(this.source[this.position]??"");)this.position+=1;if(t===this.position)throw new SyntaxError("Missing JSON value")}skipWhitespace(){for(;/[\t\n\r ]/.test(this.source[this.position]??"");)this.position+=1}consume(t){return this.source[this.position]!==t?!1:(this.position+=1,!0)}}const el=[1e3,2e3,4e3,8e3,15e3];function aM(e){const t=new Set,r=e.webSocketFactory??(N=>new WebSocket(N)),n=e.randomValues??(N=>crypto.getRandomValues(N)),i=e.timers??{clearTimeout:N=>window.clearTimeout(N),setTimeout:(N,x)=>window.setTimeout(N,x)},o=e.onlineTarget??(typeof window>"u"?void 0:window),s=e.visibilityTarget??(typeof document>"u"?void 0:document),a=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let c,d,u,f=!1,l=0,h,m=!1,g=!1;const I=new Set,E=(N,x)=>{if(!(!e.onDiagnostic||I.has(N))){I.add(N);try{e.onDiagnostic({phase:N,...x?{code:x}:{}})}catch{}}},b=(N,x,M=!1)=>{if(u&&N.account.revision<u.account.revision)return;const S=u&&JSON.stringify(N)===JSON.stringify(u);if(u=N,!(S&&!M))for(const O of t)O(N,x)},y=()=>{if(f||h!==void 0||c)return;const N=el[Math.min(l,el.length-1)];l+=1,h=i.setTimeout(()=>{h=void 0,T()},N)},v=()=>{f||!m||c||(h!==void 0&&(i.clearTimeout(h),h=void 0),T())},j=()=>{a()&&v()},A=()=>{s&&!s.hidden&&v()},D=()=>{g||(g=!0,o?.addEventListener("online",j),s?.addEventListener("visibilitychange",A))},_=()=>{g&&(g=!1,o?.removeEventListener("online",j),s?.removeEventListener("visibilitychange",A))},T=()=>{if(f||c)return;m=!0,D(),h!==void 0&&(i.clearTimeout(h),h=void 0);let N,x;try{N=r(e.url)}catch{E("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),y();return}try{x=dM(n)}catch{E("entropy","NONCE_GENERATION_FAILED");try{N?.close(1011,"channel initialization failed")}catch{}y();return}c=N;let M,S,O;const z=()=>{N.removeEventListener("open",L),N.removeEventListener("message",C),N.removeEventListener("close",H),N.removeEventListener("error",F),d===z&&(d=void 0)},U=()=>{if(c===N){c=void 0,z();try{N.close(1008,"invalid channel state")}catch{}y()}},L=()=>{if(!(f||c!==N))try{N.send(JSON.stringify({version:fa,type:"hello",csrfToken:e.csrfToken,clientNonce:x}))}catch{E("send","HELLO_SEND_FAILED"),U()}},C=G=>{if(f||c!==N)return;if(typeof G.data!="string"){E("parse","TEXT_FRAME_REQUIRED"),U();return}let K;try{K=tM(G.data)}catch(p){E("parse",p instanceof Ke?p.code:"INVALID_MESSAGE"),U();return}if(K.type==="grant"){if(O){E("sequence","DUPLICATE_GRANT"),U();return}M=K.connectionEpoch,S=K.nextClientSequence,O=rM({connectionEpoch:M,nextSequence:K.nextServerSequence}),l=0,I.clear(),b(K.snapshot,{type:"grant"});return}if(!O||!M||S===void 0){E("sequence","MESSAGE_BEFORE_GRANT"),U();return}try{O.accept(K)}catch{E("sequence","INVALID_SEQUENCE"),U();return}if(K.type==="heartbeat"){try{N.send(JSON.stringify({version:fa,type:"heartbeat.ack",connectionEpoch:M,sequence:S}))}catch{E("send","HEARTBEAT_ACK_SEND_FAILED"),U()}S=S===Number.MAX_SAFE_INTEGER?void 0:S+1;return}b(K.snapshot,{type:"event",event:K.event},!0)},H=()=>{c===N&&(E("close","SOCKET_CLOSED"),c=void 0,z(),y())},F=()=>{E("open","SOCKET_ERROR"),U()};N.addEventListener("open",L),N.addEventListener("message",C),N.addEventListener("close",H),N.addEventListener("error",F),d=z};return{connect:T,subscribeUpdates(N){return t.add(N),()=>t.delete(N)},dispose(){if(f)return;f=!0,m=!1,_(),h!==void 0&&i.clearTimeout(h),h=void 0;const N=c;c=void 0,d?.(),N?.close(1e3,"client disposed"),t.clear()}}}function cM(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 dM(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=cM(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let _e=!1,wm=!1,He;const Em=new AbortController;try{Jb((e,t)=>{Xt(`console.${e}`,{source:"host",message:t.map(r=>SM(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const uM="/__hb_sdk_bootstrap__",lM="/__hb_sdk__/mobile-launch-redirect",fM="/__hb_sdk__/network",mM="/session/status",hM="/session/request",gM="/session/events",tl=320,pM=1e3,yM=1e3,wM=15e3,rl="dark",EM=["windows","macos","linux","unknown"],Im=new URL(location.href).searchParams,_m=Im.get("mini_url"),Fe=Im.get("ui_preview")==="1",Ne={get device(){return ri("#device")},get mobileLanSelect(){return ri("#mobile-lan-select")},get mobileQrImage(){return ri("#mobile-qr-image")},get mobileQrStatus(){return ri("#mobile-qr-status")}};if(!_m&&!Fe)throw Ne.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Am=_m??"about:blank",De=await hc(),dc=Fe?void 0:await ct.configure({csrfToken:De.csrfToken??"",diagnosticsToken:De.diagnosticsToken??"",signal:Em.signal,query:KM,onDropped:e=>{q.diagnosticsDropped=e},onOwnershipLost:vm});q.diagnosticTargetId=dc?.targetId??"";q.diagnosticOwnerId=dc?.ownerId??"";q.diagnosticTargetName=dc?.metadata.displayName??"";q.openPlatformBaseUrl=De.openPlatformBaseUrl;q.devReadiness=De.devReadiness;q.miniProgramSupportsDesktop=De.miniProgramSupportsDesktop;q.miniProgramPlatforms=De.devContext.platforms??[];q.desktopLaunch.workspaceCardsEnabled=De.workspaceCardsEnabled;al(De.hostPlatform);cl(De.windowForm);let Pt=De.lanAddresses,li=De.defaultLanAddressId,Dr=De.mobileLaunchRedirect,uc=De.nativeAppLaunchUnavailableReason,hn=De.devSessionId,ha=De.miniProgramManifestAccessToken,fi=De.workspaceCardsEnabled,mi=De,lc=$o(De),Je=De.devContext,Nr=De.browserDevContext,Ue=ln(Nr);yo();let xr=Bo(Ue),Fo=0;const ar=new AbortController;let fc=0,At,ga=0,pa,St=0,Tt=!1,hi,ya,js=!1;const jr=mh({apply:hh,waitForLayout:async e=>{await Ei(),await fl(e),await ml(e)}});let mc=!1;function zs(e){if(e.throwIfAborted(),_e)throw new Wt("SESSION_CLOSED","调试台已关闭");if(q.diagnosticOwnershipLost)throw new Wt("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!mc)throw new Wt("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(Sr)throw new Wt("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const wa=lh({observe:()=>{const e=kn()?{width:wi.value.width,height:wi.value.height}:{width:Qs.value.screenWidth,height:Qs.value.screenHeight};return{preset:q.deviceSelectionId,orientation:kn()?e.width>=e.height?"landscape":"portrait":q.display.orientation,runtimeStatus:q.runtimeStatus,viewport:e,instanceId:He?.mounted?He.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:ph()}},async selectPreset(e,t){zs(t),q.deviceSelectOpen=!1;const r=q.previewMode,n=He;gh(e),await Ei(),t.throwIfAborted(),q.previewMode!==r&&await nl(n,t)},async applyOrientation(e,t){zs(t),q.deviceSelectOpen=!1,await jr.applyDisplay({mode:e,hideCapsule:q.display.capsuleHidden},t)},async reload(e){zs(e),q.deviceSelectOpen=!1;const t=He;Ht("runtime.restart",{boundary:fc+1}),ur("manual restart").catch(()=>{}),await nl(t,e)},async waitForLayout(e){await Ei(),e.throwIfAborted(),await fl(e),await ml(e)}}),gi=Ah(),Dm={...wa.bridge,prepareCapture:gi.prepare,restoreCapture:gi.restore,cancel(e){wa.bridge.cancel(e),gi.cancel(e)}};window.__HB_SDK_PREVIEW__=Dm;async function nl(e,t){for(;;){if(t.throwIfAborted(),_e)throw new Wt("SESSION_CLOSED","调试台已关闭");if(He!==e&&At===void 0){const r=q.runtimeStatus;if(r==="ready"||Fe&&r==="idle")return;if(r==="error")throw new Wt("RUNTIME_START_FAILED","小程序 Runtime 启动失败,请查看调试日志");if(r==="closed")throw new Wt("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 Ea,Ia,_a,Aa,Da,ba,il=Date.now(),Sr=!1,ol=Promise.resolve(),Tr=-1,On=!1,vt,Ma,Sa,pi,Yt;const go=new Set,sl="hb-sdk:browser-dev-host:user-data-device";function IM(){try{const e=localStorage.getItem(sl)?.trim();if(e)return e;const t=typeof crypto.randomUUID=="function"?crypto.randomUUID():`mock-${Date.now().toString(36)}`;return localStorage.setItem(sl,t),t}catch{return"browser-mock-device"}}const _M=IM();function AM(){return{miniProgramId:Je.miniProgramId?.trim().toLowerCase()||"anonymous-mini-program",userId:vt?.trim()||"anonymous-user",deviceId:_M,environment:"development"}}function bm(){return hm(Ue.runtimePermissions,xr,Ue)}function DM(){const e=qe(bm());return e.valid&&e.permissions.network?.status==="enabled"?"upload":"no_network"}function bM(){return Ib({declaredPermissions:Ue.declaredPermissions,runtimePermissions:bm()})}const ut=Eb({resolveScope:AM,egressTier:DM,declared:bM});function zr(){wm&&fh({...ut.snapshot(),targetId:q.diagnosticTargetId,instanceId:He?.instanceId})}ut.subscribe(zr);wm=!0;zr();function Bs(){const e=ut.snapshot().stateError;if(e)throw new Error(e)}Xm({async refresh(){await ut.refresh(),Bs()},async revokeSession(){await ut.revokeSession(),Bs()},async resetAll(){await ut.resetAll(),Bs()}});const Na=Ob({onDiagnostic:({action:e,alias:t,detail:r})=>Ht(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Br=eb({applyStatus:e=>Cm(e,!0),fetchStatus:e=>Rm(Fm(ar.signal,e)),getCanonicalRevision:()=>Tr,onError:XM,reconcile:()=>LM(Fo)}),Ta=tb({connectEvents:Lm,invalidate:()=>Br.invalidate(),isDisposed:()=>_e,maxDelayMs:wM,minDelayMs:yM,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let Hs=0,ti="",Fs=!1,va,Oa;function Mm(){Fe||_e||q.diagnosticOwnershipLost||ct.poll().finally(()=>{!_e&&!q.diagnosticOwnershipLost&&(Oa=window.setTimeout(Mm,1e3))})}Mm();await po(!1);jm();Bm(zm(De));Fe&&TM();Pn();Fe||await Nm();MM();Sm();BM();await ur("initial");Fe||(Lm(),RM());mc=!0;function Sm(){!Fe&&!_e&&(va=window.setTimeout(()=>{Nm().finally(Sm)},1e3))}async function Nm(){if(!(Fs||_e)){Fs=!0;try{const e=await fetch(`${Ec}?after=${Hs}&limit=500`,{headers:{"x-hb-sdk-csrf":De.csrfToken??""},signal:AbortSignal.any([ar.signal,AbortSignal.timeout(5e3)])});if(!e.ok){q.diagnosticsStale=!0;return}const t=await e.json();if(_e)return;if(ti&&t.epoch!==ti){Hs=0,ti=t.epoch,eh();return}ti=t.epoch,q.uploadSessions=t.uploadSessions;const r=await fetch(`${Ec}?mode=inspect`,{headers:{"x-hb-sdk-csrf":De.csrfToken??""},signal:AbortSignal.any([ar.signal,AbortSignal.timeout(5e3)])});if(r.ok){const o=await r.json();q.diagnosticInstances=o.instances,q.diagnosticTargets=o.targets,q.diagnosticPrimaryTargetId=o.primaryTargetId;const s=o.targets.find(a=>a.targetId===q.diagnosticTargetId);s&&(q.diagnosticTargetName=s.metadata.displayName),s&&(s.state==="closed"||s.ownerId!==q.diagnosticOwnerId)&&vm()}q.diagnosticsStale=!r.ok,q.diagnosticsGap=q.diagnosticsGap||t.gap===!0;const n=new Map(q.diagnosticTargets.map(o=>[o.targetId,o.metadata.displayName])),i=new Map(q.diagnosticInstances.map(o=>[o.instanceId,n.get(o.targetId)]));for(const o of t.items){const s=th(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,rh(s,o.cursor))}Hs=t.nextCursor}catch{q.diagnosticsStale=!0}finally{Fs=!1}}}function MM(){window.addEventListener("beforeunload",eS),window.addEventListener("hb-sdk:refresh-storage",Pn),window.addEventListener("hb-sdk:qr-open-change",Tm),Ea=nh(()=>document.querySelector("#host-fullscreen-exit-mount")),Ia=Qr(()=>[gn.value,Vs.value,ni.value?.state,ni.value?.stale,ni.value?.capabilities.storage].join("|"),()=>{q.storage=[],q.storageError="",Pn()}),_a=Qr(()=>q.devicePresetId,()=>jr.notifyViewportChange(),{flush:"post"}),Aa=Qr(()=>q.previewMode,()=>{Ot("preview mode changed"),dl(!1),ih(!1),Hr("preview mode changed")},{flush:"sync"}),Da=Qr(()=>wi.value,()=>jr.notifyViewportChange(),{flush:"post"}),ba=Qr(()=>q.desktopWindow.closed,(e,t)=>{if(kn()){if(e){Ot("desktop window closed"),q.runtimeStatus="closed";return}t&&q.runtimeStatus==="closed"&&Hr("desktop window reopened")}},{flush:"sync"})}function SM(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
|
|
227
|
+
`).slice(0,4).join(`
|
|
228
|
+
`):"")||`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}return String(e)}function Tm(e){const t=e.detail?.open===!0;t!==Tt&&(Tt=t,St+=1,Vo(),t&&(Ne.mobileLanSelect.addEventListener("change",NM),Um(),zn()))}function NM(){Tt&&zn()}function Hr(e){_e||At!==void 0||(Ht("runtime.restart",{boundary:fc+1}),At=window.setTimeout(()=>{At=void 0,_e||ur(e)},0))}async function ur(e,t=Am,r){if(_e||Sr||q.diagnosticOwnershipLost)return;if(At!==void 0&&window.clearTimeout(At),At=void 0,Ot(e),kn()&&q.desktopWindow.closed){q.runtimeStatus="closed";return}const n=document.createElement("iframe");n.dataset.testid="device-iframe",n.title="小程序预览",n.allow="clipboard-read; clipboard-write",n.name="__hb_sdk_mini_dev__";const i=crypto.randomUUID(),o=oh(i,c=>{Fe||ct.event(i,c)}),s={instanceId:i,launchUrl:t,locationBasePath:r,interactions:o,sequence:++fc,state:"starting",iframe:n,terminal:new AbortController,permissions:Gm(xr),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(s.iframe.dataset.hbSdkInstanceId=s.instanceId,He=s,q.runtimeStatus="loading",km(),Fe||ct.send({operation:"register",instanceId:s.instanceId}),await Ei(),!Be(s))return;const a=qm("#device");if(!a){$s(s,new Error("预览容器尚未挂载"));return}if(Fe){a.innerHTML='<div class="browser-mock-preview"><span class="browser-mock-preview__icon">UI</span><strong>Browser Mock</strong><small>mp_preview</small></div>',q.runtimeStatus="idle";return}a.replaceChildren(s.iframe),s.mounted=!0,ct.send({operation:"activate",instanceId:s.instanceId});try{const c=await ED(vM(s));if(!Be(s)){c.dispose();return}s.assembly=c,c.ports.companion=Na.port,c.ports.media=Lb({getMode:()=>q.mediaSimulation,signal:s.terminal.signal});const d=qD({signal:s.terminal.signal,csrfToken:()=>De.csrfToken??""}),u=tD({iframe:s.iframe,authorizationContext:QD({signal:s.terminal.signal,refreshAccount:f=>po(!0,f),request:Pm,readState:()=>({signed:Je,browser:Ue,userId:vt,accountRevision:Tr,networkEnabled:s.permissions.networkRequest.status==="enabled"})}),ports:{...c.ports,...d},environment:c.environment,hostCapabilities:{...c.hostCapabilities,"media.pick":!0,...d?{"gameSaves.getFile":!0,"user.data.file":!0,"file.readBytes":!0,"file.readText":!0,"file.stat":!0,"file.exists":!0}:{},...vb},authPresentation:c.authPresentation,userDataPresentation:c.userDataPresentation,companionPresentation:Na.presentation,resolveLaunchConfiguration:async()=>(await c.resolveLaunch()).configuration,dispose:()=>ka(s),onDevDocumentReload:(f,l)=>{Be(s)&&ur("development document reloaded",f,l)},onDevUploadSession:f=>{Be(s)&&(s.uploadSessionId=f,Fr(s,{uploadSessionId:f}))},onReady:()=>{Be(s)&&(s.state="ready",s.hadReady=!0,Ra.value=d?u.diagnostics.gameSaves:void 0,q.runtimeStatus="ready",Fr(s),Xt("runtime.ready",{generation:s.sequence},Date.now(),void 0,s.instanceId))},onUserDataTelemetry:f=>{ut.refresh();const l=bb(f);Xt(l.method,l.detail,Date.now(),"info",s.instanceId)},onTrace:f=>PM(s,f),onError:f=>{Be(s)&&$s(s,f)},onCapabilityTrace:f=>{Xt(f.method,{...f,source:"host"},f.timestamp,void 0,s.instanceId),Be(s)&&f.method==="storage.setStorage"&&f.outcome==="success"&&Pn()}});s.runtime=u,await u.start(),Be(s)&&ut.bind(u.getDataPermissionBridge())}catch(c){if(!Be(s))return;$s(s,c),Xt("runtime.start.failed",Hm(c,s),Date.now(),"error",s.instanceId),s.terminal.abort(c),s.runtime?.destroy(),s.iframe.remove(),ka(s)}}function vm(){_e||q.diagnosticOwnershipLost||(q.diagnosticOwnershipLost=!0,Ot("预览页面授权已失效"),q.runtimeStatus="closed",mc=!1)}function Be(e){return He===e&&!_e&&!e.terminal.signal.aborted&&e.state!=="closed"&&e.state!=="failed"}function Fr(e,t={}){ct.send({operation:"update",instanceId:e.instanceId,state:e.state,...t})}function Om(e,t){e.mounted&&(e.mounted=!1,ct.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function ka(e){He===e&&(Ra.value=void 0),e.interactions.dispose();const t=e.assembly;e.assembly=void 0,t?.dispose()}function $s(e,t){e.state==="failed"||e.state==="closed"||(e.state="failed",e.interactions.dispose(),Fr(e,{error:Hm(t,e),...e.uploadSessionId?{uploadSessionId:e.uploadSessionId}:{}}),Om(e,"Runtime failed"),He===e&&(q.runtimeStatus="error"))}function Ot(e){const t=He;t&&(He=void 0,Ra.value=void 0,ut.clearSession(),t.state!=="failed"&&(t.state="closed",Fr(t,{reason:e})),Om(t,e),(!gn.value||gn.value===q.diagnosticTargetId)&&(ga+=1,pa?.abort()),sh(),Na.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),ka(t),jr.reset())}function TM(){const e=wh();q.diagnosticTargetId=e.targetId,q.diagnosticOwnerId=e.ownerId,q.diagnosticPrimaryTargetId=e.targetId,q.diagnosticTargetName=e.metadata.displayName,q.diagnosticTargets=[e],q.diagnosticInstances=[{instanceId:e.currentInstanceId,targetId:e.targetId,ownerId:e.ownerId,adapterId:e.adapterId,kind:"browser",capabilities:e.capabilities,state:"ready",startedAt:Date.now(),updatedAt:Date.now(),startCursor:0,lastCursor:0,stale:!1}];const t={...e,targetId:"ui-preview-phone",ownerId:"ui-preview-phone-owner",kind:"mobile",currentInstanceId:"ui-preview-phone-instance",metadata:{displayName:"小黑盒",deviceModel:"iPhone 16 Pro",os:"iOS"}};q.diagnosticTargets.push(t),q.diagnosticInstances.push({...q.diagnosticInstances[0],instanceId:t.currentInstanceId,targetId:t.targetId,ownerId:t.ownerId,kind:"mobile"}),Gs({...qs("console.error",{source:"app",message:"真机示例:请求超时"},Date.now(),"error"),targetId:t.targetId,instanceId:t.currentInstanceId}),Ht("runtime.ready",{generation:1}),Gs(qs("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info")),Ht("user.getInfo",{durationMs:34,outcome:"success"}),Ht("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function vM(e){const t=e.terminal.signal,r=Ue,n=hn,i=hm(r.runtimePermissions,e.permissions,r),o=kn();return{signal:t,account:{async getCurrentUserId(){return(await po(!1,t)).user_id},async ensureAuthenticated({signal:s}){await po(!1,s)},onChange(s){return go.add(s),()=>go.delete(s)}},authenticatedRequest:Pm,storage:{area:"local",storage:localStorage},presentation:Nb({close:async()=>{Be(e)&&(Ot("mini program closed"),km(),q.runtimeStatus="closed",o&&dl(!0))},reload:()=>{Be(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:s=>{Be(e)&&ul(s)},...o?{getViewportMetrics:()=>{const s=wi.value;return{windowWidth:s.width,windowHeight:s.height,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio,safeArea:{left:0,right:s.width,top:0,bottom:s.height}}},getNavigationBarHeight:()=>yh}:{getDeviceMetrics:()=>Qs.value,applyDisplay:(s,a)=>jr.applyDisplay(s,a),isCapsuleHidden:()=>q.display.capsuleHidden},onViewportChange:s=>jr.onViewportChange(s)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:s=>{document.title=s}},resolveLaunch:async()=>({configuration:ub({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,...q.miniProgram.bound&&q.miniProgram.name.trim()?{miniProgramName:q.miniProgram.name}:{},...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:o?q.hostPlatform:ah.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:s=>db(s),confirmFollowAuthor:s=>rb(s)},userDataPresentation:{confirmDataPermission:hb},protocol:OM(e)}}function kn(){return q.previewMode==="desktop"}function OM(e){return{async invoke(t){Xt("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:kM(t)},Date.now(),void 0,e.instanceId)}}}function kM(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 km(){document.documentElement.dataset.navigationBarStyle=rl,ul(rl)}function PM(e,t){Be(e)&&t.type==="document_validation"&&typeof t.documentVerifying=="boolean"&&Fr(e,{documentVerifying:t.documentVerifying}),_e||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(ch({...t,generation:e.sequence})),...t.errorCode?{errorCode:t.errorCode}:{}}),e.runtimeId!==t.runtimeId&&(e.runtimeId=t.runtimeId,Fr(e,{runtimeId:t.runtimeId})),Be(e)&&e.pendingNavigationReload&&t.type==="bridge_response"&&t.method==="navigation.reload"&&t.outcome==="success"&&(e.pendingNavigationReload=!1,Hr("navigation.reload"))}async function Pm(e,t){const r=await _b(()=>ut.snapshot().dataScenario)(e);if(r)return r;if(e.redirectPolicy!=="error")throw new Error("Browser Dev Host network 只允许 no-follow redirect policy");const i=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(!i&&e.source!=="runtime-private")throw new Error("Browser Dev Host 的公开请求只支持 absolute URL");const o=await gc(i?fM:hM,{method:"POST",body:JSON.stringify(i??{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});!i&&o.status===401&&Br.invalidate();const s=await o.json();if(!o.ok)throw s;return s}async function po(e,t){const r=Fo,n=await Rm(Fm(ar.signal,t));return $m(r)?Cm(n,e).status:Pa()}async function Rm(e){return await(await fetch(mM,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Cm(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Tr)return{changed:!1,status:Pa()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?ke(e.nickname):void 0,i=e.authenticated?ke(e.avatar):void 0,o=e.revision!==Tr||e.authenticated!==On||r!==vt||n!==Ma||i!==Sa;return Tr=e.revision,On=e.authenticated,vt=r,Ma=n,Sa=i,jm(),zr(),t&&o&&go.forEach(s=>s(vt)),{changed:o,status:Pa()}}function Pa(){return{authenticated:On,revision:Tr,...On&&vt?{user_id:vt}:{}}}function RM(){if(!(!De.csrfToken||_e))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Yt=aM({csrfToken:De.csrfToken,onDiagnostic:t=>Ht("channel.diagnostic",t),url:e.toString()}),Yt.subscribeUpdates((t,r)=>CM(t,r)),Yt.connect()}catch{Yt?.dispose(),Yt=void 0}}function CM(e,t){Br.invalidate(e.account.revision),nS(xr,e.permissions)?t.type==="event"&&t.event==="status.changed"&&ur("status changed"):(xr=Gm(e.permissions),UM())}function Lm(){if(pi?.close(),pi=void 0,!vt||_e)return;const e=new EventSource(gM);pi=e,e.addEventListener("account-invalidated",()=>{Br.invalidate()}),e.addEventListener("account-revision",()=>{Br.invalidate()}),e.onopen=()=>{Ta.reset()},e.onerror=()=>{e.close(),Ta.schedule()}}async function LM(e){$m(e)&&await ur("account revision changed")}async function UM(){_e||(await ur("permission changed"),!_e&&await zn())}async function hc(){const e=await fetch(uM,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error("Browser Dev Host bootstrap request failed");const t=await e.json();if(!We(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Vm(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new $r;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:zM(t.devReadiness),csrfToken:typeof t.csrfToken=="string"?t.csrfToken:void 0,diagnosticsToken:typeof t.diagnosticsToken=="string"?t.diagnosticsToken:void 0,defaultLanAddressId:typeof t.defaultLanAddressId=="string"?t.defaultLanAddressId:void 0,devSessionId:typeof t.devSessionId=="string"&&/^[a-f0-9]{32}$/.test(t.devSessionId)?t.devSessionId:void 0,devContext:Fu(t.devContext,t.runtimePermissions),browserDevContext:Fu(t.browserDevContext??t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(rS):[],loginAvailable:t.loginAvailable===!0,miniProgram:WM(t.miniProgram),miniProgramSupportsDesktop:t.miniProgramSupportsDesktop===!0,workspaceCardsEnabled:t.workspaceCardsEnabled===!0,mobileLaunchRedirect:r,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof t.miniProgramManifestAccessToken=="string"?t.miniProgramManifestAccessToken:void 0,windowForm:jM(t.windowForm),hostPlatform:xM(t.hostPlatform)}}function xM(e){return EM.includes(e)?e:"unknown"}function jM(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 zM(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 gc(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 BM(){pc(),Fe||(ya=window.setInterval(()=>{YM()},pM))}function Um(e=Ne.mobileLanSelect.options.length>0?Ne.mobileLanSelect.value:void 0){Ne.mobileLanSelect.replaceChildren();for(const t of Pt){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,Ne.mobileLanSelect.appendChild(r)}e&&Pt.some(({id:t})=>t===e)?Ne.mobileLanSelect.value=e:li&&Pt.some(({id:t})=>t===li)?Ne.mobileLanSelect.value=li:Pt[0]&&(Ne.mobileLanSelect.value=Pt[0].id),Ne.mobileLanSelect.disabled=Pt.length===0}async function zn(){if(_e)return;const e=++St;if(Vo(),Fe){const r=await Bu.toDataURL("hb-sdk-ui-preview",{width:tl,margin:1});if(e!==St||_e||!Tt)return;Ne.mobileQrImage.src=r,Ne.mobileQrStatus.textContent="UI 预览示例,不用于真机连接";return}if(Je.source!=="remote"||!Je.localDevLaunchToken||Je.expiresAt!==void 0&&Je.expiresAt<=Date.now()){Ne.mobileQrImage.removeAttribute("src"),Ne.mobileQrStatus.textContent=uc||"需要有效的本地调试启动票";return}const t=tS();if(!t?.mobileAppQrPayload){Ne.mobileQrImage.removeAttribute("src"),Ne.mobileQrStatus.textContent="未发现可用的局域网地址";return}Ne.mobileQrStatus.textContent="正在生成二维码...";try{const r=await GM(t);if(e!==St||_e)return;const n=await HM(r.address,r.expiresAt);if(e!==St||_e)return;const i=await Bu.toDataURL(n.payload,{width:tl,margin:1});if(e!==St||_e)return;Ne.mobileQrImage.src=i,Ne.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,QM(n.expiresAt,e)}catch(r){if(e!==St||_e)return;if(r instanceof $r){yi();return}Ne.mobileQrImage.removeAttribute("src"),Ne.mobileQrStatus.textContent=yc(r)}}async function HM(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await FM(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:Cb(Rb({host:e.address,port:location.port,token:n.token}))}}catch{throw new $r}}async function FM(e,t){if(Dr?.addressId===e.id)return Dr;if(!Dr)return;const r=await gc(lM,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:Dr.token})});if(!r.ok)throw new $r;const n=await r.json(),i=We(n)?Vm({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new $r;return Dr=i,mi={...mi,mobileLaunchRedirect:i},lc=$o(mi),i}async function $M(e){const t=await hc(),r=VM(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return xm(t),{...r,mobileAppQrPayload:n}}function VM(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function xm(e){const t=Kt(Ue);q.devReadiness=e.devReadiness,q.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,q.miniProgramPlatforms=e.devContext.platforms??[],al(e.hostPlatform),cl(e.windowForm),fi=e.workspaceCardsEnabled,mi=e,lc=$o(e),Je=e.devContext,Nr=e.browserDevContext,Ue=ln(Nr),xr=Bo(Ue),yo(),Pt=e.lanAddresses,li=e.defaultLanAddressId,Dr=e.mobileLaunchRedirect,uc=e.nativeAppLaunchUnavailableReason,hn=e.devSessionId,ha=e.miniProgramManifestAccessToken,Bm(zm(e)),Tt&&Um(),pc(),t!==Kt(Ue)&&(Ot("local permission context changed"),Hr("local permission context changed"))}function yo(){if(Fe){q.localPermissions=Eh(),q.devContextWarning="";return}q.localPermissions=Zb(Ue),q.devContextWarning=Ue.source==="anonymous"?"未连接线上上下文":Ue.warning?"本地上下文受限,请检查 CLI 状态":"",zr()}function pc(){let e;try{e=dh(Am)}catch{}const t=Je.miniProgramId?.trim().toLowerCase();let r=uc?.trim()??"";!r&&(Je.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!Je.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&fi&&!hn&&(r="本地调试会话尚未就绪"),!r&&Je.expiresAt!==void 0&&Je.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),ll({...e?{address:e}:{},...t?{miniProgramId:t}:{},...fi&&hn?{devSessionId:hn}:{},...ha?{miniProgramManifestToken:ha}:{},workspaceCardsEnabled:fi,ready:r==="",...r?{unavailableReason:r}:{}})}class $r extends Error{}async function GM(e){const t=ol.then(()=>qM(e));return ol=t.then(()=>{},()=>{}),t}async function qM(e){const t=new URL(e.appUrl),r=new URL(YD,location.origin),n=await gc(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:KD(Je)})}),i=await n.json();if(!n.ok||!We(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await $M(e.id),expiresAt:i.expires_at}}function QM(e,t){hi=window.setTimeout(()=>{!_e&&Tt&&t===St&&zn()},Math.max(1e3,e-Date.now()-3e4))}async function YM(){if(!(js||_e)){js=!0;try{const e=await hc();il=Date.now();const t=Sr;Sr=!1;const r=$o(e);if(!t&&r===lc&&Kt(ln(e.browserDevContext))===Kt(Ue)){Nr=e.browserDevContext,Ue=ln(Nr),yo();return}xm(e),t&&Hr("CLI dev session reconnected"),Tt&&zn()}catch(e){e instanceof $r&&yi();const t=ln(Nr);Kt(t)!==Kt(Ue)&&(Ue=t,xr=Bo(Ue),yo(),Ot("local permission context expired"),Hr("local permission context expired"),pc(),Tt&&yi()),Date.now()-il>=3e4&&!Sr&&(Sr=!0,Ot("CLI dev session disconnected"),qm("#device")?.replaceChildren(),q.runtimeStatus="closed",q.localPermissions=[],q.devContextWarning="调试会话已断开",ll({ready:!1,unavailableReason:"调试会话已断开"}),q.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},Tt&&yi())}finally{js=!1}}}function yi(){St+=1,Vo(),Ne.mobileQrImage.removeAttribute("src"),Ne.mobileQrStatus.textContent="Mobile 短链接配置无效"}function $o(e){return JSON.stringify({devReadiness:e.devReadiness,devSessionId:e.devSessionId,defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,devContext:{platforms:e.devContext.platforms,permissionContext:Kt(e.devContext),expiresAt:e.devContext.expiresAt,localDevLaunchToken:e.devContext.localDevLaunchToken,miniProgramId:e.devContext.miniProgramId,source:e.devContext.source},nativeAppLaunchUnavailableReason:e.nativeAppLaunchUnavailableReason,miniProgramManifestAccessToken:e.miniProgramManifestAccessToken,miniProgramSupportsDesktop:e.miniProgramSupportsDesktop,workspaceCardsEnabled:e.workspaceCardsEnabled,hostPlatform:e.hostPlatform,windowForm:e.windowForm})}function jm(){if(!On){q.account={authenticated:!1,avatar:"",nickname:"未登录"};return}q.account={authenticated:!0,avatar:Sa??"",nickname:Ma||vt||"已登录"}}function zm(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Bm(e){if(!!!e?.miniProgramId||!e){q.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试",description:"",version:""},zr();return}q.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · "),description:e.description??"",version:e.version??""},zr()}function WM(e){if(e===null)return null;if(!We(e))return;const t=ke(e.miniProgramId)??ke(e.mini_program_id);if(t)return{miniProgramId:t,...ke(e.description)?{description:ke(e.description)}:{},...ke(e.name)?{name:ke(e.name)}:{},...ke(e.iconUrl)??ke(e.icon_url)?{iconUrl:ke(e.iconUrl)??ke(e.icon_url)}:{},...ke(e.status)?{status:ke(e.status)}:{},...ke(e.version)?{version:ke(e.version)}:{},...ke(e.developerName)??ke(e.developer_name)?{developerName:ke(e.developerName)??ke(e.developer_name)}:{}}}function ke(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function Pn(){const e=++ga;pa?.abort();const t=new AbortController;pa=t;const r=gn.value,n=!r||r===q.diagnosticTargetId,i=ni.value,o=Vs.value||(n?He?.instanceId:void 0),s=()=>!_e&&e===ga&&r===gn.value&&o===(Vs.value||(n?He?.instanceId:void 0));if(!n&&(!i||!o||i.stale||i.state!=="attached"||!i.capabilities.storage)){q.storage=[],q.storageError=!i||!i.capabilities.storage?"当前设备不支持存储诊断":"当前设备未连接或没有运行实例";return}if(Fe){q.storage=[{area:"local",key:"preferences",serializedValue:'{"theme":"light","language":"zh-CN"}',bytes:36},{area:"local",key:n?"lastOpenedProject":"deviceModel",serializedValue:n?'"demo-project"':'"iPhone 16 Pro"',bytes:n?14:15}],q.storageError="";return}if(!o){q.storage=[],q.storageError="";return}try{const a=await uh({instanceId:o,resource:"storage"},{csrfToken:De.csrfToken,signal:AbortSignal.any([t.signal,ar.signal])});if(!s())return;if(a.code)throw new Error(a.error??"Storage 诊断查询失败");q.storage=a.value,q.storageError=""}catch(a){if(!s())return;q.storage=[],q.storageError=yc(a)}}function Hm(e,t=He){const r=(c,d)=>{if(!(!c||typeof c!="object"))try{return Object.getOwnPropertyDescriptor(c,d)?.value}catch{return}},n=(c,d)=>{const u=r(c,d);return typeof u=="string"?u.slice(0,8192):void 0},i=r(e,"cause"),o=n(e,"stack")??n(i,"stack"),s=n(e,"name")??n(i,"name"),a=typeof i=="string"?i:[n(i,"name"),n(i,"message")].filter(Boolean).join(": ");return{code:n(e,"code")??"RUNTIME_START_FAILED",message:n(e,"message")??(typeof e=="string"?e:"Runtime 启动失败"),phase:t?.hadReady?"running":"starting",...s?{name:s}:{},...o?{stack:o}:{},...a?{cause:a}:{}}}function Xt(e,t,r=Date.now(),n,i){ZM(qs(e,t,r,n==="debug"?"log":n),i)}function ZM(e,t){if(_e)return;if(Fe){Gs({...e,targetId:q.diagnosticTargetId});return}const r=We(e.detail)?e.detail:{};ct.event(t,{source:t&&e.source==="runtime"?"runtime":"host",level:e.level,timestamp:e.timestamp,message:e.summary,method:e.method,...typeof r.phase=="string"?{phase:r.phase}:{},...e.callId?{callId:e.callId}:{},...e.outcome?{outcome:e.outcome}:typeof r.outcome=="string"?{outcome:r.outcome}:{},...e.durationMs===void 0?{}:{durationMs:e.durationMs},...typeof r.startedAt=="number"?{startedAt:r.startedAt}:{},...e.errorCode?{errorCode:e.errorCode}:{},...We(r.network)?{network:r.network}:{}})}async function KM(e){const t=He;if(!t||e.instanceId!==t.instanceId||!Be(t)||!t.runtime)return{code:"closed",error:"该实例已结束"};if(Date.now()>=e.deadline)return{code:"timeout",error:"查询已超过期限"};if(e.resource==="presentation")return{value:t.interactions.snapshot()};if(e.resource==="sandbox")return{code:"unsupported",error:"Browser Dev Host 不提供文件系统能力"};const r=t.runtime,n=r.diagnostics.storage;if(!n)return{code:"unsupported",error:"当前 Host 不支持 Storage 诊断"};const i=AbortSignal.any([ar.signal,t.terminal.signal,AbortSignal.timeout(Math.max(1,e.deadline-Date.now()))]);let o,s;try{s=await Promise.race([n.getSnapshot(),new Promise((a,c)=>{o=()=>c(i.reason),i.addEventListener("abort",o,{once:!0}),i.aborted&&o()})])}catch{return{code:Date.now()>=e.deadline?"timeout":"closed",error:"实例查询已结束或超过期限"}}finally{o&&i.removeEventListener("abort",o)}return!Be(t)||r!==t.runtime||e.instanceId!==t.instanceId?{code:"closed",error:"查询期间实例已结束"}:{value:s}}function JM(e,t){Ht("host.message",{message:e,status:t})}function XM(e){_e||JM(yc(e),"error")}function Ht(e,t){Xt(e,t)}function eS(){ct.close(),va!==void 0&&window.clearTimeout(va),Oa!==void 0&&window.clearTimeout(Oa),!_e&&(_e=!0,gi.dispose(),wa.dispose(),window.__HB_SDK_PREVIEW__===Dm&&delete window.__HB_SDK_PREVIEW__,window.removeEventListener("hb-sdk:refresh-storage",Pn),window.removeEventListener("hb-sdk:qr-open-change",Tm),Fo+=1,ar.abort(new DOMException("Browser Dev Host disposed","AbortError")),Br.dispose(),Ot("Browser Dev Host disposed"),ut.dispose(),ct.send({operation:"close-target",reason:"Browser Dev Host disposed"}),window.setTimeout(()=>Em.abort(),2e3),pi?.close(),Yt?.dispose(),Yt=void 0,Ta.dispose(),At!==void 0&&window.clearTimeout(At),At=void 0,Vo(),ya!==void 0&&window.clearInterval(ya),go.clear(),Ea?.(),Ea=void 0,Ia?.(),Ia=void 0,_a?.(),_a=void 0,Aa?.(),Aa=void 0,Da?.(),Da=void 0,ba?.(),ba=void 0)}function Vo(){hi!==void 0&&window.clearTimeout(hi),hi=void 0}function Fm(e,t){return t?AbortSignal.any([e,t]):e}function $m(e){return!_e&&e===Fo}function tS(){return Pt.find(({id:e})=>e===Ne.mobileLanSelect.value)}function rS(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 Vm(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 Gm(e){return{networkRequest:{...e.networkRequest}}}function nS(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function yc(e){return e instanceof Error&&e.message?e.message:"操作失败"}function We(e){return Object.prototype.toString.call(e)==="[object Object]"}function ri(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function qm(e){return document.querySelector(e)??void 0}
|