@heybox/hb-sdk 0.9.6-alpha.1 → 0.9.6-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -3
  3. package/dist/cli-chunks/{artifact-C5n7xjnz.cjs → artifact-D86asFjh.cjs} +3 -3
  4. package/dist/cli-chunks/{build-BgBt5SkX.cjs → build-C1LPbI94.cjs} +5 -5
  5. package/dist/cli-chunks/{create-BL6uwtkQ.cjs → create-Byf1oQzQ.cjs} +1 -1
  6. package/dist/cli-chunks/{dev-NgklQb6b.cjs → dev-CbcdKYGb.cjs} +8 -8
  7. package/dist/cli-chunks/{dev-context-Tf8MgSsu.cjs → dev-context-Dmlt0lOG.cjs} +2 -2
  8. package/dist/cli-chunks/{doctor-CGlEf1yi.cjs → doctor-CSqUoHmq.cjs} +1 -1
  9. package/dist/cli-chunks/{games-Cc-DclmK.cjs → games-BgMB9Sp_.cjs} +1 -1
  10. package/dist/cli-chunks/{index-D9XLBbNV.cjs → index-C48LyQmX.cjs} +1 -1
  11. package/dist/cli-chunks/{index-CmxsiTTn.cjs → index-Dx--h963.cjs} +17 -17
  12. package/dist/cli-chunks/{index.esm-DnyLP_Zc.cjs → index.esm-C5dcsrVZ.cjs} +6 -6
  13. package/dist/cli-chunks/{login-ZMBDHBuA.cjs → login-rffql4fh.cjs} +1 -1
  14. package/dist/cli-chunks/{project-vite-eM87vX9L.cjs → project-vite-C7Nc00mY.cjs} +1 -1
  15. package/dist/cli-chunks/{remote-DVhxpWDg.cjs → remote-Bl1ve6w9.cjs} +6 -6
  16. package/dist/cli-chunks/{runtime-permission-env-q1FWWwbV.cjs → runtime-permission-env-CxG2c1dS.cjs} +2 -2
  17. package/dist/cli-chunks/{skill-mRXM87hY.cjs → skill-DGINpnjS.cjs} +2 -2
  18. package/dist/cli-chunks/{version-BqHRI4Lz.cjs → version-D0gJvLhX.cjs} +1 -1
  19. package/dist/cli.cjs +1 -1
  20. package/dist/devtools/browser-dev-host/assets/{browser-dev-host-DtWOjzCe.js → browser-dev-host-DA94kRxx.js} +1 -1
  21. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-C2Vw0-AC.js → desktop-app-launch-DwX62DHx.js} +1 -1
  22. package/dist/devtools/browser-dev-host/assets/{index-B-rjfibN.js → index--xK6G3mS.js} +3 -3
  23. package/dist/devtools/browser-dev-host/index.html +2 -2
  24. package/dist/index.cjs.js +8 -3
  25. package/dist/index.esm.js +8 -3
  26. package/dist/vite.cjs.js +1 -1
  27. package/dist/vite.esm.js +1 -1
  28. package/package.json +6 -6
  29. package/skill/skill.json +4 -4
  30. package/types/index.d.ts +8 -1
@@ -1,4 +1,4 @@
1
- import{H as Ls,aI as nl,bd as il,U as ol,aY as sl,aZ as al,au as xr,bn as W,aT as Qc,k as Yc,ak as cl,av as qc,aB as dl,bh as Xt,aM as $c,aO as ul,g as Wc,af as Kc,v as ll,ax as fl,i as hl,aV as Zc,ai as ml,aE as Jc,y as gl,aK as Xc,u as pl,aU as yl,bf as El,be as wl,d as Il,h as Al}from"./desktop-app-launch-C2Vw0-AC.js";const En="workspaceCards.requestRefresh",wn="auth.getAccountState",In="auth.login",An="user.getFollowStatus",Mn="user.requestFollowAuthor",Ml="gameSaves.list",Nl="gameSaves.sync",Dl="gameSaves.getFile",Sl="gameSaves.readParsedData",Nn="user.getInfo",Dn="user.revokeAuthorization",Sn="user.getSteamGameList",wr="user.showAppreciation",Tn="share.copyLink",_n="share.showShareMenu",bn="share.screenshot",pt="viewport.setDisplay",On="viewport.getWindowInfo",vn="viewport.setNavigationBarStyle",Ir="storage.getStorage",Ar="storage.setStorage",Cn="network.request",Ln="network.download",Rn="network.upload",Pn="files.pickFiles",kn="files.pickDirectory",xn="files.saveFile",Mr="file.create",Nr="file.remove",Un="file.exists",Dr="file.readText",jn="file.writeText",Sr="file.readBytes",zn="file.writeBytes",Tr="file.stat",Hn="directory.create",_r="directory.remove",Fn="directory.exists",Vn="directory.list",br="media.pick",Bn="ui.showToast",Gn="ui.showLoading",Qn="ui.hideLoading",Yn="device.vibrate",qn="device.setClipboard",$n="device.executeProtocol",Wn="navigation.close",Kn="navigation.reload",Zn="navigation.openAppPage",Qe="cloud.leaderboard.submit",Oe="cloud.leaderboard.getList",et="cloud.leaderboard.getCurrentUserEntry",yt="cloud.leaderboard.deleteCurrentUserEntry",He="cloud.leaderboard.getInfo",jt="cloud.storage.getStorage",zt="cloud.storage.setStorage",Ht="cloud.storage.removeItem",Et="cloud.storage.getKeys",ui="companion.getInfo",li="companion.getPreparationStatus",fi="companion.prepare",hi="companion.cancelPreparation",mi="companion.getActiveSession",gi="companion.launch",pi="companion.session.write",yi="companion.session.closeStdin",Ei="companion.session.terminate",wi="companion.session.ackOutput",Ii="companion.openAttachment",Ai="companion.showNotification",tt=[...[Ml,Nl,Dl,Sl].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),{method:En,module:"workspaceCards",capability:En,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:wn,module:"auth",capability:wn,requirement:{kind:"none"},risk:"low"},{method:In,module:"auth",capability:In,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:An,module:"user",capability:An,requirement:{kind:"none"},risk:"low"},{method:Mn,module:"user",capability:Mn,requirement:{kind:"none"},risk:"high"},{method:Nn,module:"user",capability:Nn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Dn,module:"user",capability:Dn,requirement:{kind:"none"},risk:"high"},{method:Sn,module:"user",capability:Sn,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:wr,module:"user",capability:wr,requirement:{kind:"none"},risk:"medium"},{method:Tn,module:"share",capability:Tn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:_n,module:"share",capability:_n,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:bn,module:"share",capability:bn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:On,module:"viewport",capability:On,requirement:{kind:"none"},risk:"low"},{method:vn,module:"viewport",capability:vn,requirement:{kind:"none"},risk:"low"},{method:pt,module:"viewport",capability:pt,requirement:{kind:"none"},risk:"low"},{method:Ir,module:"storage",capability:Ir,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:Ar,module:"storage",capability:Ar,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Cn,module:"network",capability:Cn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Ln,module:"network",capability:Ln,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Rn,module:"network",capability:Rn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Pn,module:"files",capability:Pn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:kn,module:"files",capability:kn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:xn,module:"files",capability:xn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mr,module:"file",capability:Mr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Nr,module:"file",capability:Nr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Un,module:"file",capability:Un,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dr,module:"file",capability:Dr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:jn,module:"file",capability:jn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Sr,module:"file",capability:Sr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:zn,module:"file",capability:zn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Tr,module:"file",capability:Tr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Hn,module:"directory",capability:Hn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_r,module:"directory",capability:_r,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Fn,module:"directory",capability:Fn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Vn,module:"directory",capability:Vn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:br,module:"media",capability:br,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:Bn,module:"ui",capability:Bn,requirement:{kind:"none"},risk:"low"},{method:Gn,module:"ui",capability:Gn,requirement:{kind:"none"},risk:"low"},{method:Qn,module:"ui",capability:Qn,requirement:{kind:"none"},risk:"low"},{method:Yn,module:"device",capability:Yn,requirement:{kind:"none"},risk:"low"},{method:qn,module:"device",capability:qn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:$n,module:"device",capability:$n,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:Wn,module:"navigation",capability:Wn,requirement:{kind:"none"},risk:"medium"},{method:Kn,module:"navigation",capability:Kn,requirement:{kind:"none"},risk:"medium"},{method:Zn,module:"navigation",capability:Zn,requirement:{kind:"none"},risk:"medium"},{method:Qe,module:"cloud",capability:Qe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Oe,module:"cloud",capability:Oe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:et,module:"cloud",capability:et,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:yt,module:"cloud",capability:yt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:He,module:"cloud",capability:He,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:jt,module:"cloud",capability:jt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:zt,module:"cloud",capability:zt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Ht,module:"cloud",capability:Ht,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Et,module:"cloud",capability:Et,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[ui,li,fi,hi,mi,gi,pi,yi,Ei,wi,Ii,Ai].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],at="heybox:miniprogram",ed=2,Tl="hb_mini_bridge_nonce",td="sdk.handshake",Br="runtime.location.probe",_l="sdk.location.report",bl="sdk.csp.violation",rd="operation.progress",Ol="companion.session.output",vl="companion.session.exit",Cl="companion.session.ownershipLost";function Ll(e){return!Re(e)||e.namespace!==at||e.version!==1&&e.version!==2||!ce(e.nonce)?!1:e.type==="handshake"?ce(e.id)&&e.method===td&&e.error===void 0&&Hl(e.payload):e.type==="request"?ce(e.id)&&ce(e.method)&&e.error===void 0:e.type==="response"?ce(e.id)&&(e.method===void 0||ce(e.method))&&(e.error===void 0||Fl(e.error)):e.type==="event"?!ce(e.method)||e.error!==void 0?!1:e.method===rd?e.version===2&&ce(e.id)&&zl(e.payload):e.id===void 0||ce(e.id):e.type==="cancel"?e.version===2&&ce(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function os(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function nd(e){return Re(e)?e.kind==="sandbox"?Te(e,["kind"]):e.kind==="directory"&&ce(e.handleId)&&Te(e,["kind","handleId"]):!1}function Ft(e){return!Re(e)||e.kind!=="file"?!1:ce(e.handleId)?Te(e,["kind","handleId"]):nd(e.root)&&os(e.relativePath)&&Te(e,["kind","root","relativePath"])}function id(e){return!Re(e)||e.kind!=="directory"?!1:ce(e.handleId)?Te(e,["kind","handleId"]):nd(e.root)&&(e.relativePath==="."||os(e.relativePath))&&Te(e,["kind","root","relativePath"])}function Rl(e){return Re(e)&&e.kind==="file"&&ce(e.name)&&Vl(e.mode)&&Ft(e.ref)&&Te(e,["kind","name","mode","ref"])}const od=20,Rs=["type","mimeType","size","width","height","previewUrl","file"];function Pl(e){return e===void 0?!0:!(!Re(e)||!Te(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&&(!Bl(e.maxCount,1,od)||e.source==="camera"&&e.maxCount!==1))}function sd(e){if(!Re(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!Te(e,t?[...Rs,"durationMs"]:Rs)||!ce(e.mimeType)||!Ze(e.size)||!Ps(e.width)||!Ps(e.height)||!ce(e.previewUrl)||!xl(e.file)?!1:t?Ze(e.durationMs):!0}function kl(e){if(!Array.isArray(e)||e.length<1||e.length>od)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!sd(e[t]))return!1;return!0}function xl(e){return!Rl(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&ce(e.ref.handleId)}function ad(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function Ul(e){return!Re(e)||!Ze(e.loaded)||typeof e.lengthComputable!="boolean"||!Te(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Ze(e.total)&&e.loaded<=e.total:e.total===void 0}function jl(e){return Re(e)?e.phase==="downloading"?Ze(e.loaded)&&(e.total===void 0||Ze(e.total)&&e.loaded<=e.total)&&Te(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Ze(e.processed)&&Ze(e.total)&&e.processed<=e.total&&Te(e,["phase","processed","total"]):!1}function zl(e){return Ul(e)||jl(e)}function Hl(e){return Re(e)&&ce(e.href)&&typeof e.userAgent=="string"&&ce(e.sdkVersion)}function Fl(e){return Re(e)&&ce(e.code)&&typeof e.message=="string"}function Vl(e){return e==="read"||e==="readwrite"}function Ze(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ps(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Bl(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function ce(e){return typeof e=="string"&&e.length>0}function Te(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Or=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards"],cd=[{key:"gameSaves",name:"游戏存档",description:"获取和同步当前用户指定游戏的 Steam 云存档,并读取存档文件,无需单独弹窗确认。",access:"declaration",risk:"high",config:{},methods:["gameSaves.list","gameSaves.sync","gameSaves.getFile","gameSaves.readParsedData"],conditions:["需要用户明确授权、有效 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"],conditions:["继续执行分享参数校验和 Host 支持检查。"]},{key:"storage",name:"键值存储",description:"读写按小程序隔离的简单键值数据。",access:"declaration",risk:"medium",config:{},methods:["storage.getStorage","storage.setStorage"],conditions:["仅用于简单键值存储,不包含文件系统。"]},{key:"cloud_storage",name:"云端存储",description:"读写按小程序和当前登录用户隔离的云端键值数据。",access:"declaration",risk:"medium",config:{},methods:["cloud.storage.getStorage","cloud.storage.setStorage","cloud.storage.removeItem","cloud.storage.getKeys"],conditions:["云端存储按登录用户隔离并受容量配额限制。"]},{key:"filesystem",name:"文件系统",description:"访问小程序沙盒文件和用户选择的外部文件。",access:"declaration",risk:"high",config:{},methods:["network.download","network.upload","files.pickFiles","files.pickDirectory","files.saveFile","file.create","file.remove","file.exists","file.readText","file.writeText","file.readBytes","file.writeBytes","file.stat","directory.create","directory.remove","directory.exists","directory.list"],conditions:["外部文件继续要求有效的用户选择、会话句柄和匹配的读写模式。"]},{key:"media",name:"媒体",description:"通过系统图库或相机选择图片、视频。",access:"declaration",risk:"high",config:{},methods:["media.pick"],conditions:["图库授权范围仅限本次用户选择的媒体,不包含任意文件或沙盒访问权;继续执行可信手势、Host 能力与会话资源规则。"]},{key:"clipboard",name:"剪贴板",description:"向系统剪贴板写入文本。",access:"declaration",risk:"medium",config:{},methods:["device.setClipboard"],conditions:["继续执行文本长度和 Host 支持限制。"]},{key:"leaderboard",name:"排行榜",description:"读写小程序云排行榜。",access:"declaration",risk:"medium",config:{},methods:["cloud.leaderboard.submit","cloud.leaderboard.getList","cloud.leaderboard.getCurrentUserEntry","cloud.leaderboard.deleteCurrentUserEntry","cloud.leaderboard.getInfo"],conditions:["排行榜必须已创建,用户和资源规则保持不变。"]},{key:"network",name:"网络",description:"通过 network 模块请求或下载外部资源。",access:"platform-approval",risk:"high",config:{useOfficialDomain:{type:"boolean",required:!1,default:!1,description:"是否申请访问小黑盒官方域名。"}},methods:["network.request","network.download","network.upload"],conditions:["声明后仍需平台批准,并继续执行网络安全策略。"]},{key:"companion",name:"桌面辅助应用",description:"下载、准备并运行随当前小程序版本发布的受管桌面程序。",access:"platform-approval",risk:"high",config:{},methods:["companion.getInfo","companion.getPreparationStatus","companion.prepare","companion.cancelPreparation","companion.getActiveSession","companion.launch","companion.session.write","companion.session.closeStdin","companion.session.terminate","companion.session.ackOutput","companion.openAttachment","companion.showNotification"],conditions:["声明后仍需平台批准,并继续执行可信用户手势、Host 能力和当前版本 Manifest 校验。"]},{key:"appProtocol",name:"应用协议执行",description:"执行任意小黑盒客户端协议。",access:"platform-approval",risk:"high",config:{},methods:["device.executeProtocol"],conditions:["最高危险权限:批准后该入口可执行任意协议,并绕过其他 SDK 能力权限及专用授权流程。"]},{key:"workspaceCards",name:"工作区卡片",description:"在已绑定游戏的桌面工作区展示受审核卡片。",access:"platform-approval",risk:"high",config:{},methods:["workspaceCards.requestRefresh"],conditions:["需平台批准、Host 支持与有效执行租约;不隐式授予网络或存储权限。"]}];new Set(Or);const Gl=new Set(Or);function Ql(e){return Gl.has(e)}function Ce(e){if(!Gr(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(!Gr(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),!!Ql(o)){if(o==="network"){const s=n.config;if(!Gr(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(n.config!==null&&n.config!==void 0&&(!Gr(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 Gr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const rn=["network","companion","appProtocol"];function dd(e){if(!er(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>rn.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!er(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(!er(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(!er(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!er(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>rn.indexOf(n.key)-rn.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Yl(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Ce(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of rn)!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 ss(e){const t=Ce(e.runtimePermissions),r=dd(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of Or)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:cd.some(a=>a.key===s&&a.access==="declaration")?n[s]={key:s,status:"enabled",config:{}}:s==="network"&&n.network&&(n.network.config.useOfficialDomain=n.network.status==="enabled"&&n.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(r.valid)for(const s of r.grant.entries)e.declaredPermissions[s.key]?.enabled!==!0||n[s.key]?.status==="enabled"||(n[s.key]=s,i.push(s.key));const o=ud(e.runtimePermissions)&&typeof e.runtimePermissions.revision=="number"&&Number.isSafeInteger(e.runtimePermissions.revision)&&e.runtimePermissions.revision>=0?e.runtimePermissions.revision:void 0;return{runtimePermissions:{schema_version:1,...o===void 0?{}:{revision:o},entries:Or.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function ud(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function er(e,t){return ud(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Vt=["identity","profile","steam_account"],ql=/^[a-z][a-z0-9-]{0,31}$/,ld=["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"];tt.map(e=>e.method);function $l(e){const t=Ce(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 Wl(e){const t=Ce(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 ee(e,t,r){return{code:e,message:t,data:r}}function as(e){return Kl(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?ee("RUNTIME_ERROR",e.message):ee("UNKNOWN_ERROR","小程序运行时异常",e)}function Kl(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function Zl(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Jl=1e3;function Xl(e,t=Zl()){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<=Jl}const ef="runtime.gate.probe",fd=new Set(tt.map(e=>e.method));class tf{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=ed;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,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:at,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:at,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:at,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:at,version:2,nonce:this.nonce,type:"event",id:t,method:rd,payload:r})}onMessage(t){if(!this.started||!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=Xl(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&&Ll(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:at,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:td,payload:{environment:this.environmentInfo}}),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===ef){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,ee("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!fd.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,{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=as(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:at,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!rf(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 rf(e){return typeof e=="string"&&fd.has(e)}function m(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):nf(e.signal,t);return{...e,signal:r}}function nf(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 of(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"}function nn(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function X(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:nn()}function sf(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 hd="METHOD_FORBIDDEN";function De(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=hd,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 af=/^[A-Za-z0-9_-]{1,64}$/,ks=1e3;function md(e){return af.test(e)?e:df(e)}function cf(e){return`id_${md(e.trim())}`}function Nt(e,t){return`hb_miniprogram_${e}_${t}`}function Qr(e){return`hb_miniprogram_keys_${e}`}function df(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 xs={"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"],[En]:["workspaceCards.requestRefresh"],[wn]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[In]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[An]:["account.getCurrentUserId","account.onChange","network.request"],[Mn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Nn]:["account.getCurrentUserId","account.onChange","network.request"],[Dn]:["account.getCurrentUserId","account.onChange","network.request"],[Sn]:["account.getCurrentUserId","account.onChange","network.request"],[Tn]:["presentation.setClipboard"],[_n]:["presentation.showShareMenu"],[bn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[pt]:["presentation.applyOrientation"],[On]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[vn]:["presentation.setNavigationBarStyle"],[Ir]:["storage.getRaw"],[Ar]:["storage.setRaw"],[Cn]:["network.request"],[Ln]:["network.stream","files.transfer","files.access"],[Rn]:["network.upload","files.access"],[Pn]:["files.external"],[kn]:["files.external"],[xn]:["files.save"],[Mr]:["files.access"],[Nr]:["files.removeFile"],[Un]:["files.access"],[Dr]:["files.access"],[jn]:["files.access"],[Sr]:["files.access"],[zn]:["files.access"],[Tr]:["files.access"],[Hn]:["files.access"],[_r]:["files.removeDirectory"],[Fn]:["files.access"],[Vn]:["files.access"],[br]:["media.pick"],[wr]:["presentation.showAppreciation"],[Bn]:["presentation.showToast"],[Gn]:["presentation.showLoading"],[Qn]:["presentation.hideLoading"],[Yn]:["presentation.vibrate"],[qn]:["presentation.setClipboard"],[$n]:["protocol.invoke"],[Wn]:["presentation.close"],[Kn]:["presentation.reload"],[Zn]:["presentation.openAppPage"],[Qe]:["account.getCurrentUserId","account.onChange","network.request"],[Oe]:["account.onChange","network.request"],[et]:["account.getCurrentUserId","account.onChange","network.request"],[yt]:["account.getCurrentUserId","account.onChange","network.request"],[He]:["account.onChange","network.request"],[jt]:["account.getCurrentUserId","account.onChange","network.request"],[zt]:["account.getCurrentUserId","account.onChange","network.request"],[Ht]:["account.getCurrentUserId","account.onChange","network.request"],[Et]:["account.getCurrentUserId","account.onChange","network.request"],[ui]:["companion.getInfo"],[li]:["companion.getPreparationStatus"],[fi]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[hi]:["companion.cancelPreparation"],[mi]:["companion.getActiveSession"],[gi]:["companion.getInfo","companion.launch"],[pi]:["companion.session.write"],[yi]:["companion.session.closeStdin"],[Ei]:["companion.session.terminate"],[wi]:["companion.session.ackOutput"],[Ii]:["companion.openAttachment"],[Ai]:["companion.showNotification"]},uf=new Set([wr]);function lf(e,t){if(t[e]!==!0)throw uf.has(e)?ee("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):De(e)}const ff=32*1024*1024,hf=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function mf(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:ff},i);return gf(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function gf(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:pf(t,Ef(e,"content-type"))}}function pf(e,t){yf(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||!hf.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function yf(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 Ef(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function U(e){return typeof e=="function"}function Us(e){return(...t)=>{throw De(e)}}function de(e){return async(...t)=>{throw De(e)}}const wf=(e,t)=>{},If=()=>()=>{};function Af(e){const t={request:U(e.network?.request)?e.network.request.bind(e.network):de("network.request")},r={...U(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:U(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):de("account.getCurrentUserId"),ensureAuthenticated:U(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):de("account.ensureAuthenticated"),onChange:U(e.account?.onChange)?e.account.onChange.bind(e.account):If},n={getRaw:U(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):de("storage.getRaw"),setRaw:U(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):de("storage.setRaw")},i={...U(e.presentation?.showSteamLoginRequired)?{showSteamLoginRequired:e.presentation.showSteamLoginRequired.bind(e.presentation)}:{},...U(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...U(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:U(e.presentation?.close)?e.presentation.close.bind(e.presentation):de("presentation.close"),reload:U(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):de("presentation.reload"),openAppPage:U(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):de("presentation.openAppPage"),openWindow:U(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):de("presentation.openWindow"),getViewportMetrics:U(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Us("presentation.getViewportMetrics"),getNavigationBarHeight:U(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Us("presentation.getNavigationBarHeight"),setNavigationBarStyle:U(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):de("presentation.setNavigationBarStyle"),showShareMenu:U(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):de("presentation.showShareMenu"),setScreenshotChromeHidden:U(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):wf,captureAndShare:U(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):de("presentation.captureAndShare"),showAppreciation:U(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw ee("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:U(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):de("presentation.showToast"),showLoading:U(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):de("presentation.showLoading"),hideLoading:U(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):de("presentation.hideLoading"),vibrate:U(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):de("presentation.vibrate"),setClipboard:U(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):de("presentation.setClipboard")},o=U(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,U(e.companion?.[c])?e.companion[c].bind(e.companion):de(`companion.${c}`)]));U(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const a={invoke:U(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):de("protocol.invoke")};return{network:t,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 Mf(e){const t=Nf(e.files?.sandbox),r=U(e.picker?.pickFiles)&&U(e.picker?.pickDirectory),n=U(e.picker?.saveFile),i=t||r||n||U(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":U(e.account?.getAccountKey),"account.getCurrentUserId":U(e.account?.getCurrentUserId),"account.ensureAuthenticated":U(e.account?.ensureAuthenticated),"account.onChange":U(e.account?.onChange),"network.request":U(e.network?.request),"network.stream":U(e.transfer?.network.open)&&U(e.transfer?.network.release),"network.upload":U(e.transfer?.upload?.upload),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":U(o?.remove),"files.removeDirectory":U(e.files?.sandbox.remove),"files.transfer":U(e.transfer?.files.writeResource),"media.pick":U(e.media?.pick),"storage.getRaw":U(e.scopedStorage?.get)||U(e.storage?.getRaw),"storage.setRaw":U(e.scopedStorage?.set)||U(e.storage?.setRaw),"presentation.close":U(e.presentation?.close),"presentation.reload":U(e.presentation?.reload),"presentation.openAppPage":U(e.presentation?.openAppPage),"presentation.applyOrientation":U(e.presentation?.applyOrientation),"presentation.openWindow":U(e.presentation?.openWindow),"presentation.getViewportMetrics":U(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":U(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":U(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":U(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":U(e.presentation?.captureAndShare),"presentation.showAppreciation":U(e.presentation?.showAppreciation),"presentation.showToast":U(e.presentation?.showToast),"presentation.showLoading":U(e.presentation?.showLoading),"presentation.hideLoading":U(e.presentation?.hideLoading),"presentation.vibrate":U(e.presentation?.vibrate),"presentation.setClipboard":U(e.presentation?.setClipboard),"workspaceCards.requestRefresh":!1,"companion.getInfo":U(e.companion?.getInfo),"companion.getPreparationStatus":U(e.companion?.getPreparationStatus),"companion.prepare":U(e.companion?.prepare),"companion.cancelPreparation":U(e.companion?.cancelPreparation),"companion.getActiveSession":U(e.companion?.getActiveSession),"companion.launch":U(e.companion?.launch),"companion.session.write":U(e.companion?.write),"companion.session.closeStdin":U(e.companion?.closeStdin),"companion.session.terminate":U(e.companion?.terminate),"companion.session.ackOutput":U(e.companion?.ackOutput),"companion.openAttachment":U(e.companion?.openAttachment),"companion.showNotification":U(e.companion?.showNotification),"protocol.invoke":U(e.protocol?.invoke)}}function Nf(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&U(t.file)&&U(t.directory)&&U(t.create)&&U(t.stat)&&U(t.list)}function js(e,t){return t?.[e]!==!1}function Df(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function gd(e,t={}){const r={};for(const n of Object.keys(xs)){const o=xs[n].every(a=>e[a]),s=!Df(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=js(n,t.callerCapabilities)&&js(n,t.hostCapabilities)&&o&&s}return r}function pd(e={},t={}){const r=Mf(e),n=gd(r,t);return{ports:Af(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}const Sf=4,Tf=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],_f=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),bf=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Of=["/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 vf(e,t){const r=Rf(e);return r===null||zs(r,bf)?!0:t&&zs(r,Of)}function Cf(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Tf.some(r=>t===r||t.endsWith(`.${r}`))}function Lf(e){const t=e.trim().toLowerCase();return _f.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Rf(e){let t=e;for(let r=0;r<Sf;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Hs(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Hs(t)}function zs(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Hs(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Fs(e){return e instanceof le?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function $(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(nn());let n;try{n=e()}catch(i){return Promise.reject(Fs(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(nn())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(nn()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(Fs(d))))})}function Pf(e){return{[wr]:async(t,r)=>{const n=Ne(e.operationContext,r.signal);if(X(n.signal),t!==void 0)throw m("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw m("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw m("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const o=e.presentation.showAppreciation;if(!o)throw m("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await $(()=>o({name:i.name,author:i.author},n),n.signal)}}}function Dt(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Vs(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function yd(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(w,v){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:w,type:v})).catch(()=>{})}catch{}}function u(w){const v=r.get(w);if(!v)throw new Error("Unknown runtime cache scope");return v}function f(w,v){return w.flatMap((N,C)=>{const _=JSON.stringify(w.slice(0,C+1));return[JSON.stringify([_]),JSON.stringify([_,v])]})}function l(w,v){return JSON.stringify(f(w,v).map(N=>n.get(N)??0))}async function h(w,v){const N=u(w),C=JSON.stringify([JSON.stringify(N),...v?[v]:[]]),_=(n.get(C)??0)+1;n.set(C,_),i.add(C);for(const k of a)k(N,v);if(!e.store){i.delete(C),d(v??"*","invalidation");return}try{await e.store.invalidate(N,v)}catch(k){throw d(v??"*","storage_error"),k}n.get(C)===_&&i.delete(C),d(v??"*","invalidation")}function y(w){if(c)throw new Error("Runtime cache manager disposed");const v=o.get(w.namespace);if(v){if(v.sourceCodec!==w.codec||v.definition.codec.version!==w.codec.version||JSON.stringify(v.definition.policy)!==JSON.stringify(w.policy))throw new Error("Conflicting runtime cache namespace");return v.cache}if(!w.namespace||!w.codec.version)throw new Error("Invalid runtime cache definition");const N=Object.freeze({...w.policy}),C=Object.freeze({version:w.codec.version,encode:w.codec.encode.bind(w.codec),decode:w.codec.decode.bind(w.codec),validate:w.codec.validate.bind(w.codec),clone:w.codec.clone.bind(w.codec)}),_=w.namespace;for(const S of[N.ttlMs,N.memoryMaxEntries,N.diskMaxEntries,N.diskMaxBytes,N.maxEntryBytes])if(!Number.isFinite(S)||S<0)throw new Error("Invalid runtime cache policy");const k=new Map,F=new Map,j=new Map;let g=!1;function I(S,E,L){if(c||g||S.aborted||l(E,_)!==L)throw Dt()}function b(S){return N.ttlMs>0&&N.persistence==="memory-and-disk"&&!!e.store&&!f(S,_).some(E=>i.has(E))}function D(S,E,L){const R=t();return S.envelopeVersion===1&&JSON.stringify(S.address)===JSON.stringify(E)&&Vs(S.revisions,L)&&S.payload.byteLength<=N.maxEntryBytes&&Number.isFinite(S.cachedAt)&&Number.isFinite(S.expiresAt)&&S.cachedAt<=R&&S.cachedAt>=0&&S.expiresAt>S.cachedAt&&Math.min(S.expiresAt,S.cachedAt+N.ttlMs)>R}function P(S,E,L,R,x){if(!(N.ttlMs<=0||N.memoryMaxEntries<1)){for(const[z,H]of k)Math.min(H.entry.expiresAt,H.entry.cachedAt+N.ttlMs)<=t()&&k.delete(z);for(k.delete(S);k.size>=Math.floor(N.memoryMaxEntries);){const z=k.keys().next();if(z.done)break;k.delete(z.value)}k.set(S,{entry:E,value:L,epoch:R,persistent:x})}}async function p(S,E,L,R){const x={namespace:_,codecVersion:C.version,scopeIds:E,key:S.key},z=JSON.stringify(x);let H=[],V=b(E);if(V)try{H=await e.store.readRevisions(E,_)}catch{V=!1,d(_,"storage_error")}I(R.signal,E,L);async function G(){if(!V)return!0;try{return Vs(H,await e.store.readRevisions(E,_))}catch{return V=!1,d(_,"storage_error"),!1}}const K=k.get(z);if(N.ttlMs>0&&K&&K.epoch===L&&D(K.entry,x,H)&&K.persistent===V&&await G())return I(R.signal,E,L),d(_,"memory_hit"),K.value;if(k.delete(z),V){let Y,ie;try{Y=await e.store.read(x,N.maxEntryBytes),Y&&D(Y,x,H)?ie=C.decode(Y.payload):Y=void 0}catch{Y=void 0,d(_,"storage_error")}if(I(R.signal,E,L),Y&&await G())return I(R.signal,E,L),P(z,Y,ie,L,!0),d(_,"disk_hit"),ie}d(_,"miss");const Z=C.validate(await S.load(R.signal));I(R.signal,E,L);const J=C.clone(Z);if(!await G()&&V)throw Dt();if(I(R.signal,E,L),N.ttlMs>0){const Y=t();let ie;try{ie=C.encode(J)}catch{return J}const Pe={envelopeVersion:1,address:x,revisions:V?H:[],cachedAt:Y,expiresAt:Y+N.ttlMs,payload:ie};if(V&&ie.byteLength<=N.maxEntryBytes){let ge=!0,he=!1;try{ge=await e.store.publish(Pe,N),he=ge}catch{d(_,"storage_error")}if(I(R.signal,E,L),!ge)throw Dt();he&&d(_,"published")}I(R.signal,E,L),P(z,Pe,J,L,V)}return J}async function T(S){if(c||g||S.signal?.aborted)return Promise.reject(Dt());const E=u(S.scope),L=l(E,_);let R;if(b(E)){const V=new AbortController;j.set(V,E);const G=()=>V.abort();S.signal?.addEventListener("abort",G,{once:!0});let K=()=>{};try{R=await Promise.race([e.store.readRevisions(E,_),new Promise((Z,J)=>{const Y=()=>J(Dt());V.signal.addEventListener("abort",Y,{once:!0}),K=()=>V.signal.removeEventListener("abort",Y)})])}catch{V.signal.aborted||d(_,"storage_error")}finally{K(),j.delete(V),S.signal?.removeEventListener("abort",G)}}I(S.signal??new AbortController().signal,E,L);const x=JSON.stringify([E,S.key,L,R]);let z=F.get(x);if(z?.controller.signal.aborted&&(z=void 0),!z){const V=new AbortController;z={ids:E,controller:V,waiters:0,promise:Promise.resolve(void 0)};const G=z;G.promise=p(S,E,L,V).finally(()=>{F.get(x)===G&&F.delete(x)}),F.set(x,G)}const H=z;return H.waiters+=1,new Promise((V,G)=>{let K=!1;function Z(Y){K||(K=!0,S.signal?.removeEventListener("abort",J),H.controller.signal.removeEventListener("abort",J),H.waiters-=1,H.waiters===0&&H.controller.abort(),Y())}function J(){Z(()=>G(Dt()))}S.signal?.addEventListener("abort",J,{once:!0}),H.controller.signal.addEventListener("abort",J,{once:!0}),H.promise.then(Y=>Z(()=>{try{I(S.signal??new AbortController().signal,E,L),V(C.clone(Y))}catch(ie){G(ie)}}),Y=>Z(()=>G(Y)))})}function A(S,E){if(E&&E!==_)return;const L=R=>S.every((x,z)=>R[z]===x);for(const[R,x]of k)L(x.entry.address.scopeIds)&&k.delete(R);for(const[R,x]of F)L(x.ids)&&(x.controller.abort(),F.delete(R));for(const[R,x]of j)L(x)&&R.abort()}function O(){if(!g){g=!0,k.clear();for(const S of j.keys())S.abort();j.clear();for(const S of F.values())S.controller.abort();F.clear(),s.delete(O),a.delete(A),o.get(_)?.cache===M&&o.delete(_)}}const M={read:T,invalidateScope:S=>h(S,_),dispose:O};return s.add(O),a.add(A),o.set(_,{definition:{namespace:_,codec:C,policy:N},sourceCodec:w.codec,cache:M}),M}return{createScope(w,v){if(c||!w)throw new Error("Invalid runtime cache scope");const N=Object.freeze({});return r.set(N,[...v?u(v):[],w]),N},register:y,invalidateScope:w=>h(w),dispose(){if(!c){c=!0;for(const w of[...s])w();o.clear(),n.clear(),i.clear()}}}}function kf(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 xf=".hb-runtime-cache-v1",Uf=1e3,Ri=64*1024,St=1e3,jf=2048,tr=32*1024*1024,zf=1024,on=new TextEncoder,Bs=new TextDecoder("utf-8",{fatal:!0});function rr(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Yr(e){const t=await globalThis.crypto.subtle.digest("SHA-256",on.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function ke(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Gs(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function Hf(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function Qs(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function Ff(e,t){const r=e.sandbox.directory(xf),n=r.directory("revisions"),i=r.directory("entries");for(const p of[r,n,i,i.directory("capability-check")])Qs(p,["directory","file","create","stat","list","remove"]),Qs(p.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(p){d=p,o.abort(),t.signal.removeEventListener("abort",s)}function f(p){if(Hf(p))throw u(p),p}function l(){if(d)throw d;if(a.signal.aborted)throw rr()}function h(p,T=a.signal){const A=c.then(()=>{if(T.aborted)throw d??rr();return l(),p()},()=>{if(T.aborted)throw d??rr();return l(),p()}).catch(E=>{throw f(E),E});if(c=A.catch(()=>{}),T.aborted)return Promise.reject(d??rr());let O=()=>{};const M=new Promise((E,L)=>{const R=()=>L(d??rr());T.addEventListener("abort",R,{once:!0}),O=()=>T.removeEventListener("abort",R)}),S=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},Uf);return Promise.race([A,M]).finally(()=>{clearTimeout(S),O()})}async function y(){l(),await n.create({recursive:!0,exclusive:!1},a),l(),await i.create({recursive:!0,exclusive:!1},a),l()}async function w(p,T){const A=n.file(`${await Yr([p,T??null])}.revision`);await N(A);let O=!1;try{await A.create({recursive:!1,exclusive:!0},a),O=!0}catch(E){f(E),l()}if(O){const E=Gs();return await A.write(on.encode(E),a),l(),E}const M=await A.stat(a);if(M.size<1||M.size>128)throw new Error("缓存 revision 文件损坏");const S=Bs.decode(await A.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(S))throw new Error("缓存 revision 文件损坏");return l(),S}async function v(p){const T=await p.list({limit:St},a);if(T.length>=St)throw new Error("缓存目录超过治理上限");return T}async function N(p){try{await p.stat(a);return}catch(A){if(!qr(A))throw A}if((await v(n)).length>=St-1)throw new Error("缓存 metadata 超过治理上限")}async function C(p,T){await y();const A=[];for(let O=0;O<p.length;O+=1){const M=p.slice(0,O+1);A.push(await w(M),await w(M,T))}return A}async function _(p){return r.directory(`entries/${await Yr([p.namespace,p.codecVersion,p.scopeIds])}`)}async function k(p){return(await _(p)).file(`${await Yr(p.key)}.cache`)}async function F(p,T){const A=await p.stat(a);if(A.size<5||A.size>T+Ri+4)throw new Error("缓存条目超过大小限制");const O=await p.read(a);if(l(),O.length!==A.size)throw new Error("缓存条目读取不完整");const M=new DataView(O.buffer,O.byteOffset,O.byteLength).getUint32(0);if(M<1||M>Ri||M+4>O.length)throw new Error("缓存信封损坏");const S=JSON.parse(Bs.decode(O.subarray(4,M+4))),E=O.slice(M+4);if(S.envelopeVersion!==1||!S.address||!Array.isArray(S.address.scopeIds)||!S.address.scopeIds.every(L=>typeof L=="string")||typeof S.address.namespace!="string"||typeof S.address.codecVersion!="string"||typeof S.address.key!="string"||!Array.isArray(S.revisions)||S.revisions.length!==S.address.scopeIds.length*2||!S.revisions.every(L=>typeof L=="string"&&L.length>0)||!Number.isSafeInteger(S.cachedAt)||!Number.isSafeInteger(S.expiresAt)||S.cachedAt<0||S.expiresAt<=S.cachedAt||S.payloadBytes!==E.length||E.length>T)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:S.address,revisions:S.revisions,cachedAt:S.cachedAt,expiresAt:S.expiresAt,payload:E}}async function j(p){if(!p.remove)throw new Error("Host 不支持缓存文件删除");await p.remove(a)}async function g(p){try{if((await p.file.stat(a)).size!==p.size)return!1;const T=await F(p.file,tr);return!ke(T.address,p.entry.address)||!ke(T.revisions,p.entry.revisions)||T.cachedAt!==p.entry.cachedAt||T.expiresAt!==p.entry.expiresAt||!ke(await I(T.payload),await I(p.entry.payload))?!1:(await j(p.file),!0)}catch(T){if(qr(T))return!0;throw T}}async function I(p){const T=await globalThis.crypto.subtle.digest("SHA-256",p);return Array.from(new Uint8Array(T),A=>A.toString(16).padStart(2,"0")).join("")}async function b(){const p=await v(n);let T=0;for(const S of p)if(S.kind==="file"&&(T+=(await S.stat(a)).size,T>tr))throw new Error("缓存扫描超过字节上限");const A=[];let O=0,M=T;for(const S of await v(i)){if(S.kind!=="directory")throw new Error("缓存目录结构损坏");for(const E of await v(S)){if(E.kind!=="file"||++O>jf)throw new Error("缓存文件超过治理上限");const L=(await E.stat(a)).size;if(M+=L,M>tr)throw new Error("缓存扫描超过字节上限");try{const R=await F(E,tr);A.push({file:E,entry:R,size:(await E.stat(a)).size,bucketName:S.name})}catch(R){f(R),l(),qr(R)||await j(E)}}}return{entries:A,metadataBytes:T}}async function D(){for(const p of await v(i))if(p.kind==="directory"&&p.remove&&(await v(p)).length===0)try{await p.remove({recursive:!1},a)}catch(T){f(T),l()}}function P(p){const{payload:T,...A}=p,O=on.encode(JSON.stringify({...A,payloadBytes:T.length}));if(O.length>Ri)throw new Error("缓存信封过大");const M=new Uint8Array(4+O.length+T.length);return new DataView(M.buffer).setUint32(0,O.length),M.set(O,4),M.set(T,O.length+4),M}return{readRevisions:(p,T)=>h(()=>C(p,T)),read:(p,T)=>h(async()=>{l();const A=await k(p);let O;try{O=await F(A,T)}catch(M){if(l(),qr(M))return;throw M}if(!(!ke(O.address,p)||O.expiresAt<=Date.now())&&ke(O.revisions,await C(p.scopeIds,p.namespace)))return O}),publish:(p,T)=>h(async()=>{l();const{address:A}=p;if(!ke(p.revisions,await C(A.scopeIds,A.namespace)))return!1;const O=P(p);if(p.payload.length>T.maxEntryBytes||O.length>T.diskMaxBytes||T.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await y();const M=await _(A),S=await k(A),E=await b(),L=[],R=new Map;for(const H of E.entries){if(H.bucketName===M.name&&H.file.name===S.name)continue;const V=JSON.stringify([H.entry.address.scopeIds,H.entry.address.namespace]);let G=R.get(V);if(G||(G=await C(H.entry.address.scopeIds,H.entry.address.namespace),R.set(V,G)),H.entry.expiresAt<=Date.now()||!ke(H.entry.revisions,G)){if(!await g(H))throw new Error("缓存治理期间条目已变化")}else L.push(H)}L.sort((H,V)=>H.entry.cachedAt-V.entry.cachedAt);function x(){const H=L.filter(V=>V.bucketName===M.name);return L.length+1>zf||O.length+E.metadataBytes+L.reduce((V,G)=>V+G.size,0)>tr||H.length+1>Math.min(T.diskMaxEntries,St-1)||O.length+H.reduce((V,G)=>V+G.size,0)>T.diskMaxBytes}for(;x();){const H=L.filter(K=>K.bucketName===M.name),G=H.length+1>Math.min(T.diskMaxEntries,St-1)||O.length+H.reduce((K,Z)=>K+Z.size,0)>T.diskMaxBytes?H[0]:L[0];if(!G||!await g(G))throw new Error("缓存容量不足或条目已变化");L.splice(L.indexOf(G),1)}await D();const z=await v(i);if(!z.some(H=>H.name===M.name)&&z.length>=St-1)throw new Error("缓存目录超过治理上限");if(await M.create({recursive:!0,exclusive:!1},a),!ke(p.revisions,await C(A.scopeIds,A.namespace)))return!1;try{await S.create({recursive:!1,exclusive:!0},a)}catch(H){f(H),await S.stat(a)}return await S.write(O,a),l(),ke(p.revisions,await C(A.scopeIds,A.namespace))}),invalidate:(p,T)=>h(async()=>{await y();const A=n.file(`${await Yr([p,T??null])}.revision`);await N(A);try{await A.create({recursive:!1,exclusive:!0},a)}catch(O){f(O),await A.stat(a)}await A.write(on.encode(Gs()),a),l();try{const{entries:O}=await b();for(const M of O){if(T!==void 0&&M.entry.address.namespace!==T||!p.every((E,L)=>M.entry.address.scopeIds[L]===E))continue;const S=await C(M.entry.address.scopeIds,M.entry.address.namespace);ke(M.entry.revisions,S)||await g(M)}await D()}catch(O){f(O),l()}})}}function qr(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const Vf="RATE_LIMITED_BY_RUNTIME",Bf="RATE_LIMITED",Ed=20,wd=40,Id=150,Ad=20,Md=1e4,Nd=45e3,Dd=1,Gf=300*1e3,Qf=64;function Tt(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Yf(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function qf(e={}){const t=e.now??Date.now,r=Yf(e.coalesceWindowMs,Id),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,Tt(e.budget?.ratePerSecond,Ed)),burst:Math.max(1,Math.floor(Tt(e.budget?.burst,wd)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(Tt(e.loopDetection?.maxCalls,Ad))),windowMs:Math.max(1,Math.floor(Tt(e.loopDetection?.windowMs,Md)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(Tt(e.circuitBreaker?.failureThreshold,Dd))),openMs:Math.max(1,Math.floor(Tt(e.circuitBreaker?.openMs,Nd)))},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(g){try{e.onReport?.(g)}catch{}}function y(g,I){if(!i)return{exceeded:!1,count:0};const b=a.get(g)??[],D=I-i.windowMs;let P=0;for(;P<b.length&&b[P]<=D;)P+=1;P>0&&b.splice(0,P);const p=b.length>=i.maxCalls;return p||(b.push(I),b.length>i.maxCalls+1&&b.splice(0,b.length-(i.maxCalls+1))),a.set(g,b),{exceeded:p,count:b.length}}function w(g){if(!n)return!0;const I=Math.max(0,g-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+I*n.ratePerSecond),u.updatedAt=g,u.tokens<1?!1:(u.tokens-=1,!0)}function v(g){if(!n)return 0;const I=Math.max(0,g-u.updatedAt)/1e3,b=Math.min(n.burst,u.tokens+I*n.ratePerSecond);return Math.max(0,Math.ceil((1-b)/n.ratePerSecond*1e3))}function N(g,I,b,D,P){if(!o)return;const p=d.get(I),T=(p?.open?0:p?.failures??0)+1;if(T<o.failureThreshold){d.set(I,{open:!1,openedAt:0,openMs:0,failures:T});return}const A=Math.min(Math.max(o.openMs,D),Gf);d.set(I,{open:!0,openedAt:P,openMs:A,failures:T}),f.circuitOpened+=1,h({type:"circuit_opened",capability:g,endpointId:I,status:b,openMs:A,timestamp:P})}function C(g){const I=d.get(g);I&&!I.open&&d.delete(g)}function _(g){for(const[I,b]of s)!b.pending&&b.expiresAt<=g&&s.delete(I);for(;s.size>=Qf;){const I=[...s].find(([,b])=>!b.pending);if(!I)break;s.delete(I[0])}}function k(g,I){if(g===void 0)return;const b=s.get(g);b?.promise===I&&(b.pending=!1)}function F(g,I){if(g===void 0)return;s.get(g)?.promise===I&&s.delete(g)}async function j(g){if(l)return g.load();const I=t();if(o){const p=d.get(g.endpointId);if(p?.open){const T=p.openedAt+p.openMs-I;if(T>0)throw f.circuitRejected+=1,h({type:"circuit_rejected",capability:g.capability,endpointId:g.endpointId,retryAfterMs:T,timestamp:I}),Kf("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:g.endpointId,retryAfterMs:T});d.delete(g.endpointId)}}const b=y(g.endpointId,I);b.exceeded&&i?c.has(g.endpointId)||(c.add(g.endpointId),h({type:"loop_detected",capability:g.capability,endpointId:g.endpointId,count:b.count,windowMs:i.windowMs,timestamp:I})):c.delete(g.endpointId);const D=r>0?g.coalesceKey:void 0;if(D!==void 0){const p=s.get(D);if(p&&(p.pending||p.expiresAt>I))return f.coalesced+=1,h({type:"coalesced",capability:g.capability,endpointId:g.endpointId,timestamp:I}),p.promise;p&&s.delete(D)}if(b.exceeded&&i)throw f.loopRejected+=1,Ys("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:g.capability,endpointId:g.endpointId,count:b.count,windowMs:i.windowMs});if(!w(I)){f.budgetRejected+=1;const p=v(I);throw h({type:"budget_exhausted",capability:g.capability,endpointId:g.endpointId,retryAfterMs:p,timestamp:I}),Ys("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:g.capability,endpointId:g.endpointId,retryAfterMs:p})}D!==void 0&&_(I);const P=g.load().then(p=>(k(D,P),C(g.endpointId),p),p=>{F(D,P);const T=$f(p);throw T!==void 0&&N(g.capability,g.endpointId,T,Wf(p),I),p});return D!==void 0&&s.set(D,{endpointId:g.endpointId,promise:P,expiresAt:I+r,pending:!0}),P}return{execute:j,invalidateCoalescing(g){if(g===void 0){s.clear();return}for(const[I,b]of s)g.includes(b.endpointId)&&s.delete(I)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,g])=>g.open).map(([g])=>g)}},dispose(){l||(l=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function $f(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 Wf(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 Ys(e,t){return{code:Vf,message:e,data:t}}function Kf(e,t){return{code:Bf,message:e,data:t}}const Sd=3e4,Td=6e4,Do=1440*60*1e3;function Zf(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??Sd)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??Td)):0,steamGameListTtlMs:t?Jf(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:Ed,burst:wd},coalesceWindowMs:r?.coalesceWindowMs??Id,loopDetection:r?.loopDetection??{maxCalls:Ad,windowMs:Md},circuitBreaker:r?.circuitBreaker??{failureThreshold:Dd,openMs:Nd}}}}function Jf(e){return e===void 0||!Number.isFinite(e)?Do:Math.max(0,Math.floor(e))}function Xf(e){return typeof e=="object"&&e!==null}function ae(e,t){const r=e.data;if(!Xf(r)||typeof r.status!="string")throw new Error(t);return r}const _d={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},eh={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 ae(e,"工坊小程序详情加载失败")}};function Ur(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function th(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function rh(e){const t=ae(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=th(r.consent_challenge)),{...t,result:n}}const nh={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=>({...Ur(e.runtimeContext),challenge:e.challenge}),parse:e=>ae(e,"小程序授权取消接口响应异常")},ih={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=>Ur(e.runtimeContext),parse:e=>ae(e,"小程序授权撤销接口响应异常")},oh={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=>Ur(e.runtimeContext),parse(e){const t=ae(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}:{}}}}},sh={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=>({...Ur(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>rh(e)},ah={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=>({...Ur(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=ae(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},ch=64;function bd(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??ch)),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 y=n();for(c(y),i.delete(f);i.size>=r;){const w=i.keys().next();if(w.done)break;i.delete(w.value)}i.set(f,{expiresAt:y+t,value:l})}function u(f,l){if(a)return l();if(t>0){const v=i.get(f);if(v&&v.expiresAt>n())return Promise.resolve(v.value);v&&i.delete(f)}const h=o.get(f);if(h)return h;const y=s,w=l().then(v=>(d(f,v,y),v)).finally(()=>{o.get(f)===w&&o.delete(f)});return o.set(f,w),w}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 dh(e,t){return t?e?"server":"local":"legacy"}function uh(e,t){if(e==="local")throw m("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const lh=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],fh=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),hh=/authorization|cookie|pkey|password|secret|token/i,Od=/authorization|cookie|pkey|token|password|secret/i;function xe(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function mh(e){for(const t of Object.keys(e))if(!fh.has(t))throw new le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of lh)if(Object.prototype.hasOwnProperty.call(e,t)&&xe(e,t)!==void 0)throw new le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(xe(e,"bodyEncoding")!==void 0&&xe(e,"bodyEncoding")!=="json"&&xe(e,"bodyEncoding")!=="form")throw new le("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(xe(e,"failurePresentation")!==void 0&&xe(e,"failurePresentation")!=="none")throw new le("endpoint failurePresentation 必须为 none");if(xe(e,"auth")!==void 0&&xe(e,"auth")!=="none"&&xe(e,"auth")!=="optional"&&xe(e,"auth")!=="required")throw new le("endpoint auth 必须为 none、optional 或 required")}function hr(e){if(Array.isArray(e))return e.map(hr);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))hh.test(n)||(r[n]=hr(i));return r}function qs(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Od.test(r)||(t[r]=n);return t}function gh(e){if(!e)return;const t=Object.keys(e).find(r=>Od.test(r));if(t)throw new le(`endpoint 禁止声明 credential-bearing header: ${t}`)}class jr 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 $s=1440*60*1e3,ph=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function yh(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,$s):void 0}if(!ph.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,$s):void 0}function Eh(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 vd(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class Bt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,vd(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class zr extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,vd(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function wh(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:hr(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:qs(o),method:e.method,metadata:{endpointId:e.id},query:hr(n),timeout:e.timeout,url:r},data:hr(a.data),headers:qs(a.headers)||{},status:a.status,statusText:a.statusText}}async function Mi(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(mh(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;gh(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 Bt({endpointId:t.id,cause:h})}if(f.status<200||f.status>=300)throw new jr({endpointId:t.id,status:f.status,responseData:f.data,retryAfterMs:yh(f.headers)});const l=wh(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(l,r)}catch(h){throw new zr({endpointId:t.id,cause:h})}return l.data},d=n.gate;if(!d)return c();const u=Eh(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const Ih=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),Ah=new Set(Vt),cs="steam_account",Cd=new Set(Vt.filter(e=>e!==cs)),Mh=1e3;function Nh(e){const t=new Set,r=bd({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??Sd))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??dh(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 m("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let E;try{E=await e.authorizationContext.get(e.operationContext)}catch(R){throw To(R)?Pi(R.code,R.message,R):Pi("REQUEST_FAILED","读取 Runtime auth context 失败",R)}if(E.steamAccount!==c||E.userDataMode!==d)throw m("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const L=E.token.trim();if(!L)throw m("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:L}}const h=e.account.onChange(E=>{if(y(),w("heybox_app_login_change",E?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),E&&e.account.getAccountKey){const L=i;F().then(R=>{!o&&i===L&&w("heybox_app_login_change",R)}).catch(()=>{})}});function y(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function w(E,L){E==="user_info_authorization_change"&&Oh(L)&&r.invalidate();for(const R of t)try{R(E,L)}catch{}}function v(){const E=e.identity.get()?.miniProgramId?.trim();if(!E)throw m("INVALID_STATE","当前能力缺少 canonical 小程序身份");return E}function N(){if(o||e.operationContext.signal.aborted)throw m("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function C(){N();let E;try{E=await e.account.getCurrentUserId(e.operationContext)}catch(L){throw Js(L,e.operationContext.signal,"读取小黑盒账号失败")}return typeof E=="string"&&E.trim()?E.trim():void 0}async function _(E,L){const R=await C();if(i!==L||R!==E)throw m("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function k(E,L,R=v()){if(!e.account.getAccountKey)throw m("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let x;try{x=await e.account.getAccountKey(R,E,e.operationContext)}catch{throw N(),m("REQUEST_FAILED","读取本地账号标识失败")}if(await _(E,L),v()!==R)throw m("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof x!="string"||!x.trim())throw m("INVALID_RESPONSE","Host 返回了无效的账号标识");return x}async function F(){const E=v(),L=i,R=await C();if(N(),i!==L)throw m("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return R?{isHeyboxAppLoggedIn:!0,accountKey:await k(R,L,E)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function j(E){N();try{await e.account.ensureAuthenticated({trustedUserGesture:E,reason:"runtime_auth",signal:e.operationContext.signal})}catch(R){throw Js(R,e.operationContext.signal,"小黑盒登录失败")}const L=await C();if(!L)throw m("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return L}async function g(E,L,R=e.operationContext.signal){try{if(R.aborted)throw So();return await bh(Mi(e.network,E,L,{...e.operationContext,credentials:"heybox-session",signal:R,...f?{gate:f}:{}}),R)}catch(x){throw e.operationContext.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):x instanceof le?m("REQUEST_UNSUPPORTED",x.message):x instanceof zr?m("INVALID_RESPONSE","授权接口响应不合法"):x instanceof Bt?m("REQUEST_FAILED","授权请求失败"):x instanceof jr?u&&(x.status===403||x.status===429)?m("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:x.status,...x.retryAfterMs===void 0?{}:{retryAfterMs:x.retryAfterMs}}):m("REQUEST_FAILED",x.message):To(x)?x:m("REQUEST_FAILED","授权请求失败")}}async function I(E,L){await g(nh,{runtimeContext:{miniProgramId:E,...await l()},challenge:L}).catch(()=>{})}function b(E){const L=async()=>{const x=Ks(e.operationContext.signal);a=x;try{return await E(x.signal)}finally{a===x&&(a=void 0),x.abort()}},R=s.then(L,L);return s=R.then(()=>{},()=>{}),R}async function D(E,L,R,x,z){if(!R)throw await I(E,L.challenge),m("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await I(E,L.challenge),m("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return b(async H=>{await _(x,z);const V=await P(E,L.displayedScopes,H);await _(x,z);let G;try{G=await e.authPresentation.confirmAuthorization({miniProgramId:E,scopes:L.displayedScopes,...V,signal:H})}catch(Z){throw e.operationContext.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await _(x,z),await I(E,L.challenge),Pi("REQUEST_FAILED","授权确认界面执行失败",Z))}if(await _(x,z),G.status!=="granted")throw await I(E,L.challenge),m("AUTHORIZATION_CANCELLED","用户取消授权");const K=Th(G.grantedScopes,L.displayedScopes,c);if(!K.includes("identity"))throw await I(E,L.challenge),m("AUTHORIZATION_CANCELLED","用户拒绝授权");return K})}async function P(E,L,R){const x=Ks(R),z=setTimeout(()=>x.abort(),Mh);try{const H=_h(e.miniProgramPresentation),[V,G]=await Promise.all([H?Promise.resolve(H):p(E,x.signal),L.includes("profile")?T(x.signal):Promise.resolve(void 0)]);return{...V?{miniProgram:V}:{},...G?{userProfile:G}:{}}}finally{clearTimeout(z),x.abort()}}async function p(E,L){try{const R=e.identity.get()?.version?.trim(),x=await g(eh,{mini_program_id:E,...R?{miniprogram_version:R}:{}},L),z=_t(x,"小程序公开资料"),H=Pt(z.name),V=Pt(z.icon_url);return H||V?{...H?{name:H}:{},...V?{avatarUrl:V}:{}}:void 0}catch{return}}async function T(E){try{const L=await g(_d,void 0,E),R=_t(L,"账号基础信息"),x=Pt(R.display_username),z=Pt(R.display_avatar);return x||z?{...x?{nickname:x}:{},...z?{avatar:z}:{}}:void 0}catch{return}}async function A(E,L){if(uh(d,"auth.login"),!c&&E.includes(cs))throw m("INVALID_PARAMS","auth.login 参数不合法");const R=v(),x=await j(L),z=i,H=await g(sh,{runtimeContext:{miniProgramId:R,...await l()},scopes:E});await _(x,z);const V=_t(H,"小程序登录"),G=Zs(V,"loginCode"),K=Zs(V,"consentChallenge");if(G===K)throw m("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let Z;if(G)Z=Ws(V.loginCode,c);else{const Y=Dh(V.consentChallenge,c),ie=await D(R,Y,L,x,z);await _(x,z);const Pe=await g(ah,{runtimeContext:{miniProgramId:R,...await l()},challenge:Y.challenge,selectedScopes:ie});if(await _(x,z),Z=Ws(_t(Pe,"小程序登录确认"),c),Z.scopes.some(ge=>!ie.includes(ge)))throw m("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const Y of Z.scopes)n.add(Y);r.invalidate();const J=e.account.getAccountKey?await k(x,z,R):void 0;return w("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...J===void 0?{}:{accountKey:J}}),w("user_info_authorization_change",ki(n,c)),{...Z,...J===void 0?{}:{accountKey:J}}}async function O(E,L){const R=i,x=await g(oh,{runtimeContext:{miniProgramId:L,...await l()}});await _(E,R);const z=Sh(_t(x,"用户本地身份"),c);for(const H of c?Vt:Cd)n.add(H);return w("user_info_authorization_change",ki(n,c)),z}function M(E){N();const L=v(),R=`${E}\0${L}\0${i}\0${c}`;return r.read(R,()=>O(E,L))}async function S(E){if(!E)throw m("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const L=v(),R=i,x=await C();if(!x)throw m("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const z=await g(ih,{runtimeContext:{miniProgramId:L,...await l()}});await _(x,R),_t(z,"用户授权撤销"),y(),w("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:F,login:A,async confirmGameSaves(E){if(!E)throw m("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw m("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const L=v(),R=await j(E),x=i;await b(async z=>{await _(R,x);const H=await P(L,["identity"],z),V=await e.authPresentation.confirmAuthorization({miniProgramId:L,scopes:["identity","game_saves"],...H,signal:z});if(await _(R,x),V.status!=="granted"||!V.grantedScopes.includes("game_saves")||!V.grantedScopes.includes("identity"))throw m("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:M,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>ki(n,c),revoke:S,onEvent(E){return t.add(E),()=>t.delete(E)},dispose(){o||(o=!0,y(),r.dispose(),h(),t.clear())}}}function Pi(e,t,r){const n=m(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function _t(e,t){if(!Q(e))throw m("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":Ih.has(r)?r:"REQUEST_FAILED";throw m(n,r)}if(!Q(e.result))throw m("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Ws(e,t){if(!Q(e))throw m("INVALID_RESPONSE","login code 必须是对象");const r=Jn(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 m("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function Dh(e,t){if(!Q(e))throw m("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Jn(e.requestedScopes,"challenge requestedScopes",t),n=Jn(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 m("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function Sh(e,t){if(!Q(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw m("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw m("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 Th(e,t,r){const n=Jn(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw m("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Pt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function _h(e){const t=Pt(e?.name),r=Pt(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Ks(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 bh(e,t){return t.aborted?Promise.reject(So()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(So()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function So(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Jn(e,t,r){const n=r?Ah:Cd;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw m("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function ki(e,t){const r=t?Vt:Vt.filter(n=>n!==cs);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function Zs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Oh(e){return Q(e)?Object.values(e).some(t=>t==="denied"):!1}function To(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Js(e,t,r){return t.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):To(e)?e:m("REQUEST_FAILED",r)}const vh=new Set(Vt);function Ch(e){return{[wn]:async t=>{if(t!==void 0)throw m("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[In]:async(t,r)=>e.authorization.login(Lh(t),r.trustedUserGesture)}}function Lh(e){if(e===void 0)return["identity"];if(!Q(e)||Object.keys(e).some(t=>t!=="scopes"))throw Xs();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!vh.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Xs();return[...e.scopes]}function Xs(){return m("INVALID_PARAMS","auth.login 参数不合法")}const Rh={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 ae(e,"排行榜记录删除接口响应异常")}},Ph={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 ae(e,"当前排行榜记录接口响应异常")}},kh={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 ae(e,"排行榜信息接口响应异常")}},xh={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 ae(e,"排行榜列表接口响应异常")}},Uh={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 ae(e,"排行榜提交接口响应异常")}},jh={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 ds(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await $(()=>Mi(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(ti(i)||dr(i,"REQUEST_UNSUPPORTED")||dr(i,"RATE_LIMITED")||dr(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof le)throw B("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof Bt&&dr(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof jr){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw B("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw B("UNAUTHORIZED","当前用户未登录");const o=zh(i.responseData);if(te(o)&&typeof o.status=="string"&&o.status!=="ok"){const s=te(o.result)?Ge(o.result.error_code):void 0;if(o.status==="login"||o.status==="relogin"||Xn(o.result)||Xn(o)||s&&/^[A-Z][A-Z0-9_]+$/.test(s))throw Ld(o,e.subject)}throw B("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof Bt?ei(e.subject):i instanceof zr?re(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):re(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function Fe(e,t,r){if(!te(e)||typeof e.status!="string")throw re(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Ld(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw re(`${t} 响应缺少 result`);return e.result}function us(e,t){try{return e.onChange(t)}catch(r){if(dr(r,hd))return()=>{};throw r}}function Ld(e,t){if(e.status==="login"||e.status==="relogin")throw B("UNAUTHORIZED",Ge(e.msg)||"当前用户未登录");if(te(e.result)){const i=Ge(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw B(i,Ge(e.result.message)||Ge(e.msg)||`${t}请求失败`)}const r=Xn(e.result)??Xn(e),n=Ge(r?.user_message)||Ge(e.msg)||Ge(r?.developer_message)||`${t}请求失败`;throw r?B(Hh(r),n,{status:e.status,sbe:r}):B("HEYBOX_API_ERROR",n,{status:e.status})}function zh(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function Xn(e){return te(e)&&te(e.sbe)?e.sbe:void 0}function Hh(e){const t=Ge(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 jh[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 te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function dr(e,t){return te(e)&&e.code===t}function B(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function re(e){return B("INVALID_RESPONSE",e)}function ei(e){return B("REQUEST_FAILED",`${e}请求失败`)}function ti(e){return e instanceof Error&&e.name==="AbortError"}const Fh="default",ot="排行榜",Vh=/^[A-Za-z0-9_-]{1,64}$/,Bh=300*1e3,Gh=250,Qh=3;class Yh{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=us(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(Uh,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=Fe(i,Qe,ot);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),xi(o,Qe)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=nr("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(xh,{miniProgramId:r,...t}),s=Fe(o,Oe,ot);if(!te(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw re(`${Oe} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw re(`${Oe} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>xi(a,Oe)),...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=nr("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(Ph,{miniProgramId:n,...t}),c=Fe(a,et,ot);if(!te(c))throw re(`${et} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:xi(c.entry,et)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Rh,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=Fe(i,yt,ot);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!te(o)||typeof o.deleted!="boolean")throw re(`${yt} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",nr("info"),async()=>{const i=await this.request(kh,{miniProgramId:r,...t}),o=Fe(i,He,ot);if(!te(o)||typeof o.key!="string"||!Vh.test(o.key))throw re(`${He} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw re(`${He} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw re(`${He} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw re(`${He} 返回的 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=nr(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>=Gh&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Bh,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>=Qh)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)ea(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){ea(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await $(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw ti(n)?n:ei(ot)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw B("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw B("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return nr(t,r??Fh)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw B("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return ds({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:ot,assertUsable:()=>this.assertUsable()},t,r)}dispose(){this.disposed||(this.disposed=!0,this.accountGeneration+=1,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.buckets.clear(),this.inflight.clear())}assertUsable(){if(X(this.options.operationContext.signal),this.disposed)throw B("INVALID_STATE","Cloud capability 已释放")}}function qh(e){return new Yh(e)}function xi(e,t){if(!te(e))throw re(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw re(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw re(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw re(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw re(`${t} 返回的 score 必须是有限数字`);if(!te(e.extra))throw re(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw re(`${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 ea(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function nr(...e){return JSON.stringify(e)}const $h={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 ae(e,"云端存储删除接口响应异常")}},ta={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 ae(e,"云端存储读取接口响应异常")}},ra={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 ae(e,"云端存储 key 列表接口响应异常")}},Wh={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 ae(e,"云端存储写入接口响应异常")}},st="云端存储",Kh=3e4,Zh=128,Jh=500;class Xh{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=us(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=Fe(await this.request(ra,{}),Et,st);if(this.assertAccountGeneration(t),!te(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw re("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"?Jh: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=Fe(await this.request($h,{key:t}),Ht,st);if(this.assertAccountGeneration(r.generation),!te(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw re("删除结果不合法");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 re("云存储版本超出安全整数范围");const o=Fe(await this.request(Wh,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),zt,st);if(this.assertAccountGeneration(r.generation),!te(o)||o.success!==!0)throw re("云存储写入结果不合法");const s=na({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw re("写入版本凭证不匹配");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(ta,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=na(Fe(c,jt,st));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>=Zh&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+Kh,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([ta.id,ra.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(B("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(B("UNAUTHORIZED","登录状态已变化,请重试")),this.options.requestGate?.invalidateCoalescing()}purge(t){this.accountGeneration+=1;for(const r of this.timers.values())clearTimeout(r);this.timers.clear();for(const r of[...this.unfinished])this.finish(r,t);this.queues.clear(),this.blockedKeys.clear(),this.cache.clear(),this.inflight.clear(),this.keyGenerations.clear(),this.boundScope=void 0,this.boundUserId=void 0}async requireCurrentUser(t){this.assertAccountGeneration(t);const r=this.readMiniProgramId();let n;try{n=await $(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw ti(o)?o:ei(st)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),B("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),B("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw B("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw B("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw B("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw B("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await $(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw ti(s)?s:ei(st)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw B("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return ds({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:st,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(X(this.options.operationContext.signal),this.disposed)throw B("INVALID_STATE","Cloud capability 已释放")}}function em(e){return new Xh(e)}function na(e){if(!te(e))throw re("云存储读取结果必须是对象");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 re("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw re("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const tm=/^[A-Za-z0-9_-]{1,64}$/,ia=20,rm=100,oa=2048,nm=/^[A-Za-z0-9_-]{1,128}$/,sa=16*1024;function im(e){const t=qh(e),r=em(e);return{handlers:{[Qe]:async i=>t.submit(om(i)),[Oe]:async i=>t.getList(sm(i)),[et]:async i=>t.getCurrentUserEntry(Ui(i,et)),[yt]:async i=>t.deleteCurrentUserEntry(Ui(i,yt)),[He]:async i=>t.getInfo(Ui(i,He)),[jt]:async i=>r.getItem(aa(i,jt)),[zt]:async i=>{const{key:o,value:s}=am(i);return r.setItem(o,s)},[Ht]:async i=>r.removeItem(aa(i,Ht)),[Et]:async i=>(dm(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function om(e){const t=Zt(e,Qe,!1);if(Jt(t,["key","score","extra"],Qe),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw Ee("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...ls(t.key,Qe),score:t.score,...t.extra===void 0?{}:{extra:um(t.extra)}}}function sm(e){if(e===void 0)return{limit:ia};const t=Zt(e,Oe,!0);Jt(t,["key","limit","cursor"],Oe);const r=t.limit===void 0?ia:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>rm)throw Ee("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw Ee("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...ls(t.key,Oe),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Ui(e,t){if(e===void 0)return{};const r=Zt(e,t,!0);return Jt(r,["key"],t),ls(r.key,t)}function aa(e,t){const r=Zt(e,t,!1);return Jt(r,["key"],t),Rd(r.key,t)}function am(e){const t=zt,r=Zt(e,t,!1);Jt(r,["key","value"],t);const n=Rd(r.key,t);if(typeof r.value!="string")throw Ee("INVALID_PARAMS",`${t} value 必须是字符串`);if(cm(r.value))throw Ee("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>sa)throw Ee("INVALID_PARAMS",`${t} value 不能超过 ${sa} 字节`);return{key:n,value:r.value}}function cm(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 dm(e){const t=Zt(e,Et,!0);Jt(t,[],Et)}function Rd(e,t){if(typeof e!="string"||!nm.test(e))throw Ee("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function Zt(e,t,r){if(e===void 0&&r)return{};if(!Pd(e))throw Ee("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Jt(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Ee("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function ls(e,t){if(e===void 0)return{};if(typeof e!="string"||!tm.test(e))throw Ee("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function um(e){if(!Pd(e))throw Ee("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw Ee("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw Ee("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>oa)throw Ee("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${oa} 字节`);return e}function Pd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ee(e,t){return{code:e,message:t}}const lm={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 ae(e,"游戏存档接口响应异常")}};function kd(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw m("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 m("FILE_IO_FAILED","无法生成安全文件标识")}}function xd(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):_o,remove:o?s=>e.remove(s):jd,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):_o,stat:s=>e.stat(s)})}function Ud(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=>xd(e.file(a),n,{allowRemove:o}),directory:a=>Ud(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):_o,remove:s?(a,c)=>e.remove(a,c):jd,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function _o(){return Promise.reject(m("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function jd(){return Promise.reject(m("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const fm=new Set(["METHOD_FORBIDDEN","FILE_PICKER_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_ENCODING_INVALID","DIRECTORY_LIST_LIMIT_EXCEEDED","DIRECTORY_NOT_EMPTY","FILE_IO_FAILED"]),hm={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 vr(e){const t=fs(e),r=t&&fm.has(t)?m(t,hm[t]??"文件操作失败"):m("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Be(e){try{return e()}catch(t){throw vr(t)}}function fs(e){try{if(!Q(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const ca=1024;class hs{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new hs(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 $r(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Be(()=>{if(!Array.isArray(t))throw m("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw m("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>ca)throw m("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw m("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>$r(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 ua(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Ft(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!Ft(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}resolveFileEntry(t){this.assertCanonicalDetail();const r=gm(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Cr(r.relativePath);ji(n.origin,i);const o=this.prepareFile(Be(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=pm(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==="."?".":Cr(r.relativePath);ji(n.origin,i);const o=this.prepareDirectory(i==="."?n.hostHandle:Be(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return fa(t),$r(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Be(()=>{if(!Array.isArray(r))throw m("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw m("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw m("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&Q(a)&&typeof a.name=="string"&&zd(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Be(()=>{if(Q(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return $r(n.handle,da(t.ref,n.handle.name))}if(Q(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return ua(n.handle,mm(t.ref,n.handle.name))}throw m("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Hr(r);ji(t.origin,n);const i=this.prepareFile(Be(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:da(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw m("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Be(()=>{fa(t);const i=n??t.mode;return la(t.mode,i),{handle:xd(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Be(()=>{Em(t,i);const o=n??t.mode;return la(t.mode,o),{handle:Ud(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>ca)throw m("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=kd();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw m("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!ym(t))throw m("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw m("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw m("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw De("files.sandbox");return this.prepareDirectory(Be(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw m("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw De("files")}}function Cr(e){if(!os(e))throw m("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function ji(e,t){if(e==="sandbox"&&zd(t))throw m("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function zd(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function Hr(e,t="文件名"){const r=Cr(e);if(r.includes("/"))throw m("INVALID_PARAMS",`${t} 只能是 basename`);return r}function da(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Cr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function mm(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Cr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function $r(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function ua(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function la(e,t){if(t==="readwrite"&&e!=="readwrite")throw m("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function gm(e){return Ft(e)||Hd(),e}function pm(e){return id(e)||Hd(),e}function Hd(){throw m("INVALID_PARAMS","文件引用不合法")}function ym(e){return/^[0-9a-f]{32}$/.test(e)}function fa(e){if(!Q(e)||e.kind!=="file"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.create!="function"||typeof e.read!="function"||typeof e.write!="function"||typeof e.stat!="function")throw m("FILE_IO_FAILED","Host 返回了无效 File handle");Hr(e.name,"Host File name")}function Em(e,t=!1){if(!Q(e)||e.kind!=="directory"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.file!="function"||typeof e.directory!="function"||typeof e.create!="function"||typeof e.stat!="function"||typeof e.list!="function")throw m("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw m("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&Hr(e.name,"Host Directory name")}const wm=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Im=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Am=new Set(["range","if-range","a-im"]),Mm=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"]),Nm=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Wr={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Dm{constructor(t){this.signal=t}phase="initial";transition(t){if(Wr[t]<=Wr[this.phase])throw m("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Wr[this.phase]<Wr.committed&&this.signal.aborted)throw Bd()}normalizeHostError(t,r){return this.throwIfCancelled(),gs(t,r,this.signal)}}async function Fd(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw De("network.download");const o=Ne(r.operationContext,t.signal),s=new Dm(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await bm(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=vm(c);Cm(c,u);const f=Lm(c.status,u);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw m("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const l=Om(e,a,u,i);let h=0;const y=Tm(f.expectedBytes,e.maxBytes);Hi(t,zi(0,f));const w={...o,onProgress(C){!Number.isSafeInteger(C)||C<h||y!==void 0&&C>y||(h=C,Hi(t,zi(h,f)))}};s.transition("transfer"),d=!0;let v;try{v=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}},w)}catch(C){throw s.normalizeHostError(C,"transfer")}s.transition("committed"),h=Sm(v,f,h,e.maxBytes),Hi(t,zi(h,f));const N=i.describeFile(l.handle,l.ref);return s.transition("completed"),N}finally{d||_m(n.network,c.body)}}function Sm(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 Tm(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function _m(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function bm(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return bo(i.handle.mode),await zm(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return bo(n.handle.mode),await Hm(n.handle,r),{kind:"directory",...n}}function Om(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Pm(e,r),o=n.deriveFile(t,i);return bo(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function vm(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 m("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!Q(e.headers))throw m("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!wm.has(r)||!Array.isArray(n)||n.length===0)throw m("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw m("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Cm(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw m("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:jm(t,Im)});if((t["content-range"]?.length??0)>0)throw m("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Lm(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw m("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw m("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw m("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=Rm(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 Rm(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function zi(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Hi(e,t){try{e.postProgress(t)}catch{}}function Pm(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=km(i);if(o&&sn(o))return o}for(const i of r){const o=xm(i);if(o&&sn(o))return o}if(e.suggestedName!==void 0)return ms(e.suggestedName);const n=Um(e.url);return n&&sn(n)?n:"download.bin"}function km(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 xm(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 Um(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function ms(e){try{Hr(e,"suggestedName")}catch{throw m("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!sn(e))throw m("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function sn(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Nm.test(e))}function jm(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function zm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Vd()}catch(r){throw gs(r,"file",t.signal)}}async function Hm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Vd()}catch(r){throw gs(r,"file",t.signal)}}function bo(e){if(e!=="readwrite")throw m("FILE_ACCESS_DENIED","下载目标只允许读取")}const Fm={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 gs(e,t,r){if(r.aborted)return Bd();const n=Vm(e);if(n&&Mm.has(n)){const o=m(n,Fm[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?m("DOWNLOAD_TIMEOUT","下载网络请求超时"):m("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?m("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):m("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function Vm(e){return Q(e)&&typeof e.code=="string"?e.code:void 0}function Vd(){return m("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Bd(){return m("DOWNLOAD_CANCELLED","下载已取消")}function Bm(e){if(!e)return;const t=Object.keys(e).find(r=>Am.has(r.trim().toLowerCase()));if(t)throw m("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}function Oo(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=>Oo(r,t+1)):te(e)&&Object.values(e).every(r=>Oo(r,t+1))}function Gm(e,t){const r=t==="2358720"?"blackMythWukong":t==="3678970"?"taskbarHero":t==="4115450"?"phantomBladeZero":void 0;if(!r)return{status:"unsupported"};const n={status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}};if(!te(e))return n;if(e.status==="unsupported")return{status:"unsupported"};if(e.game!==r)return n;if(e.status==="empty")return{status:"empty"};if(e.status==="failed"){if(["UNAUTHORIZED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED"].includes(String(e.error_code)))throw B(String(e.error_code),"账号或授权已变化");return n}return e.status!=="ready"||!te(e.data)||!Oo(e.data)?n:{status:"ready",data:e.data}}function Qm(e){const t=new Map,r=new Map,n=a=>`hb_runtime_game_save_sync_v1_${[a.miniProgramId,a.userId,a.gameId].map(encodeURIComponent).join(":")}`;async function i(a,c,d){const u=n(a),f=r.get(u)??Promise.resolve();let l;const h=new Promise(w=>{l=w}),y=f.then(()=>h);r.set(u,y);try{return await $(()=>f,c.signal),X(c.signal),await d()}finally{l(),r.get(u)===y&&y.then(()=>{r.get(u)===y&&r.delete(u)})}}async function o(a,c){const d=n(a);if(t.has(d))return t.get(d);if(e)try{const u=await $(()=>e.getRaw(d,c),c.signal);if(!u)return;const f=JSON.parse(u);if(!f||typeof f!="object")return;const l=f;return l.version!==1||l.miniProgramId!==a.miniProgramId||l.userId!==a.userId||l.gameId!==a.gameId||typeof l.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(l.accountId)||typeof l.taskId!="string"||!/^[1-9][0-9]{0,19}$/.test(l.taskId)?void 0:(t.set(d,l),l)}catch{X(c.signal);return}}async function s(a,c,d){X(d.signal);const u=n(a),f=c?{...a,version:1,taskId:c}:void 0;if(t.set(u,f),!!e)try{await $(()=>e.setRaw(u,f?JSON.stringify(f):"",d),d.signal)}catch{X(d.signal)}}return{run:i,async get(a,c){const d=await o(a,c);if(d&&d.accountId!==a.accountId){await s(a,void 0,c);return}return d?.taskId},set:s,async remove(a,c,d){await i(a,d,async()=>{const u=await o(a,d);u?.taskId===c&&u.accountId===a.accountId&&await s(a,void 0,d)})},clear(a){for(const c of t.values())c&&i(c,a,()=>s(c,void 0,a)).catch(()=>{})}}}const Fi=8*1024*1024,ha=32*1024*1024,Ym=2e3,qm=5*6e4;function $m(e){const t=Qm(e.storage);let r=0,n=!1,i,o=0;const s=new Set,a={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},c=g=>g.remove(a),d=new Set;let u=new AbortController,f;const l=()=>{u.abort(),u=new AbortController,f=void 0},h=(g=!0)=>{g&&t.clear(a),r++,l();for(const I of d)I.abort();for(const I of s)c(I).catch(()=>{});s.clear(),o=0},y=us(e.account,g=>{i&&g!==i&&(h(),i=void 0)}),w=e.authorization.onEvent(()=>h());function v(g,I,b,D){if(N(b),D.signal.aborted||!g.account_id||!e.presentation?.showSteamLoginRequired)return;const P=`${g.account_id}:${g.game_id}:${g.task_id??"sync"}`;if(f!==P){f=P;try{e.presentation.showSteamLoginRequired({userId:I,accountId:g.account_id},Ne(e.operationContext,u.signal))}catch{}}}function N(g){if(n||e.operationContext.signal.aborted)throw B("RUNTIME_DESTROYED","小程序已关闭");if(g!==r)throw B("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function C(g,I,b){if(N(I),await e.account.getCurrentUserId(b)!==g)throw h(),B("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");N(I)}async function _(g,I,b,D){if(await C(I,b,D),!e.authorizationContext)throw B("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const P=await e.authorizationContext.get(D);if(!P.token||P.expiresAt<=Date.now())throw B("UNAUTHORIZED","小程序运行上下文已过期");const p=await ds({network:e.network,operationContext:D,subject:"游戏存档",assertUsable:()=>N(b),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},lm,{...g,runtime_auth_context_token:P.token});if(await C(I,b,D),p.status==="failed"&&te(p.result)&&p.result.error_code==="RECENT_SAVE_AVAILABLE")throw B("RECENT_SAVE_AVAILABLE",typeof p.msg=="string"&&p.msg?p.msg:"已有近期存档,请直接查询使用");const T=Fe(p,g.action,"游戏存档");if(!te(T))throw B("INVALID_RESPONSE","存档响应不合法");return T}async function k(g,I,b){const D=Wm(g,I),P=r;if(N(P),g==="file"&&(!e.transfer||!e.files))throw B("METHOD_FORBIDDEN","宿主不支持存档文件读取");const p=new AbortController;d.add(p);let T=!1;const A=g==="sync"?setTimeout(()=>{T=!0,p.abort()},qm):void 0,O=Ne(Ne(e.operationContext,b.signal),p.signal);try{const M=await e.account.getCurrentUserId(O);if(!M)throw B("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==M)throw h(),B("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=M,g==="sync"||g==="parsed"){if(g==="sync"&&l(),!D.account_id){const G=await _({action:"check",game_id:D.game_id},M,P,O);D.account_id=Lr(G.account_id)}if(g==="sync")return await F(D,M,P,O)}const S=await _({action:g,...D},M,P,O);if(g==="list")return Km(S);if(g==="parsed")return Gm(S.parsed_data,D.game_id);const E=Gd(S.file);if(E.fileId!==D.file_id)throw B("INVALID_RESPONSE","文件标识不匹配");if(E.sizeBytes>Fi)throw B("FILE_TOO_LARGE","首期存档文件上限为 8 MiB");if(o+E.sizeBytes>ha)throw B("FILE_QUOTA_EXCEEDED","当前会话存档文件已达 32 MiB");const L={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:ct(S.download_url)},timeout:6e4};if(!sf(L)||new URL(ct(S.download_url)).pathname!=="/cloud_archive/"+D.file_id+".zip"||ri(S.expires_at)<=Date.now())throw B("INVALID_RESPONSE","存档下载地址无效");const R=".hb-game-saves/"+kd()+".zip",x=e.files.sandbox.file(R);if(!x.remove)throw B("METHOD_FORBIDDEN","宿主不支持存档临时文件清理");await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},O);const z=e.fileRegistry.createTransferScope();let H=!1,V=!1;try{await x.create({recursive:!0,exclusive:!0},O),V=!0;const G=z.registerFile(x,"game-save","readwrite");await Fd({request:L,url:new URL(ct(S.download_url)),to:G.ref,targetKind:"file",maxBytes:Fi},{...b,signal:O.signal,postProgress:()=>{}},{transfer:e.transfer,fileRegistry:z,operationContext:O}),await C(M,P,O);const K=await x.stat(O);if(K.size===void 0||!Number.isSafeInteger(K.size)||K.size<0||K.size>Fi)throw B("FILE_TOO_LARGE","存档文件超过 8 MiB");if(await C(M,P,O),o+K.size>ha)throw B("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达 32 MiB");if(O.signal.aborted)throw B("DOWNLOAD_CANCELLED","存档下载已取消");const Z=K.size,J=async ge=>{try{N(P),await _({action:"check",game_id:D.game_id,account_id:D.account_id},M,P,ge)}catch(he){throw te(he)&&["GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","UNAUTHORIZED"].includes(String(he.code))?(h(),B("FILE_ACCESS_REVOKED","游戏存档授权已失效")):he}},Y=async()=>{throw B("FILE_ACCESS_DENIED","存档文件只读")},ie={kind:"file",mode:"read",name:E.name,create:Y,write:Y,async read(ge){await J(ge);const he=await x.read(ge);try{if(await C(M,P,ge),!(he instanceof Uint8Array)||he.byteLength!==Z)throw B("INVALID_RESPONSE","存档文件长度不匹配");return he}catch(Li){throw he instanceof Uint8Array&&he.fill(0),Li}},async stat(ge){return await J(ge),{kind:"file",size:Z,modifiedAt:E.modifiedAt}}},Pe=e.fileRegistry.registerFile(ie,"game-save","read");return s.add(x),o+=Z,H=!0,Pe}finally{z.dispose(),V&&!H&&await c(x)}}catch(M){throw T?B("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):M}finally{A!==void 0&&clearTimeout(A),d.delete(p)}}async function F(g,I,b,D){const P=e.identity.get()?.miniProgramId;if(!P)throw B("INVALID_STATE","小程序身份尚未确认");const p={miniProgramId:P,userId:I,gameId:g.game_id,accountId:g.account_id},T=O=>_({action:"status",...g,task_id:O},I,b,D);let A;try{const O=await t.run(p,D,async()=>{await C(I,b,D);const S=await t.get(p,D);if(S){A=S;try{return{taskId:S,status:await T(S)}}catch(L){if(!te(L)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(L.code)))throw L;await t.set(p,void 0,D),A=void 0}}const E=await _({action:"sync",...g},I,b,D);return A=Lr(E.task_id),await t.set(p,A,D),await C(I,b,D),{taskId:A,status:void 0}});A=O.taskId;let M=O.status;for(;;){if(N(b),D.signal.aborted)throw B("REQUEST_CANCELLED","已停止等待存档同步");if(M??=await T(A),M.state==="succeeded"||M.state==="failed"){if(await t.remove(p,A,D),await C(I,b,D),M.state==="succeeded")return{state:"succeeded"};throw B(M.error_code?ct(M.error_code):"SYNC_FAILED",M.message?ct(M.message):"存档同步失败")}if(M.state!=="syncing"&&M.state!=="uploading")throw B("INVALID_RESPONSE","同步状态不合法");M=void 0,await Zm(Ym,D.signal)}}catch(O){if(te(O)){const M=String(O.code);M==="STEAM_LOGIN_REQUIRED"&&v({...g,task_id:A},I,b,D),A&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(M)&&await t.remove(p,A,a)}throw O}}return{handlers:{"gameSaves.list":(g,I)=>k("list",g,I),"gameSaves.sync":(g,I)=>k("sync",g,I),"gameSaves.readParsedData":(g,I)=>k("parsed",g,I),"gameSaves.getFile":(g,I)=>k("file",g,I)},allowsRead(g,I){return["file.readBytes","file.readText","file.stat","file.exists"].includes(g)&&te(I)&&e.fileRegistry.isGameSaveRef(I.target)},dispose(){n||(n=!0,h(!1),y(),w())}}}function Wm(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!te(t)||Object.keys(t).some(i=>!r.includes(i)))throw B("INVALID_PARAMS","存档参数不合法");const n=ur(t.gameId);if(Number(n)>2147483647)throw B("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:ur(t.accountId)}:{},...e==="file"?{save_id:ur(t.saveId),file_id:ur(t.fileId)}:{}}}function ur(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw B("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function Lr(e){try{return ur(e)}catch{throw B("INVALID_RESPONSE","服务端存档标识无效")}}function ct(e){if(typeof e!="string")throw B("INVALID_RESPONSE","服务端存档字段无效");return e}function ri(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw B("INVALID_RESPONSE","服务端存档数值无效");return e}function Gd(e){if(!te(e))throw B("INVALID_RESPONSE","存档文件信息无效");return{fileId:Lr(e.file_id),name:ct(e.name),originalPath:ct(e.original_path),sizeBytes:ri(e.size_bytes),modifiedAt:ri(e.modified_at)}}function Km(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw B("INVALID_RESPONSE","存档列表无效");return{accountId:Lr(e.account_id),saves:e.saves.map(t=>{if(!te(t)||!Array.isArray(t.files)||t.files.length>200)throw B("INVALID_RESPONSE","存档文件列表无效");return{saveId:Lr(t.save_id),createdAt:ri(t.created_at),files:t.files.map(Gd)}})}}function Zm(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(o),t.removeEventListener("abort",i),n(B("REQUEST_CANCELLED","已停止等待存档同步"))},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}const Jm=new Set(["stdio","attachments","notifications"]),Qd=new Set(["windows-x64","macos-arm64"]),Xm=new Set(["unsigned","valid","invalid","unknown"]),eg=/^[a-f0-9]{64}$/,tg=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),rg=new Set(ld),ng=new Set([...ld,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Yd=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 ig(e){const t=async(n,i,o,s)=>{const a=og(n);try{ze(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return ze(i.signal),c}catch(c){throw Co(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw m("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw m("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>sg(d,i)).catch(d=>{throw Co(d)});ze(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(ze(o.signal),c.status!=="granted")throw m("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[ui]:(n,i)=>t(n,i,async(o,s)=>vo(await e.companion.getInfo(o,s),o)),[li]:(n,i)=>t(n,i,async(o,s)=>ma(await e.companion.getPreparationStatus(o,s))),[fi]:(n,i)=>t(n,i,async(o,s)=>{const a=ma(await e.companion.getPreparationStatus(o,s));return ze(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),ze(i.signal),vo(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress($d(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[hi]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[mi]:(n,i)=>t(n,i,async(o,s)=>ga(await e.companion.getActiveSession(o,s),o)),[gi]:(n,i)=>t(n,i,async(o,s)=>{const a=ga(await e.companion.getActiveSession(o,s),o);return ze(i.signal),a||(await r("launch",o,i),ze(i.signal),Wd(await e.companion.launch(o,s),o))}),[pi]:(n,i)=>bt(n,i,e,"write"),[yi]:(n,i)=>bt(n,i,e,"closeStdin"),[Ei]:(n,i)=>bt(n,i,e,"terminate"),[wi]:(n,i)=>bt(n,i,e,"ackOutput"),[Ii]:async(n,i)=>{const o=await bt(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Ai]:(n,i)=>bt(n,i,e,"showNotification")}}function og(e){if(!Q(e)||typeof e.alias!="string"||!ql.test(e.alias))throw m("INVALID_PARAMS","Companion alias 不合法");return e.alias}function ze(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function bt(e,t,r,n){if(!Q(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw m("INVALID_PARAMS","Companion Session controller 不合法");try{ze(t.signal);const i=await r.companion[n](ag(e,n),{...r.operationContext,signal:t.signal});return ze(t.signal),i}catch(i){throw Co(i)}}function Le(){throw m("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function qd(e){return!Array.isArray(e)||e.some(t=>!Jm.has(t))?Le():Object.freeze([...new Set(e)])}function vo(e,t){return!Q(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Qd.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!Xm.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?Le():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:qd(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function sg(e,t){const r=vo(e,t);return!Q(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!eg.test(e.sha256)?Le():Object.freeze({...r,sha256:e.sha256})}function $d(e){return Q(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):Le():Le()}function ma(e){return Q(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:$d(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&Q(e.error)&&typeof e.error.code=="string"&&rg.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:Yd[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):Le():Le()}function Wd(e,t){return!Q(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Qd.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?Le():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:qd(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function ga(e,t){return e===void 0?void 0:Wd(e,t)}function ag(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!ad(r.data))throw m("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 m("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw m("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw m("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function cg(e){return!Q(e)||!tg.has(String(e.reason))?Le():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):Le():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?Le():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function dg(e){if(!Q(e)||!Q(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,r=t.sessionId;if(e.type==="companion.session.output")return!Number.isSafeInteger(t.controllerGeneration)||Number(t.controllerGeneration)<0||t.stream!=="stdout"&&t.stream!=="stderr"||!Number.isSafeInteger(t.sequence)||Number(t.sequence)<0||!ad(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:cg(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 Co(e,t){return Q(e)&&typeof e.code=="string"&&ng.has(e.code)?m(e.code,Yd[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&Q(e)&&e.name==="AbortError"?m(t,"Companion 准备已取消"):m("COMPANION_HOST_FAILED","Companion Host 操作失败")}const pa=5e3,ya=1e4;function pe(e){throw{code:"INVALID_PARAMS",message:e}}function ps(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kd(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&pe(`${r} 不支持字段: ${n.join(", ")}`)}function ug(e){if(e===void 0)return{intensity:"light",delay:0};if(!ps(e))return pe("device.vibrate 参数必须是对象");Kd(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return pe("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>pa?pe(`device.vibrate delay 必须是 0-${pa} 的整数毫秒`):{intensity:r,delay:n}}function lg(e){return ps(e)?(Kd(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?pe("device.setClipboard text 必须是非空字符串"):e.text.length>ya?pe(`device.setClipboard text 不能超过 ${ya} 字符`):{text:e.text}):pe("device.setClipboard 参数必须是对象")}function fg(e){return typeof e=="string"?e.trim()?e:pe("device.executeProtocol 协议字符串不能为空"):ps(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?pe("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(Lo(e,new Set),e):pe("device.executeProtocol 参数必须是协议字符串或协议对象")}function Lo(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||pe("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":pe("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":pe(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&pe("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)Lo(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&pe("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))Lo(i,t);t.delete(r)}function hg(e){return{[Yn]:async t=>{X(e.operationContext.signal),await $(()=>e.presentation.vibrate(ug(t),e.operationContext),e.operationContext.signal)},[qn]:async t=>{X(e.operationContext.signal),await $(()=>e.presentation.setClipboard(lg(t),e.operationContext),e.operationContext.signal)},[$n]:async(t,r)=>{const n=Ne(e.operationContext,r.signal);X(n.signal);const i=fg(t);await $(()=>e.protocol.invoke(i,n),n.signal)}}}const Ea=1e3,mg=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function gg(e){const t=r=>Ne(e.operationContext,r.signal);return{files:{[Pn]:async(r,n)=>{Vi(n);const i=Bi(e.picker),o=pg(r),s=await Ie(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[kn]:async(r,n)=>{Vi(n);const i=Bi(e.picker),o=yg(r),s=await Ie(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[xn]:async(r,n)=>{Vi(n);const i=Bi(e.picker),o=Eg(r).suggestedName,s=t(n);if(!i.saveFile)throw De("files.saveFile");const a=await Ie(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[Mr]:async(r,n)=>{const i=Me(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);Ot(o.mode),await Ie(()=>o.create(wa(i),t(n)))},[Nr]:async(r,n)=>{const i=Me(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),Ot(o.handle.mode),!o.handle.remove)throw De(Nr);await Ie(()=>o.handle.remove(t(n)))},[Un]:async(r,n)=>{const i=Me(r);return Ia(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!Q(o)||o.kind!=="file")throw Ma()})},[Dr]:async(r,n)=>{const i=Me(r),o=Aa(await Ie(()=>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 m("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[jn]:async(r,n)=>{const i=Me(r,["content"]);typeof i.content!="string"&&_e("content 必须是字符串");const o=e.registry.resolveFile(i.target);Ot(o.mode),await Ie(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[Sr]:async(r,n)=>{const i=Me(r),o=await Ie(()=>e.registry.resolveFile(i.target).read(t(n)));return Aa(o)},[zn]:async(r,n)=>{const i=Me(r,["content"]),o=e.registry.resolveFile(i.target);Ot(o.mode),await Ie(()=>o.write(Ig(i.content),t(n)))},[Tr]:async(r,n)=>{const i=Me(r),o=await Ie(()=>e.registry.resolveFile(i.target).stat(t(n)));return Ag(o)}},directory:{[Hn]:async(r,n)=>{const i=Me(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);Ot(o.mode),await Ie(()=>o.create(wa(i),t(n)))},[_r]:async(r,n)=>{const i=Me(r,["recursive"]);if(Q(i.target)&&i.target.relativePath===".")throw m("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),Ot(o.handle.mode),!o.handle.remove)throw De(_r);await Ie(()=>o.handle.remove({recursive:i.recursive===void 0?!1:ni(i.recursive,"recursive")},t(n)))},[Fn]:async(r,n)=>{const i=Me(r);return Ia(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!Q(o)||o.kind!=="directory")throw Ma()})},[Vn]:async(r,n)=>{const i=Me(r,["limit"]),o=wg(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await Ie(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function pg(e){if(e===void 0)return{mode:"read",multiple:!1};Q(e)||_e("pickFiles 参数必须是对象"),Ni(e,["mode","accept","multiple"]);const t=Zd(e.mode,"read"),r=e.multiple===void 0?!1:ni(e.multiple,"multiple");let n;return e.accept!==void 0&&((!Array.isArray(e.accept)||e.accept.some(i=>typeof i!="string"||!/^\.[a-z0-9][a-z0-9._-]*$/i.test(i)))&&_e("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function yg(e){return e===void 0?{mode:"read"}:(Q(e)||_e("pickDirectory 参数必须是对象"),Ni(e,["mode"]),{mode:Zd(e.mode,"read")})}function Eg(e){return Q(e)||_e("saveFile 参数必须是对象"),Ni(e,["suggestedName"]),{suggestedName:Hr(e.suggestedName,"suggestedName")}}function Me(e,t=[]){return(!Q(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&_e("文件操作参数必须包含 target"),Ni(e,["target",...t]),e}function wa(e){return{recursive:e.recursive===void 0?!1:ni(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:ni(e.exclusive,"exclusive")}}function Zd(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&_e("mode 必须是 read 或 readwrite"),e)}function ni(e,t){return typeof e!="boolean"&&_e(`${t} 必须是布尔值`),e}function wg(e){if(e===void 0)return Ea;if((!Number.isSafeInteger(e)||e<=0)&&_e("limit 必须是正整数"),e>Ea)throw m("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Ni(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&_e(`不支持字段: ${r.join(", ")}`)}function Ot(e){if(e!=="readwrite")throw m("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Vi(e){if(!e.trustedUserGesture)throw m("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Bi(e){if(!e)throw De("files.external");return e}async function Ia(e){try{return await e(),!0}catch(t){if(mg.has(fs(t)??""))return!1;throw vr(t)}}async function Ie(e){try{return await e()}catch(t){throw vr(t)}}function Ig(e){return e instanceof Uint8Array||_e("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&_e("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Aa(e){if(!(e instanceof Uint8Array))throw m("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Ma(){return m("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Ag(e){if(!Q(e)||e.kind!=="file"||!Mg(e.size))throw m("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Ng(e[t]))throw m("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 Mg(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ng(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function _e(e){throw m("INVALID_PARAMS",e)}const Dg=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),Gi={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function Sg(e){if(e instanceof le)return m("REQUEST_UNSUPPORTED",Gi.REQUEST_UNSUPPORTED);const t=Jd(e);return t!==void 0&&Dg.has(t)?m(t,Gi[t]??"媒体操作失败"):m("MEDIA_PREPARE_FAILED",Gi.MEDIA_PREPARE_FAILED)}function Jd(e){try{if(!Q(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Tg=["source","mediaType","maxCount"],an=Object.freeze({source:"album",mediaType:"all",maxCount:1});function _g(e){if(e===void 0)return an;if(!Pl(e))throw m("INVALID_PARAMS",Og(e));return bg(e)}function bg(e){return Object.freeze({source:e.source??an.source,mediaType:e.mediaType??an.mediaType,maxCount:e.maxCount??an.maxCount})}function Og(e){if(!Q(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!Tg.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 vg=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),Cg={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class Lg{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=Rg(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>kg(s,i[a]));if(!kl(o))throw Ve("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(xg).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=Jd(n);throw i!==void 0&&vg.has(i)?n:Ve("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function Na(e,t){if(e.signal.aborted)throw m("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw m("REQUEST_CANCELLED","media.pick 已取消")}function Rg(e,t){if(!Array.isArray(e))throw Ve("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw Ve("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw Ve("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw Ve("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw Ve("Host 返回了稀疏媒体结果");Pg(e[n],n)}return e}function Pg(e,t){if(!Q(e))throw Ve(`第 ${t+1} 项不是对象`);if(!sd({...e,file:Cg}))throw Ve(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!Q(e.file))throw Ve(`第 ${t+1} 项缺少文件句柄`)}function kg(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 xg(e){return"handleId"in e.ref?e.ref.handleId:void 0}function Ve(e){return m("MEDIA_PREPARE_FAILED",e)}function Ug(e){const t=e.media?new Lg(e.registry,e.media,e.operationContext):void 0;return{handlers:{[br]:async(n,i)=>{const o=_g(n);zg(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw De(br);const c=Ne(e.operationContext,i.signal);Na(e.operationContext,i.signal);const d=await jg(s,o,c,e.operationContext,i.signal);Na(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function jg(e,t,r,n,i){try{return await $(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?m("REQUEST_CANCELLED","media.pick 已取消"):Sg(o)}}function zg(e){if(!e.trustedUserGesture)throw m("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Kr=4294967296;function Hg(e){const t=new Fg;return t.write(e),t.finish()}class Fg{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<Kr?(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=Vg(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<Kr)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/Kr),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Kr)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Vg(e){const t=new Uint8Array(Bg(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 Bg(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 Xd(e){Ro(e);const t=Hg(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 Ro(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)Ro(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");Ro(s,t+1,r)}r.delete(e)}const Gg=["pc","console","mobile"],Qg=["game","wiki"];function ii(e){throw{code:"INVALID_PARAMS",message:e}}function Yg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rt(e,t){return typeof e!="string"||!e.trim()?ii(t):e.trim()}function Da(e,t,r){return typeof e!="string"||!t.includes(e)?ii(r):e}function qg(e){const t={target:"game_detail",appId:rt(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Da(e.gameType,Gg,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Da(e.page,Qg,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=rt(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=rt(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function $g(e){return{target:"user_detail",userId:rt(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Wg(e){const t={target:"post_detail",linkId:rt(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=rt(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=rt(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Kg(e){const t={target:"mini_program",miniProgramId:rt(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Zg(e){return Yg(e)?e.target==="game_detail"?qg(e):e.target==="user_detail"?$g(e):e.target==="post_detail"?Wg(e):e.target==="mini_program"?Kg(e):ii("navigation.openAppPage target 不支持"):ii("navigation.openAppPage options 必须是对象")}function Jg(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 Xg(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function ep(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 tp(e){const t=e;return t.target==="game_detail"?Jg(t):t.target==="user_detail"?Xg(t):ep(t)}const rp="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",np="data-hb-sdk-fullscreen-exit",ip=3e3,op=2e3,Sa="var(--white-70a,rgba(255,255,255,.7))",Ta="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function sp(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(np,""),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 ${Sa}`,`box-shadow:${Ta}`,"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=rp,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(v=op){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")},v)}function y(){l(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Sa,t.style.boxShadow=Ta,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),h()}async function w(){if(!(s||a)){if(!o){y();return}a=!0,clearTimeout(c),l();try{await e()}catch{}finally{a=!1,s||y()}}}return t.addEventListener("click",w),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(ip),{dispose(){s=!0,clearTimeout(c),l(),t.removeEventListener("click",w),window.removeEventListener("resize",f),t.remove()}}}const eu=1e4;function tu(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()},eu);return{signal:r.signal,async run(s){try{return await $(s,r.signal)}catch(a){throw n??a}},dispose(){clearTimeout(o),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function _a(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 Qi(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function ir(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function ap(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(y){if(!y.hideCapsule){c();return}a??=sp(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",c,{once:!0});function u(y,w){if(n===y){if(n=void 0,clearTimeout(y.timer),e.operationContext.signal.removeEventListener("abort",f),"error"in w)y.controller.abort();else if(i={options:y.options,result:w.result},o=y.options,d(y.options),e.onApplied?.(y.options),w.result.supported&&!Qi(s,y.options)){s={...y.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:y.source})}catch{}}for(const v of y.subscribers)v.dispose(),"error"in w?v.reject(w.error):v.resolve(w.result);y.subscribers.clear()}}function f(){n&&u(n,{error:ir()})}function l(y,w){return new Promise((v,N)=>{const C=()=>{y.subscribers.delete(_),_.dispose(),N(ir()),y.subscribers.size===0&&u(y,{error:ir()})},_={resolve:v,reject:N,dispose:()=>w?.removeEventListener("abort",C)};y.subscribers.add(_),w?.addEventListener("abort",C,{once:!0}),w?.aborted&&C()})}const h={async runDisplayRequest(y,w,v){const N=++t,C=tu(w,e.operationContext.signal);try{return await C.run(async()=>{if(await v(C.signal),C.signal.aborted)throw ir();if(_a(y),N<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=N,h.apply(y,C.signal)})}finally{C.dispose()}},async apply(y,w,v="api"){if(X(e.operationContext.signal),w?.aborted)throw ir();const N=_a(y),C=n?.options??o,_={mode:N.orientation??C.mode,hideCapsule:N.fullscreen??C.hideCapsule};_.mode==="landscape"&&(_.hideCapsule=!0);const k=e.presentation.applyOrientation;if(!k)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&Qi(n.options,_))return l(n,w);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&Qi(i.options,_))return i.result;i=void 0;const F={options:_,source:v,controller:new AbortController,subscribers:new Set};n=F;const j=l(F,w);return e.operationContext.signal.addEventListener("abort",f,{once:!0}),w||(F.timer=setTimeout(()=>{u(F,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},eu)),$(()=>k.call(e.presentation,_,{...e.operationContext,signal:F.controller.signal}),F.controller.signal).then(g=>u(F,{result:g??{supported:!0}}),g=>u(F,{error:g})),j},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return h}function ru(e){throw{code:"INVALID_PARAMS",message:e}}function ba(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&ru(`${t} 不支持参数`)}function cp(e){return{[Wn]:async t=>{X(e.operationContext.signal),ba(t,"navigation.close"),await $(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Kn]:async t=>{X(e.operationContext.signal),ba(t,"navigation.reload"),await $(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[Zn]:async(t,r)=>{const n=Ne(e.operationContext,r?.signal);X(n.signal);const i=Zg(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Xd(i.extra)}catch{ru("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=tu(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}X(n.signal),await $(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await $(()=>e.presentation.openAppPage(tp(i),n),n.signal)}}}const Oa={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function dp(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw De("network.upload");const o=Ne(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw m("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(l){throw s(),vr(l)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw m("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw m("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,y=await n.upload(a,{...h,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:f});if(u=!0,!Number.isSafeInteger(y.uploadedBytes)||y.uploadedBytes<d||y.uploadedBytes>c.size)throw m("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(y.status>=200&&y.status<300&&y.uploadedBytes!==c.size)throw m("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:y.uploadedBytes,total:c.size,lengthComputable:!0}),y}catch(l){u=!0;const h=fs(l);throw h&&Oa[h]?m(h,Oa[h]):o.signal.aborted?m("UPLOAD_CANCELLED","上传已取消"):h?.startsWith("FILE_")||h?.startsWith("DIRECTORY_")?vr(l):m("UPLOAD_NETWORK_FAILED","上传网络失败")}}const ys="withCredentials",up=new Set(["url","method","params","data","headers","timeout",ys]),lp=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",ys]),fp=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),va=3e4,Po=2*1024*1024,hp=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,nu=/[\u0000-\u0008\u000A-\u001F\u007F]/,mp=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,gp="network.request 不支持 multipart/form-data,请使用专用上传能力";function pp(e){const t=yp(e.runtimePermissions),r=Cp(e.allowedHttpOrigins);return{[Rn]:async(n,i)=>{const o=wp(n,{permission:t,allowedHttpOrigins:r}),s=await dp(o,i,e),{uploadedBytes:a,...c}=s;return La(c)},[Ln]:async(n,i)=>{const o=Ip(n,{permission:t,allowedHttpOrigins:r});return Fd(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Cn]:async(n,i)=>{const o=Ne(e.operationContext,i?.signal);X(o.signal);const s=Ep(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await $(()=>e.network.request(s,o),o.signal)}catch(c){throw Rp(c)?c:Pp(c,"REQUEST_UNSUPPORTED")?q("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):q("REQUEST_FAILED","网络请求失败")}return La(a)}}}function yp(e){const t=Ce(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Ep(e,t){const r=Gt(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!up.has(c));if(n.length>0)throw q("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);iu(r,"network.request");const i=Es(r,t,"network.request"),o=Mp(r.method),s=r.data;s!==void 0&&Sp(s),_p(i.headers,s);const a=bp(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 wp(e,t){const r=Gt(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 q("INVALID_PARAMS","network.upload 包含不支持的字段");const i=Es(r,t,"network.upload");if(i.official)throw q("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw q("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!Ft(r.from))throw q("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw q("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw q("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw q("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 q("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(u=>u.toLowerCase()==="content-type"))throw q("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=Ca(r.fieldName),c=r.fields===void 0?void 0:Gt(r.fields,"fields 必须是字符串字典");for(const[u,f]of Object.entries(c??{}))if(Ca(u),typeof f!="string"||u===a)throw q("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw q("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||nu.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw q("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>Po)throw q("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:ms(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function Ca(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw q("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function Ip(e,t){const r=Gt(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!lp.has(c));if(n.length>0)throw q("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);iu(r,"network.download");const i=Es(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw q("INVALID_PARAMS","network.download timeout 必须是有限正数");Bm(i.headers);const o=Ft(r.to),s=id(r.to);if(!o&&!s)throw q("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw q("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw q("INVALID_PARAMS","suggestedName 必须是字符串");a=ms(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw q("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw q("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 Es(e,t,r){const n=Ap(e.url,t.allowedHttpOrigins,r),i=Cf(n);if(i&&!t.permission.useOfficialDomain)throw q("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(vf(n.pathname,i))throw q("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Gt(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Np(e.headers,r),timeout:Dp(e.timeout,r)}}function Ap(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw q("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw q("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Mp(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw q("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!fp.has(t))throw q("INVALID_PARAMS","network.request method 不合法");return t}function Np(e,t="network.request"){const r=Gt(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!hp.test(s)||typeof o!="string"||nu.test(o))throw q("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Lf(s))throw q("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function iu(e,t){const r=e[ys];if(r!==void 0&&typeof r!="boolean")throw q("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Dp(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw q("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>va)throw q("INVALID_PARAMS",`${t} timeout 不能超过 ${va}ms`);return e}}function Sp(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw q("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Tp(e)>Po)throw q("INVALID_PARAMS",`network.request data 不能超过 ${Po} 字节`)}function Tp(e){if(typeof e=="string")return Yi(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return Yi(e.toString());try{const t=JSON.stringify(e);return t?Yi(t):0}catch{throw q("INVALID_PARAMS","network.request data 必须可序列化")}}function _p(e,t){const r=ou(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 q("INVALID_PARAMS",gp)}function bp(e,t,r){if(t===void 0)return;const n=ou(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)||vp(t))?"form":Op(t)?"json":void 0}function ou(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function Op(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function vp(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Cp(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&&Lp(n.hostname)&&t.add(n.origin)}catch{}return t}function Lp(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 La(e){return Object.keys(e.headers).some(Ra)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Ra(t)))}:e}function Ra(e){const t=e.trim().toLowerCase();return mp.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Rp(e){return e instanceof Error&&e.name==="AbortError"}function Pp(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Gt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw q("INVALID_PARAMS",t);return e}function Yi(e){return new TextEncoder().encode(e).length}function q(e,t){return{code:e,message:t}}function kp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xp(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 Up(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=xp(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function jp(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 su(e,t){if(e==null)return{};if(!kp(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=Up(e.topicIds),n=jp(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 zp(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function Hp(e){try{if(zp(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function fe(e){throw{code:"INVALID_PARAMS",message:e}}function Fr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ko(e,t){return typeof e!="string"||!e.trim()?fe(t):e}function Fp(e,t){const r=ko(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?fe(t):r}catch{return fe(t)}}function Vp(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function au(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return fe(`${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 fe(`${t} 缺少有效的小程序分享地址`)}}function Bp(e,t){if(!Fr(e))return fe("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return fe("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!Vp(r))return fe("share.showShareMenu channel 不合法");const n=cu(e.extra,"share.showShareMenu");return{title:ko(e.title,"share.showShareMenu title 必须是非空字符串"),description:ko(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:au(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:Fp(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function cu(e,t){if(e!==void 0)try{return Xd(e)}catch{return fe(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function du(e,t){return e.invalidMessage&&await $(()=>Hp(t.environment),t.operationContext.signal)?fe(e.invalidMessage):e.post}function Pa(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Gp(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Pa(t.windowWidth,0),height:Pa(t.windowHeight,0)}}function xo(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?fe(t):r}function ka(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?fe(t):r}function Qp(e){return Fr(e)?{left:xo(e.left,"share.screenshot rect.left 必须是非负数字"),top:xo(e.top,"share.screenshot rect.top 必须是非负数字"),width:ka(e.width,"share.screenshot rect.width 必须是正数"),height:ka(e.height,"share.screenshot rect.height 必须是正数")}:fe("share.screenshot rect 必须是对象")}function Yp(e,t){if(e!=null&&!Fr(e))return fe("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?fe("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?fe("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?Gp(t):Qp(r.rect),...r.delay===void 0?{}:{delay:xo(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function qp(e,t){X(t.operationContext.signal);const r=Bp(e,t);let n=su(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await du(n,t);return $(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function $p(e,t){if(X(t.operationContext.signal),e!==void 0&&!Fr(e))return fe("share.copyLink 参数必须是对象");const r=cu(e?.extra,"share.copyLink"),n=au(t,"share.copyLink",r);return await $(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Wp(e,t,r){X(t.operationContext.signal);const n=su(Fr(e)?e.post:void 0,{method:"share.screenshot"}),i=await du(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=Kp(),{watermarkTheme:a,...c}=r;let d=!1,u,f;try{d=!0,await $(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),u=await t.prepareScreenshot?.(r.rect,t.operationContext.signal,a),f={status:"fulfilled",value:await $(()=>t.presentation.captureAndShare({...c,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(h){f={status:"rejected",error:h}}finally{u?.()}const l=d?await Zp(t.presentation,s,t.operationContext.signal):void 0;if(f.status==="rejected")throw f.error;if(l)throw l;return f.value}function Kp(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Zp(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await $(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function Jp(e){let t=Promise.resolve();return{[Tn]:(r,n)=>$p(r,e),[_n]:(r,n)=>qp(r,e),[bn]:async(r,n)=>{const i=Ne(e.operationContext,n.signal);X(i.signal);const o=Yp(r,e.presentation),s=t.then(()=>Wp(r,{...e,operationContext:i},o));return t=s.then(()=>{},()=>{}),$(()=>s,i.signal)}}}const xa=new WeakMap;function uu(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return cf(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${md(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function lu(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=xa.get(t);f||(f=new Map,xa.set(t,f));const l=f.get(u)??Promise.resolve(),h=async()=>(X(c.signal,{preserveReason:!0}),d(u)),y=l.catch(()=>{}).then(()=>e.lock?e.lock(u,h):h());f.set(u,y);try{return await y}finally{f.get(u)===y&&f.delete(u)}},o=async(c,d,u=!1)=>{const f=Nt(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(y=>y.key.startsWith(f)&&y.value!=="").map(y=>y.key.slice(f.length)))];const l=await e.storage.getRaw(Qr(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>ks||h.some(y=>typeof y!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(y)))throw new Error("本地数据索引异常");return[...new Set(h)]},s=async(c,d)=>{if(e.diagnostics){const l=Nt(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){X(d.signal,{preserveReason:!0});const h=await Promise.all(f.slice(l,l+16).map(async y=>{const w=await e.storage.getRaw(Nt(c,y),d);return w!==void 0&&w!==""?{area:"local",key:y,value:w}:void 0}));for(const y of h)y&&u.push(y)}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(Nt(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>=ks)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const h=[...new Set([...l,c])];await e.storage.setRaw(Qr(f),JSON.stringify(h),u)}X(u.signal,{preserveReason:!0}),await e.storage.setRaw(Nt(f,c),d,u),X(u.signal,{preserveReason:!0})})},list(c){return i(c,d=>s(d,c))},clear(c){return i(c,async d=>{const u=await o(d,c);e.diagnostics||await e.storage.setRaw(Qr(d),JSON.stringify(u),c);for(let f=0;f<u.length;f+=16){X(c.signal,{preserveReason:!0});const h=(await Promise.allSettled(u.slice(f,f+16).map(y=>e.storage.setRaw(Nt(d,y),"",c)))).find(y=>y.status==="rejected");if(h)throw h.reason}X(c.signal,{preserveReason:!0}),await e.storage.setRaw(Qr(d),"[]",c)})}}}function Xp(e,t){return typeof navigator<"u"&&navigator.locks?new Promise((r,n)=>{navigator.locks.request(`hb-miniprogram-storage:${e}`,()=>t().then(r,n)).catch(n)}):t()}const ey=128,ty=/^[A-Za-z0-9_-]+$/;function ry(e){const t=e.scopedStorage??lu({storage:e.storage,resolveScope:()=>uu({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[Ir]:async n=>{X(e.operationContext.signal);const i=Ua(n,Ir,e.storageLimits?.maxKeyLength),o=await $(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:ja(o)}},[Ar]:async n=>{X(e.operationContext.signal);const i=fu(n,"storage.setStorage 参数必须是对象"),o=Ua(i,Ar,e.storageLimits?.maxKeyLength),s=ny(i.data,e.storageLimits?.maxValueBytes);await $(()=>t.set(o,s,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(X(e.operationContext.signal),(await $(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?ht("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:ja(o),serializedValue:o,bytes:hu(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function Ua(e,t,r=ey){const i=fu(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw ht("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!ty.test(i))throw ht("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function ny(e,t){let r;try{r=JSON.stringify(e)}catch{throw ht("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw ht("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&hu(r)>t)throw ht("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function ja(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function fu(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw ht("INVALID_PARAMS",t);return e}function hu(e){return new TextEncoder().encode(e).length}function ht(e,t){return{code:e,message:t}}const za=120;function Je(e){throw{code:"INVALID_PARAMS",message:e}}function ws(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mu(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Je(`${r} 不支持字段: ${n.join(", ")}`)}function iy(e){if(!ws(e))return Je("ui.showToast 参数必须是对象");if(mu(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Je("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>za)return Je(`ui.showToast message 不能超过 ${za} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Je("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function oy(e){return e===void 0?{dismissible:!1}:ws(e)?(mu(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Je("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Je("ui.showLoading 参数必须是对象")}function sy(e){e!==void 0&&(!ws(e)||Object.keys(e).length)&&Je("ui.hideLoading 不支持参数")}function ay(e){return{[Bn]:async t=>{X(e.operationContext.signal),await $(()=>e.presentation.showToast(iy(t),e.operationContext),e.operationContext.signal)},[Gn]:async t=>{X(e.operationContext.signal),await $(()=>e.presentation.showLoading(oy(t),e.operationContext),e.operationContext.signal)},[Qn]:async t=>{X(e.operationContext.signal),sy(t),await $(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const cy={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ae(e,"当前用户首页资料接口响应异常")}},dy=3e4;function uy(e,t,r={}){const n=r.ttlMs??dy,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 Mi(e,cy,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(l){throw t.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):l instanceof le?m("REQUEST_UNSUPPORTED",l.message):l instanceof zr?m("INVALID_RESPONSE","user home_v2 响应不合法"):l instanceof Bt?m("REQUEST_FAILED","user home_v2 请求失败"):l instanceof jr?i&&(l.status===403||l.status===429)?m("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:l.status,...l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs}}):m("REQUEST_FAILED",l.message):fy(l)?l:m("REQUEST_FAILED","user home_v2 请求失败")}return ly(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,y=d().then(w=>(s===h&&(a={userId:f,value:w,expiresAt:Date.now()+n}),w)).finally(()=>{c?.promise===y&&(c=void 0)});return c={userId:f,generation:h,promise:y},y}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function ly(e,t){if(!Q(e))throw m("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 m(n,r)}if(!Q(e.result))throw m("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function fy(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}const hy={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 ae(e,"关注用户接口响应异常")}},my={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 ae(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowStatus 接口响应异常")}},gy={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 ae(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowGuidanceBegin 接口响应异常")}},py={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 ae(e,"Steam 游戏库接口响应异常")}};function yy(e,t=Do){const r=kf({version:"2",validate:wy}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):Do,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 Ha(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 Ey(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 wy(e){if(!Q(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Fa(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw kt();for(const t of e.gameList){if(!Q(t)||!Uo(t.appid)||!Uo(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw kt();for(const r of["image","portraitImage","icon"])Iy(t,r);for(const r of["playtimeForever","playtime2Weeks"])Fa(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw kt()}return e}function Uo(e){return typeof e=="number"&&Number.isFinite(e)}function Fa(e,t){if(e[t]!==void 0&&!Uo(e[t]))throw kt()}function Iy(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw kt()}function kt(){return m("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const gu=20,Ay=100,My=128,pu=0,yu="weeks",Ny=100,Dy=new Set(["weeks","all","achieved"]);function Sy(){return{nickname:"",avatar:""}}function Ty(e){const t=uy(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??yd(),i=yy(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(A,O){const M=JSON.stringify([A,O]);return(!o||o.key!==M)&&(o={key:M,scope:n.createScope(O,n.createScope(A))}),o.scope}function d(){const A=o;o=void 0,A&&n.invalidateScope(A.scope).catch(()=>{}),s.clear()}const u=bd({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??Td))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let l,h,y=0,w=!1;const v=e.account.onChange(()=>{y+=1,t.clear(),u.invalidate(),d()}),N=e.authorization.onEvent((A,O)=>{A==="user_info_authorization_change"&&Object.values(O).some(M=>M==="denied")&&(y+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(w)return;const M=await e.account.getCurrentUserId(e.operationContext);typeof M=="string"&&M.trim()&&await n.invalidateScope(c(_(),M.trim()))}).catch(()=>{}))});function C(){if(w||e.operationContext.signal.aborted)throw m("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function _(){const A=e.identity.get()?.miniProgramId?.trim();if(!A)throw m("INVALID_STATE","用户能力缺少 canonical 小程序身份");return A}async function k(){C(),await a,C();let A;try{A=await e.account.getCurrentUserId(e.operationContext)}catch(O){throw e.operationContext.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):or(O)?O:m("REQUEST_FAILED","读取小黑盒账号失败")}return typeof A=="string"&&A.trim()?A.trim():void 0}async function F(A,O){const M=await k();if(y!==O||M!==A)throw m("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function j(A,O,M=e.operationContext.signal){try{return await Mi(e.network,A,O,{...e.operationContext,signal:M,credentials:"heybox-session",...f?{gate:f}:{}})}catch(S){throw e.operationContext.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):S instanceof le?m("REQUEST_UNSUPPORTED",S.message):S instanceof zr?m("INVALID_RESPONSE","用户接口响应不合法"):S instanceof Bt?m("REQUEST_FAILED","用户请求失败"):S instanceof jr?r&&(S.status===403||S.status===429)?m("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:S.status,...S.retryAfterMs===void 0?{}:{retryAfterMs:S.retryAfterMs}}):m("REQUEST_FAILED",S.message):or(S)?S:m("REQUEST_FAILED","用户请求失败")}}async function g(A,O){if(!e.authorizationContext)return{mini_program_id:A};let M;try{M=await $(()=>e.authorizationContext.get({...e.operationContext,signal:O}),O)}catch(S){if(or(S))throw S;const E=m("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(E,"cause",{configurable:!0,value:S}),E}if(!M.token?.trim())throw m("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:A,runtime_auth_context_token:M.token}}async function I(){C();const A=_(),O=y,M=await k();if(!M){if(y!==O)throw m("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const S=await g(A,e.operationContext.signal);await F(M,O);const E=await j(my,S);if(await F(M,O),_()!==A)throw m("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Ga(Ba(E))}function b(A,O){if(!A)return Promise.reject(m("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(O?.aborted)return Promise.reject(m("REQUEST_CANCELLED","关注操作已取消"));if(l)return Promise.reject(m("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(m("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const M=D(O).finally(()=>{l===M&&(l=void 0)});return l=M,M}async function D(A){C();const O=_(),M=new AbortController;h=M;const S=()=>M.abort();e.operationContext.signal.addEventListener("abort",S,{once:!0}),A?.addEventListener("abort",S,{once:!0});let E=()=>{},L=!1;try{try{await $(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:M.signal}),M.signal)}catch(ie){throw or(ie)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(ie.code)?m("FOLLOW_CANCELLED","已取消小黑盒登录"):ie}C();const R=y;E=e.account.onChange(()=>{L=!0,S()});const x=await $(k,M.signal);if(!x)throw m("FOLLOW_CANCELLED","未完成小黑盒登录");const z=async()=>{if(await $(()=>F(x,R),M.signal),C(),_()!==O)throw m("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await z();const H=await g(O,M.signal);await z();const V=ky(),G=await $(()=>j(gy,{...H,request_id:V},M.signal),M.signal);await z();const K=Ba(G);if(K.status!=="notFollowing")return Ga(K);if(K.rateLimited)throw m("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const Z=await $(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:O,signal:M.signal}),M.signal);if(await z(),Z!=="confirmed")throw m("FOLLOW_CANCELLED","已取消关注作者");const J=K.authorId,Y=await $(()=>j(hy,{body:{following_id:J}},M.signal),M.signal);if(await z(),Y.status!=="ok"){const ie=["login","relogin","lack_token"].includes(Y.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw m(ie,typeof Y.msg=="string"&&Y.msg.trim()?Y.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(R){throw C(),L?m("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):A?.aborted?m("REQUEST_CANCELLED","关注操作已取消"):or(R)?R:m("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{E(),e.operationContext.signal.removeEventListener("abort",S),A?.removeEventListener("abort",S),h===M&&(h=void 0)}}async function P(){_();const A=y,O=await k();if(!O)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[M,S]=await Promise.all([e.authorization.getOrCreateLocalIdentity(O),p(O).catch(()=>Sy())]);return await F(O,A),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:M.appUserId,profile:S,...M.steamId?{steam_id:M.steamId}:{}}}}function p(A){return u.read(A,()=>j(_d,void 0).then(O=>{const M=jo(O,"账号基础信息");if(M.display_username!==void 0&&typeof M.display_username!="string")throw m("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(M.display_avatar!==void 0&&typeof M.display_avatar!="string")throw m("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:M.display_username??"",avatar:M.display_avatar??""}}))}async function T(A){const O=_y(A),M=_(),S=y,E=await k();if(!E)return d(),{isLogin:!1,isBound:!1,data:null};const L=await t.get(E);await F(E,S);const R=Eu(L.steam_id_info);if(Object.keys(R).length===0)return await n.invalidateScope(c(M,E)).catch(()=>{}),await F(E,S),s.delete(JSON.stringify([M,E])),{isLogin:!0,isBound:!1,data:null};const x=JSON.stringify([M,E]),z=c(M,E),H=Ha({...O,steamId:void 0},R),V=wu(R.personal_infomation_open??R.personal_information_open),G=JSON.stringify([H??null,V??null]),K=s.get(x);K&&K.identity!==G&&(await n.invalidateScope(z).catch(()=>{}),await F(E,S));const Z={identity:G,scope:n.createScope(G,z)};s.set(x,Z);const J=Ha(O,R),Y=J?i.persistent:i.unresolved,ie=n.createScope(J??"unresolved",Z.scope),Pe=async()=>{if(await F(E,S),_()!==M||s.get(x)?.identity!==G)throw m("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},ge=await Y.read({scope:ie,key:Ey({miniProgramId:M,userId:E,effectiveSteamId:J,personalInformationOpen:V,query:O}),signal:e.operationContext.signal,load:async he=>{const Li=await j(py,{userId:E,...O,personalInformationOpen:V},he);return await Pe(),Ly(jo(Li,"Steam 游戏库"),O)}}).catch(async he=>{throw await Pe(),he});return await Pe(),{isLogin:!0,isBound:!0,data:ge}}return{getFollowStatus:I,requestFollowAuthor:b,getInfo:P,getSteamGameList:T,async invalidateSteamGameListCache(){const A=_(),O=y,M=await k();if(!M)return;const S=c(A,M);await Promise.all([i.persistent.invalidateScope(S),i.unresolved.invalidateScope(S)]),t.clear(),s.delete(JSON.stringify([A,M])),await F(M,O)},dispose(){w||(w=!0,h?.abort(),y+=1,v(),N(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function _y(e){if(e==null)return{limit:gu,offset:pu,sort:yu,includeHidden:!1};if(!Q(e))throw Xe("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Xe(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:by(e.limit),offset:Oy(e.offset),sort:vy(e.sort),includeHidden:Cy(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>My)throw Xe("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Xe("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Ny))}return r}function by(e){if(e===void 0)return gu;if(!Number.isInteger(e)||Number(e)<1)throw Xe("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Ay)}function Oy(e){if(e===void 0)return pu;if(!Number.isInteger(e)||Number(e)<0)throw Xe("user.getSteamGameList offset 必须是非负整数");return Number(e)}function vy(e){if(e===void 0)return yu;if(typeof e!="string"||!Dy.has(e))throw Xe("user.getSteamGameList sort 不支持");return e}function Cy(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Xe("user.getSteamGameList includeHidden 必须是 boolean");return e}function Ly(e,t){if(!Array.isArray(e.game_list))throw m("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(Ry).filter(a=>a!==void 0),n=oi(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=wu(e.is_me);return s!==void 0&&(o.isMe=s),o}function Ry(e){const t=Eu(e),r=oi(t.appid),n=oi(t.steam_appid)??r,i=Is(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};qi(o,"image",t.image),typeof t.vertical_head_image=="string"&&qi(o,"portraitImage",t.vertical_head_image),qi(o,"icon",t.appicon??t.icon),Va(o,"playtimeForever",t.playtime_forever),Va(o,"playtime2Weeks",t.playtime_2weeks);const s=Py(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function jo(e,t){if(!Q(e))throw m("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 m(n,r)}if(!Q(e.result))throw m("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Eu(e){return Q(e)?e:{}}function Is(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Py(e){return Array.isArray(e)?e.map(Is).filter(Boolean):[]}function oi(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function wu(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function qi(e,t,r){const n=Is(r);n&&Object.assign(e,{[t]:n})}function Va(e,t,r){const n=oi(r);n!==void 0&&Object.assign(e,{[t]:n})}function Xe(e){return m("INVALID_PARAMS",e)}function or(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Ba(e){const t=jo(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 m("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Ga(e){return e.status}function ky(){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 xy(e){return{[An]:async t=>(Zr(t,"user.getFollowStatus"),e.user.getFollowStatus()),[Mn]:async(t,r)=>(Zr(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[Nn]:async t=>(Zr(t,"user.getInfo"),e.user.getInfo()),[Dn]:async(t,r)=>{Zr(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Sn]:async t=>e.user.getSteamGameList(t)}}function Zr(e,t){if(e!==void 0)throw m("INVALID_PARAMS",`${t} 不接收入参`)}function Qa(e){throw{code:"INVALID_PARAMS",message:e}}function sr(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Iu(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Jr(e,t,r){return Math.min(Iu(e,t),r)}async function Uy(e){try{return Iu(await e.getNavigationBarHeight(),0)}catch{return 0}}function jy(e,t,r,n){const i=Jr(e.safeArea?.left,0,t),o=Math.max(i,Jr(e.safeArea?.right,t,t)),s=Jr(e.safeArea?.top,n,r),a=Math.max(s,Jr(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Ya(e){const t=e.getViewportMetrics(),r=sr(t.windowWidth,0),n=sr(t.windowHeight,0),i=await Uy(e);return{pixelRatio:sr(t.pixelRatio,1),screenWidth:sr(t.screenWidth,r),screenHeight:sr(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:jy(t,r,n,i),screenTop:i}}function zy(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;Ya(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=ap({...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:{[pt]:async(f,l)=>c.apply(f,l?.signal),[On]:async()=>(X(r.operationContext.signal),Ya(r.presentation)),[vn]:async f=>{if(X(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return Qa("viewport.setNavigationBarStyle 参数必须是对象");const l=f.foregroundStyle;if(l!=="light"&&l!=="dark")return Qa("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await $(()=>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}}const Hy=new Map(tt.map(e=>[e.method,e]));function cn(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function Fy(e){const t=$l(e);return r=>t(r.requirement,r.method)}function Vy(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 By(e){const t=Fy(e.runtimePermissions),r=Ce(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??Gy,c=e.onTrace?a():0,d=e.onTrace?`cap_${++n}`:"";try{if(e.terminalSignal.aborted)throw cn("RUNTIME_DESTROYED","小程序 Runtime 已终止");lf(i,e.effectiveCapabilities);const u=Hy.get(i);if(!u)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const f=t(u),l=!f.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,o)===!0,h=!f.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,o)===!0;if(!f.allowed&&!l&&!h)throw cn(f.code,f.message,f.data);const y=e.handlers[i];if(!y)throw new Error(`Capability method ${i} 缺少 handler`);const w=async C=>{for(const _ of e.policies??[]){const k=await _.evaluate({method:i,payload:o,capability:u});if(e.terminalSignal.aborted||C.aborted)throw Wa();if(!k.allowed)throw cn(k.code,k.message,k.data)}if(e.terminalSignal.aborted||C.aborted)throw Wa()},N=await Vy(async()=>{if(i===pt){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,w)}return await w(e.terminalSignal),y(o,s)},void 0,s,e.terminalSignal);return qa(e.onTrace,$a(d,i,o,c,N),a),N}catch(u){throw qa(e.onTrace,$a(d,i,o,c,{status:"error",error:u}),a),u}}}}function Gy(){return typeof performance>"u"?Date.now():performance.now()}function qa(e,t,r){if(!e)return;const n=r();try{e({...t,timestamp:n,durationMs:Math.max(0,Number.isFinite(n-t.startedAt)?n-t.startedAt:0)})}catch{}}function $a(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:Qy(i.error)}:{},...Yy(t,r,i)}}function Qy(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function Yy(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"&&Au(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 Au(e){return typeof e=="object"&&e!==null}function Wa(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function qy(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=Zf(e.requestPolicy);let n;if(e.files)try{n=Ff(e.files,t)}catch{}const i=yd({store:n}),o=e.onRequestPolicyReport??(r.debugReport?$y:void 0),s=r.enabled?qf({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new hs(e.files,e.miniProgramDetail),c=gg({registry:a,picker:e.picker,operationContext:t}),d=Nh({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,y,w=()=>{},v=()=>{};try{u=zy({operationContext:t,presentation:e.hostPresentation,onDisplayChange:I=>e.eventSink.postEvent("display_change",I),onViewportChange:I=>e.eventSink.postEvent("viewport_change",I)}),l=Ty({authPresentation:e.authPresentation,authorizationContext:e.authorizationContext,account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:d,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:s,requestPolicyEnabled:r.enabled}),w=d.onEvent((I,b)=>e.eventSink.postEvent(I,b)),v=e.hostCompanion?.onSessionEvent?.(I=>{const b=dg(I);!e.terminalSignal.aborted&&b&&e.eventSink.postEvent(b.type,b.payload)})??(()=>{}),h=im({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled}),y=$m({identity:e.identity,storage:e.storage,account:e.account,presentation:e.hostPresentation,network:e.network,authorization:d,authorizationContext:e.authorizationContext,operationContext:t,files:e.files,transfer:e.transfer,fileRegistry:a,requestGate:s,requestPolicyEnabled:r.enabled});const N=ry({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});f=Ug({registry:a,media:e.media,operationContext:t});const C=[{name:"gameSaves",handlers:y.handlers},{name:"auth",handlers:Ch({authorization:d})},{name:"user",handlers:{...xy({user:l,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...Pf({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:Jp({prepareScreenshot:e.prepareScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:u.handlers},{name:"storage",handlers:N.handlers},{name:"network",handlers:pp({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[En]:async()=>{throw cn("CAPABILITY_UNAVAILABLE","当前 Runtime 不支持工作区卡片刷新")}}},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"media",handlers:f.handlers},{name:"ui",handlers:ay({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:hg({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:cp({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:I=>u.applyOrientation({mode:"portrait",hideCapsule:!1},I)}:{}})},{name:"cloud",handlers:h.handlers},{name:"companion",handlers:ig({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],_=Wy(C);let k=!1;const F=()=>{k||(k=!0,e.terminalSignal.removeEventListener("abort",F),u?.dispose(),f?.dispose(),h?.dispose(),y?.dispose(),w(),v(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?F():e.terminalSignal.addEventListener("abort",F,{once:!0});const j=new Set(["file.readText","file.readBytes","file.stat"]),g=(I,b)=>j.has(I)&&Au(b)&&a.isCompanionAttachmentRef(b.target);return{modules:C,handlers:_,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:g,allowsGameSaveAccess:y.allowsRead,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...N.diagnostics?{storageDiagnostics:N.diagnostics}:{},dispose:F}}catch(N){throw u?.dispose(),f?.dispose(),h?.dispose(),y?.dispose(),w(),v(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),N}}function $y(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Wy(e){const t=new Map(tt.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=tt.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==tt.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Ky="heybox-mini-dev:";function Ka(e){try{return Zy(new URL(e))}catch{return!1}}function Zy(e){return e.protocol===Ky}function Jy(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Xy(e)}function Xy(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 eE=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function tE(e,t){const r=[],n=rE(e.environmentInfo,r),i=dn(n?.appVersion,"host.appVersion",r),o=iE(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:nE(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:dn(t.miniProgramId),version:dn(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function rE(e,t){if(e!=null){if(Mu(e))return e;t.push("environmentInfo")}}function nE(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function iE(e,t){if(e==null)return{name:"unknown",version:null};if(!Mu(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=eE.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:dn(e.version,"operatingSystem.version",t)}}function dn(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const oE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",sE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",aE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",cE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function dE(e,t,r,n,i="dark"){X(n);const o=e.defaultView;if(!o||!e.body)throw new Error("截图水印缺少可用的展示窗口");const s=e.createElement("div"),a=i==="light",c=a?"black":"white";s.dataset.miniProgramScreenshotWatermark="",s.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);s.style.cssText=`position:absolute;left:${r.left+o.scrollX}px;top:${r.top+o.scrollY+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const u=e.createElement("div");u.style.cssText=`display:flex;flex-direction:column;align-items:center;width:${r.width/d}px;height:57px;transform:scale(${d});transform-origin:top left;font-family:"PingFang SC",sans-serif;`;const 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?aE:oE,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 y=e.createElement("img");y.src=a?cE:sE,y.style.cssText="width:12px;height:12px;flex-shrink:0;";const w=e.createElement("span");w.textContent=t?.trim()||"小程序工坊",w.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const v=e.createElement("div");v.textContent="小黑盒工坊小程序",v.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(y,w),f.append(l,h),u.append(f,v),s.append(u),e.body.append(s);const N=()=>{s.remove(),n.removeEventListener("abort",N)};n.addEventListener("abort",N,{once:!0});try{return await $(()=>Promise.all([l.decode(),y.decode()]),n),await $(()=>new Promise(C=>{let _=o.requestAnimationFrame(()=>{_=o.requestAnimationFrame(()=>{n.removeEventListener("abort",k),C()})});const k=()=>o.cancelAnimationFrame(_);n.addEventListener("abort",k,{once:!0})}),n),N}catch(C){throw N(),C}}const uE=1,Nu="allow-scripts allow-same-origin",lE="",fE="no-referrer";function hE(e=Nu){return!e.split(/\s+/).includes("allow-same-origin")}function Za(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const mE=new Set(["javascript:","data:","blob:","file:"]),Ja="xiaoheihe.cn";function gE(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(mE.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!IE(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function pE(e,t){const r=new URL(e);return r.searchParams.set(Tl,t),r.toString()}function yE(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=EE(r)??wE(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function EE(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function wE(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function Xa(e){const t=new URL(e);return As(t)?"loopback":Ms(t)?"lan":"production"}function IE(e,t,r){return AE(e)||As(e)||Ms(e)&&NE(t,r)}function AE(e){return e.protocol==="https:"&&TE(e.hostname)}function As(e){return e.protocol==="http:"&&ME(e.hostname)}function ME(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Ms(e){return e.protocol==="http:"&&DE(e.hostname)}function NE(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return As(r)||Ms(r)}catch{return!1}}function DE(e){const t=SE(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function SE(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 TE(e){return e===Ja||e.endsWith(`.${Ja}`)}const _E=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"]),bE=new Set(["url","inline","eval","unknown"]),OE=/^\/(?:\:segment(?:\/\:segment)*)?$/,vE=/^[a-f0-9]{64}$/,CE=255,LE=160,RE=256;function PE(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!_E.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>RE||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!bE.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=kE(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>LE||!OE.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!vE.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 kE(e){if(e!==void 0&&!(typeof e!="string"||e.length>CE))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const xE=/^(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 UE(e){if(!e?.minimumSdkVersion)throw ee("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=ut(e.minimumSdkVersion),r=e.sdkVersion?ut(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=ut("0.6.0");if(!r){if(un(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(un(r,t)<0)throw ee("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:un(r,ut("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function jE(e,t){if(typeof t!="string"||!ut(t))throw ee("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw ee("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function Du(e,t){const r=ut(e),n=ut(t);if(!(!r||!n))return un(r,n)}function ut(e){const t=xE.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 un(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],o=t.prerelease[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const Di=["android","ios","ohos","windows","macos","linux"],zE="0.9.0",HE=Object.freeze(["android","ios","ohos","windows","macos"]),Su="该小程序暂不支持当前平台",FE="PLATFORM_UNSUPPORTED";function VE(e){return typeof e=="string"&&Di.includes(e)}function BE(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 GE(e){const t=e.manifest;if(!WE(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=tc(e.sdkVersion)??tc(t.sdkVersion);return qE(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:YE()}const r=Tu(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function QE(e){const t=BE(e.operatingSystemName);if(!t)return Lt("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Lt("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Di,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=GE({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Lt("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):ec(t,s)}if(r.effectivePlatforms===void 0)return Lt("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=Tu(r.effectivePlatforms);if("reason"in n)return Lt("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=$E(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return ec(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function ec(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Lt("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Lt(e,t={}){return{status:"denied",reason:e,message:Su,...t}}function YE(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:HE,platformsDeclared:!1,policy:"legacy_mobile_default"}}function Tu(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(!VE(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Di.filter(r=>t.has(r)))}}function qE(e){if(typeof e!="string"||!e.trim())return!1;const t=Du(e.trim(),zE);return t!==void 0&&t>=0}function tc(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function $E(e){return e==="explicit"||e==="legacy_mobile_default"}function WE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const KE=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 ZE(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:JE(i.pathname),sanitizedPathnameHash:XE(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function JE(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function XE(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 v=0;v<16;v+=1)o[v]=s.getUint32(a+v*4,!1);for(let v=16;v<64;v+=1){const N=o[v-15],C=o[v-2],_=Ue(N,7)^Ue(N,18)^N>>>3,k=Ue(C,17)^Ue(C,19)^C>>>10;o[v]=o[v-16]+_+o[v-7]+k>>>0}let[c,d,u,f,l,h,y,w]=i;for(let v=0;v<64;v+=1){const N=w+(Ue(l,6)^Ue(l,11)^Ue(l,25))+(l&h^~l&y)+KE[v]+o[v]>>>0,C=(Ue(c,2)^Ue(c,13)^Ue(c,22))+(c&d^c&u^d&u);w=y,y=h,h=l,l=f+N>>>0,f=u,u=d,d=c,c=N+C>>>0}[c,d,u,f,l,h,y,w].forEach((v,N)=>{i[N]=i[N]+v>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function Ue(e,t){return e>>>t|e<<32-t}const ew=1e4,tw=1e4,$i=2e3,rw=2,nw="open-with-native-credential-policy",_u="安全提示",bu="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class iw{nonce=Za();runtimeId=Za();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;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;sdkVersionDecision;platformGateDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;unexpectedDocumentLoadTimer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=pd(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities});this.ports=r.ports,this.primitiveAvailability=r.primitiveAvailability,this.effectiveCapabilities=r.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const n=this.identity.miniProgramId?.trim();if(n)return{miniProgramId:n,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??ew,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics;return t?{storage:t}:{}}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:(hw(),this.startPromise=this.createReadyPromise(),this.setState("starting"),this.setStatus("starting"),this.launch().catch(t=>{this.failRuntime(t)}),this.startPromise)}destroy(){if(this.stateValue==="destroyed")return;const t=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.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;this.runtimePermissions=Wl(t.runtimePermissions),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=UE(t.sdkVersionPolicy);const n=tE(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=QE({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw pw(this.platformGateDecision);if(this.miniProgramDetail=yw(t),this.effectiveCapabilities=gd(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),cw(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(uw(i)),this.launchUrl=i,this.miniProgramSrc=pE(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=as(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:pt,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,qe(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[pt])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=qy({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,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,prepareScreenshot:(n,i,o)=>{const s=this.sdkVersionDecision?.sdkVersion;return!s||(Du(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):dE(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=By({handlers:this.capabilityGraph.handlers,runDisplayRequest:this.capabilityGraph.runDisplayRequest,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,allowsGameSaveAccess:this.capabilityGraph.allowsGameSaveAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:u})=>{const f={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...u?{network:u}:{}};qe(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new tf({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,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.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 aw(t)?t:Ou(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 gE(t,r,{allowPrivateNetwork:Ka(r)||rc(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??fw)({message:bu,title:_u,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Xa(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!Ka(r)&&!rc(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{nc(),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(()=>nc())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",lE),this.iframe.setAttribute("referrerpolicy",fE),this.iframe.setAttribute("sandbox",Nu)}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.lifecycleDisposer=null;for(const r of t)try{r?.()}catch{}}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(),qe(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(),qe(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{jE(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>=rw)){this.failRuntime(ee("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Br,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},$i),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Br})}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(),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(Br,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Br})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&(this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(ee("UNEXPECTED_DOCUMENT_LOAD",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时")))},r.waitingForDocument?tw:$i))}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()},$i))}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()}handleDuplicateBridgeHandshake(){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"}),this.documentRevalidationPending&&this.resendDocumentRevalidationProbe()}handleInternalBridgeEvent(t){if(t.method===bl){this.handleCspViolation(t.payload);return}if(t.method!==_l)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"||!yE(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=PE(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){qe(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=ZE(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:uE,launchUrlType:Xa(t),networkPolicy:nw})}failRuntime(t){const r=ow(t);return this.isInactive()||(this.terminalError=r,this.terminalController.abort(r),this.postBridgeError(r),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),this.setState("failed"),this.teardownIframe(r),qe(this.options.onError,sw(r)),this.rejectReady?.(r)),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.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!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,qe(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){qe(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 ow(e){const t=as(e);return si(e)&&"cause"in e&&Ou(t,e.cause),t}function Ou(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function sw(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function aw(e){return si(e)&&typeof e.code=="string"&&typeof e.message=="string"}function si(e){return!!e&&typeof e=="object"}function qe(e,t){try{e?.(t)}catch{}}function cw(e,t,r){try{e?.(t,r)}catch{}}function rc(e){try{const t=new URL(e);return t.protocol==="http:"&&Jy(t.hostname)}catch{return!1}}function dw(e){try{return new URL(e).origin}catch{return}}function uw(e){return hE()?"*":dw(e)}function lw(e){return`${_u}
1
+ import{H as Ls,aI as nl,bd as il,U as ol,aY as sl,aZ as al,au as xr,bn as W,aT as Qc,k as Yc,ak as cl,av as qc,aB as dl,bh as Xt,aM as $c,aO as ul,g as Wc,af as Kc,v as ll,ax as fl,i as hl,aV as Zc,ai as ml,aE as Jc,y as gl,aK as Xc,u as pl,aU as yl,bf as El,be as wl,d as Il,h as Al}from"./desktop-app-launch-DwX62DHx.js";const En="workspaceCards.requestRefresh",wn="auth.getAccountState",In="auth.login",An="user.getFollowStatus",Mn="user.requestFollowAuthor",Ml="gameSaves.list",Nl="gameSaves.sync",Dl="gameSaves.getFile",Sl="gameSaves.readParsedData",Nn="user.getInfo",Dn="user.revokeAuthorization",Sn="user.getSteamGameList",wr="user.showAppreciation",Tn="share.copyLink",_n="share.showShareMenu",bn="share.screenshot",pt="viewport.setDisplay",On="viewport.getWindowInfo",vn="viewport.setNavigationBarStyle",Ir="storage.getStorage",Ar="storage.setStorage",Cn="network.request",Ln="network.download",Rn="network.upload",Pn="files.pickFiles",kn="files.pickDirectory",xn="files.saveFile",Mr="file.create",Nr="file.remove",Un="file.exists",Dr="file.readText",jn="file.writeText",Sr="file.readBytes",zn="file.writeBytes",Tr="file.stat",Hn="directory.create",_r="directory.remove",Fn="directory.exists",Vn="directory.list",br="media.pick",Bn="ui.showToast",Gn="ui.showLoading",Qn="ui.hideLoading",Yn="device.vibrate",qn="device.setClipboard",$n="device.executeProtocol",Wn="navigation.close",Kn="navigation.reload",Zn="navigation.openAppPage",Qe="cloud.leaderboard.submit",Oe="cloud.leaderboard.getList",et="cloud.leaderboard.getCurrentUserEntry",yt="cloud.leaderboard.deleteCurrentUserEntry",He="cloud.leaderboard.getInfo",jt="cloud.storage.getStorage",zt="cloud.storage.setStorage",Ht="cloud.storage.removeItem",Et="cloud.storage.getKeys",ui="companion.getInfo",li="companion.getPreparationStatus",fi="companion.prepare",hi="companion.cancelPreparation",mi="companion.getActiveSession",gi="companion.launch",pi="companion.session.write",yi="companion.session.closeStdin",Ei="companion.session.terminate",wi="companion.session.ackOutput",Ii="companion.openAttachment",Ai="companion.showNotification",tt=[...[Ml,Nl,Dl,Sl].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),{method:En,module:"workspaceCards",capability:En,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:wn,module:"auth",capability:wn,requirement:{kind:"none"},risk:"low"},{method:In,module:"auth",capability:In,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:An,module:"user",capability:An,requirement:{kind:"none"},risk:"low"},{method:Mn,module:"user",capability:Mn,requirement:{kind:"none"},risk:"high"},{method:Nn,module:"user",capability:Nn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Dn,module:"user",capability:Dn,requirement:{kind:"none"},risk:"high"},{method:Sn,module:"user",capability:Sn,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:wr,module:"user",capability:wr,requirement:{kind:"none"},risk:"medium"},{method:Tn,module:"share",capability:Tn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:_n,module:"share",capability:_n,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:bn,module:"share",capability:bn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:On,module:"viewport",capability:On,requirement:{kind:"none"},risk:"low"},{method:vn,module:"viewport",capability:vn,requirement:{kind:"none"},risk:"low"},{method:pt,module:"viewport",capability:pt,requirement:{kind:"none"},risk:"low"},{method:Ir,module:"storage",capability:Ir,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:Ar,module:"storage",capability:Ar,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Cn,module:"network",capability:Cn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Ln,module:"network",capability:Ln,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Rn,module:"network",capability:Rn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Pn,module:"files",capability:Pn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:kn,module:"files",capability:kn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:xn,module:"files",capability:xn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mr,module:"file",capability:Mr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Nr,module:"file",capability:Nr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Un,module:"file",capability:Un,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dr,module:"file",capability:Dr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:jn,module:"file",capability:jn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Sr,module:"file",capability:Sr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:zn,module:"file",capability:zn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Tr,module:"file",capability:Tr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Hn,module:"directory",capability:Hn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_r,module:"directory",capability:_r,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Fn,module:"directory",capability:Fn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Vn,module:"directory",capability:Vn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:br,module:"media",capability:br,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:Bn,module:"ui",capability:Bn,requirement:{kind:"none"},risk:"low"},{method:Gn,module:"ui",capability:Gn,requirement:{kind:"none"},risk:"low"},{method:Qn,module:"ui",capability:Qn,requirement:{kind:"none"},risk:"low"},{method:Yn,module:"device",capability:Yn,requirement:{kind:"none"},risk:"low"},{method:qn,module:"device",capability:qn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:$n,module:"device",capability:$n,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:Wn,module:"navigation",capability:Wn,requirement:{kind:"none"},risk:"medium"},{method:Kn,module:"navigation",capability:Kn,requirement:{kind:"none"},risk:"medium"},{method:Zn,module:"navigation",capability:Zn,requirement:{kind:"none"},risk:"medium"},{method:Qe,module:"cloud",capability:Qe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Oe,module:"cloud",capability:Oe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:et,module:"cloud",capability:et,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:yt,module:"cloud",capability:yt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:He,module:"cloud",capability:He,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:jt,module:"cloud",capability:jt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:zt,module:"cloud",capability:zt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Ht,module:"cloud",capability:Ht,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Et,module:"cloud",capability:Et,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[ui,li,fi,hi,mi,gi,pi,yi,Ei,wi,Ii,Ai].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],at="heybox:miniprogram",ed=2,Tl="hb_mini_bridge_nonce",td="sdk.handshake",Br="runtime.location.probe",_l="sdk.location.report",bl="sdk.csp.violation",rd="operation.progress",Ol="companion.session.output",vl="companion.session.exit",Cl="companion.session.ownershipLost";function Ll(e){return!Re(e)||e.namespace!==at||e.version!==1&&e.version!==2||!ce(e.nonce)?!1:e.type==="handshake"?ce(e.id)&&e.method===td&&e.error===void 0&&Hl(e.payload):e.type==="request"?ce(e.id)&&ce(e.method)&&e.error===void 0:e.type==="response"?ce(e.id)&&(e.method===void 0||ce(e.method))&&(e.error===void 0||Fl(e.error)):e.type==="event"?!ce(e.method)||e.error!==void 0?!1:e.method===rd?e.version===2&&ce(e.id)&&zl(e.payload):e.id===void 0||ce(e.id):e.type==="cancel"?e.version===2&&ce(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function os(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function nd(e){return Re(e)?e.kind==="sandbox"?Te(e,["kind"]):e.kind==="directory"&&ce(e.handleId)&&Te(e,["kind","handleId"]):!1}function Ft(e){return!Re(e)||e.kind!=="file"?!1:ce(e.handleId)?Te(e,["kind","handleId"]):nd(e.root)&&os(e.relativePath)&&Te(e,["kind","root","relativePath"])}function id(e){return!Re(e)||e.kind!=="directory"?!1:ce(e.handleId)?Te(e,["kind","handleId"]):nd(e.root)&&(e.relativePath==="."||os(e.relativePath))&&Te(e,["kind","root","relativePath"])}function Rl(e){return Re(e)&&e.kind==="file"&&ce(e.name)&&Vl(e.mode)&&Ft(e.ref)&&Te(e,["kind","name","mode","ref"])}const od=20,Rs=["type","mimeType","size","width","height","previewUrl","file"];function Pl(e){return e===void 0?!0:!(!Re(e)||!Te(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&&(!Bl(e.maxCount,1,od)||e.source==="camera"&&e.maxCount!==1))}function sd(e){if(!Re(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!Te(e,t?[...Rs,"durationMs"]:Rs)||!ce(e.mimeType)||!Ze(e.size)||!Ps(e.width)||!Ps(e.height)||!ce(e.previewUrl)||!xl(e.file)?!1:t?Ze(e.durationMs):!0}function kl(e){if(!Array.isArray(e)||e.length<1||e.length>od)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!sd(e[t]))return!1;return!0}function xl(e){return!Rl(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&ce(e.ref.handleId)}function ad(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function Ul(e){return!Re(e)||!Ze(e.loaded)||typeof e.lengthComputable!="boolean"||!Te(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Ze(e.total)&&e.loaded<=e.total:e.total===void 0}function jl(e){return Re(e)?e.phase==="downloading"?Ze(e.loaded)&&(e.total===void 0||Ze(e.total)&&e.loaded<=e.total)&&Te(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Ze(e.processed)&&Ze(e.total)&&e.processed<=e.total&&Te(e,["phase","processed","total"]):!1}function zl(e){return Ul(e)||jl(e)}function Hl(e){return Re(e)&&ce(e.href)&&typeof e.userAgent=="string"&&ce(e.sdkVersion)}function Fl(e){return Re(e)&&ce(e.code)&&typeof e.message=="string"}function Vl(e){return e==="read"||e==="readwrite"}function Ze(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ps(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Bl(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function ce(e){return typeof e=="string"&&e.length>0}function Te(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Or=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards"],cd=[{key:"gameSaves",name:"游戏存档",description:"获取和同步当前用户指定游戏的 Steam 云存档,并读取存档文件,无需单独弹窗确认。",access:"declaration",risk:"high",config:{},methods:["gameSaves.list","gameSaves.sync","gameSaves.getFile","gameSaves.readParsedData"],conditions:["需要用户明确授权、有效 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"],conditions:["继续执行分享参数校验和 Host 支持检查。"]},{key:"storage",name:"键值存储",description:"读写按小程序隔离的简单键值数据。",access:"declaration",risk:"medium",config:{},methods:["storage.getStorage","storage.setStorage"],conditions:["仅用于简单键值存储,不包含文件系统。"]},{key:"cloud_storage",name:"云端存储",description:"读写按小程序和当前登录用户隔离的云端键值数据。",access:"declaration",risk:"medium",config:{},methods:["cloud.storage.getStorage","cloud.storage.setStorage","cloud.storage.removeItem","cloud.storage.getKeys"],conditions:["云端存储按登录用户隔离并受容量配额限制。"]},{key:"filesystem",name:"文件系统",description:"访问小程序沙盒文件和用户选择的外部文件。",access:"declaration",risk:"high",config:{},methods:["network.download","network.upload","files.pickFiles","files.pickDirectory","files.saveFile","file.create","file.remove","file.exists","file.readText","file.writeText","file.readBytes","file.writeBytes","file.stat","directory.create","directory.remove","directory.exists","directory.list"],conditions:["外部文件继续要求有效的用户选择、会话句柄和匹配的读写模式。"]},{key:"media",name:"媒体",description:"通过系统图库或相机选择图片、视频。",access:"declaration",risk:"high",config:{},methods:["media.pick"],conditions:["图库授权范围仅限本次用户选择的媒体,不包含任意文件或沙盒访问权;继续执行可信手势、Host 能力与会话资源规则。"]},{key:"clipboard",name:"剪贴板",description:"向系统剪贴板写入文本。",access:"declaration",risk:"medium",config:{},methods:["device.setClipboard"],conditions:["继续执行文本长度和 Host 支持限制。"]},{key:"leaderboard",name:"排行榜",description:"读写小程序云排行榜。",access:"declaration",risk:"medium",config:{},methods:["cloud.leaderboard.submit","cloud.leaderboard.getList","cloud.leaderboard.getCurrentUserEntry","cloud.leaderboard.deleteCurrentUserEntry","cloud.leaderboard.getInfo"],conditions:["排行榜必须已创建,用户和资源规则保持不变。"]},{key:"network",name:"网络",description:"通过 network 模块请求或下载外部资源。",access:"platform-approval",risk:"high",config:{useOfficialDomain:{type:"boolean",required:!1,default:!1,description:"是否申请访问小黑盒官方域名。"}},methods:["network.request","network.download","network.upload"],conditions:["声明后仍需平台批准,并继续执行网络安全策略。"]},{key:"companion",name:"桌面辅助应用",description:"下载、准备并运行随当前小程序版本发布的受管桌面程序。",access:"platform-approval",risk:"high",config:{},methods:["companion.getInfo","companion.getPreparationStatus","companion.prepare","companion.cancelPreparation","companion.getActiveSession","companion.launch","companion.session.write","companion.session.closeStdin","companion.session.terminate","companion.session.ackOutput","companion.openAttachment","companion.showNotification"],conditions:["声明后仍需平台批准,并继续执行可信用户手势、Host 能力和当前版本 Manifest 校验。"]},{key:"appProtocol",name:"应用协议执行",description:"执行任意小黑盒客户端协议。",access:"platform-approval",risk:"high",config:{},methods:["device.executeProtocol"],conditions:["最高危险权限:批准后该入口可执行任意协议,并绕过其他 SDK 能力权限及专用授权流程。"]},{key:"workspaceCards",name:"工作区卡片",description:"在已绑定游戏的桌面工作区展示受审核卡片。",access:"platform-approval",risk:"high",config:{},methods:["workspaceCards.requestRefresh"],conditions:["需平台批准、Host 支持与有效执行租约;不隐式授予网络或存储权限。"]}];new Set(Or);const Gl=new Set(Or);function Ql(e){return Gl.has(e)}function Ce(e){if(!Gr(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(!Gr(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),!!Ql(o)){if(o==="network"){const s=n.config;if(!Gr(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(n.config!==null&&n.config!==void 0&&(!Gr(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 Gr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const rn=["network","companion","appProtocol"];function dd(e){if(!er(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>rn.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!er(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(!er(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(!er(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!er(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>rn.indexOf(n.key)-rn.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Yl(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Ce(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of rn)!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 ss(e){const t=Ce(e.runtimePermissions),r=dd(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of Or)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:cd.some(a=>a.key===s&&a.access==="declaration")?n[s]={key:s,status:"enabled",config:{}}:s==="network"&&n.network&&(n.network.config.useOfficialDomain=n.network.status==="enabled"&&n.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(r.valid)for(const s of r.grant.entries)e.declaredPermissions[s.key]?.enabled!==!0||n[s.key]?.status==="enabled"||(n[s.key]=s,i.push(s.key));const o=ud(e.runtimePermissions)&&typeof e.runtimePermissions.revision=="number"&&Number.isSafeInteger(e.runtimePermissions.revision)&&e.runtimePermissions.revision>=0?e.runtimePermissions.revision:void 0;return{runtimePermissions:{schema_version:1,...o===void 0?{}:{revision:o},entries:Or.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function ud(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function er(e,t){return ud(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Vt=["identity","profile","steam_account"],ql=/^[a-z][a-z0-9-]{0,31}$/,ld=["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"];tt.map(e=>e.method);function $l(e){const t=Ce(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 Wl(e){const t=Ce(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 ee(e,t,r){return{code:e,message:t,data:r}}function as(e){return Kl(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?ee("RUNTIME_ERROR",e.message):ee("UNKNOWN_ERROR","小程序运行时异常",e)}function Kl(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function Zl(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Jl=1e3;function Xl(e,t=Zl()){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<=Jl}const ef="runtime.gate.probe",fd=new Set(tt.map(e=>e.method));class tf{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=ed;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,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:at,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:at,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:at,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:at,version:2,nonce:this.nonce,type:"event",id:t,method:rd,payload:r})}onMessage(t){if(!this.started||!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=Xl(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&&Ll(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:at,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:td,payload:{environment:this.environmentInfo}}),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===ef){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,ee("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!fd.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,{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=as(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:at,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!rf(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 rf(e){return typeof e=="string"&&fd.has(e)}function m(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):nf(e.signal,t);return{...e,signal:r}}function nf(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 of(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"}function nn(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function X(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:nn()}function sf(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 hd="METHOD_FORBIDDEN";function De(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=hd,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 af=/^[A-Za-z0-9_-]{1,64}$/,ks=1e3;function md(e){return af.test(e)?e:df(e)}function cf(e){return`id_${md(e.trim())}`}function Nt(e,t){return`hb_miniprogram_${e}_${t}`}function Qr(e){return`hb_miniprogram_keys_${e}`}function df(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 xs={"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"],[En]:["workspaceCards.requestRefresh"],[wn]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[In]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[An]:["account.getCurrentUserId","account.onChange","network.request"],[Mn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Nn]:["account.getCurrentUserId","account.onChange","network.request"],[Dn]:["account.getCurrentUserId","account.onChange","network.request"],[Sn]:["account.getCurrentUserId","account.onChange","network.request"],[Tn]:["presentation.setClipboard"],[_n]:["presentation.showShareMenu"],[bn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[pt]:["presentation.applyOrientation"],[On]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[vn]:["presentation.setNavigationBarStyle"],[Ir]:["storage.getRaw"],[Ar]:["storage.setRaw"],[Cn]:["network.request"],[Ln]:["network.stream","files.transfer","files.access"],[Rn]:["network.upload","files.access"],[Pn]:["files.external"],[kn]:["files.external"],[xn]:["files.save"],[Mr]:["files.access"],[Nr]:["files.removeFile"],[Un]:["files.access"],[Dr]:["files.access"],[jn]:["files.access"],[Sr]:["files.access"],[zn]:["files.access"],[Tr]:["files.access"],[Hn]:["files.access"],[_r]:["files.removeDirectory"],[Fn]:["files.access"],[Vn]:["files.access"],[br]:["media.pick"],[wr]:["presentation.showAppreciation"],[Bn]:["presentation.showToast"],[Gn]:["presentation.showLoading"],[Qn]:["presentation.hideLoading"],[Yn]:["presentation.vibrate"],[qn]:["presentation.setClipboard"],[$n]:["protocol.invoke"],[Wn]:["presentation.close"],[Kn]:["presentation.reload"],[Zn]:["presentation.openAppPage"],[Qe]:["account.getCurrentUserId","account.onChange","network.request"],[Oe]:["account.onChange","network.request"],[et]:["account.getCurrentUserId","account.onChange","network.request"],[yt]:["account.getCurrentUserId","account.onChange","network.request"],[He]:["account.onChange","network.request"],[jt]:["account.getCurrentUserId","account.onChange","network.request"],[zt]:["account.getCurrentUserId","account.onChange","network.request"],[Ht]:["account.getCurrentUserId","account.onChange","network.request"],[Et]:["account.getCurrentUserId","account.onChange","network.request"],[ui]:["companion.getInfo"],[li]:["companion.getPreparationStatus"],[fi]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[hi]:["companion.cancelPreparation"],[mi]:["companion.getActiveSession"],[gi]:["companion.getInfo","companion.launch"],[pi]:["companion.session.write"],[yi]:["companion.session.closeStdin"],[Ei]:["companion.session.terminate"],[wi]:["companion.session.ackOutput"],[Ii]:["companion.openAttachment"],[Ai]:["companion.showNotification"]},uf=new Set([wr]);function lf(e,t){if(t[e]!==!0)throw uf.has(e)?ee("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):De(e)}const ff=32*1024*1024,hf=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function mf(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:ff},i);return gf(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function gf(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:pf(t,Ef(e,"content-type"))}}function pf(e,t){yf(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||!hf.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function yf(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 Ef(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function U(e){return typeof e=="function"}function Us(e){return(...t)=>{throw De(e)}}function de(e){return async(...t)=>{throw De(e)}}const wf=(e,t)=>{},If=()=>()=>{};function Af(e){const t={request:U(e.network?.request)?e.network.request.bind(e.network):de("network.request")},r={...U(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:U(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):de("account.getCurrentUserId"),ensureAuthenticated:U(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):de("account.ensureAuthenticated"),onChange:U(e.account?.onChange)?e.account.onChange.bind(e.account):If},n={getRaw:U(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):de("storage.getRaw"),setRaw:U(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):de("storage.setRaw")},i={...U(e.presentation?.showSteamLoginRequired)?{showSteamLoginRequired:e.presentation.showSteamLoginRequired.bind(e.presentation)}:{},...U(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...U(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:U(e.presentation?.close)?e.presentation.close.bind(e.presentation):de("presentation.close"),reload:U(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):de("presentation.reload"),openAppPage:U(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):de("presentation.openAppPage"),openWindow:U(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):de("presentation.openWindow"),getViewportMetrics:U(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Us("presentation.getViewportMetrics"),getNavigationBarHeight:U(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Us("presentation.getNavigationBarHeight"),setNavigationBarStyle:U(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):de("presentation.setNavigationBarStyle"),showShareMenu:U(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):de("presentation.showShareMenu"),setScreenshotChromeHidden:U(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):wf,captureAndShare:U(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):de("presentation.captureAndShare"),showAppreciation:U(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw ee("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:U(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):de("presentation.showToast"),showLoading:U(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):de("presentation.showLoading"),hideLoading:U(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):de("presentation.hideLoading"),vibrate:U(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):de("presentation.vibrate"),setClipboard:U(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):de("presentation.setClipboard")},o=U(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,U(e.companion?.[c])?e.companion[c].bind(e.companion):de(`companion.${c}`)]));U(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const a={invoke:U(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):de("protocol.invoke")};return{network:t,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 Mf(e){const t=Nf(e.files?.sandbox),r=U(e.picker?.pickFiles)&&U(e.picker?.pickDirectory),n=U(e.picker?.saveFile),i=t||r||n||U(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":U(e.account?.getAccountKey),"account.getCurrentUserId":U(e.account?.getCurrentUserId),"account.ensureAuthenticated":U(e.account?.ensureAuthenticated),"account.onChange":U(e.account?.onChange),"network.request":U(e.network?.request),"network.stream":U(e.transfer?.network.open)&&U(e.transfer?.network.release),"network.upload":U(e.transfer?.upload?.upload),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":U(o?.remove),"files.removeDirectory":U(e.files?.sandbox.remove),"files.transfer":U(e.transfer?.files.writeResource),"media.pick":U(e.media?.pick),"storage.getRaw":U(e.scopedStorage?.get)||U(e.storage?.getRaw),"storage.setRaw":U(e.scopedStorage?.set)||U(e.storage?.setRaw),"presentation.close":U(e.presentation?.close),"presentation.reload":U(e.presentation?.reload),"presentation.openAppPage":U(e.presentation?.openAppPage),"presentation.applyOrientation":U(e.presentation?.applyOrientation),"presentation.openWindow":U(e.presentation?.openWindow),"presentation.getViewportMetrics":U(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":U(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":U(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":U(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":U(e.presentation?.captureAndShare),"presentation.showAppreciation":U(e.presentation?.showAppreciation),"presentation.showToast":U(e.presentation?.showToast),"presentation.showLoading":U(e.presentation?.showLoading),"presentation.hideLoading":U(e.presentation?.hideLoading),"presentation.vibrate":U(e.presentation?.vibrate),"presentation.setClipboard":U(e.presentation?.setClipboard),"workspaceCards.requestRefresh":!1,"companion.getInfo":U(e.companion?.getInfo),"companion.getPreparationStatus":U(e.companion?.getPreparationStatus),"companion.prepare":U(e.companion?.prepare),"companion.cancelPreparation":U(e.companion?.cancelPreparation),"companion.getActiveSession":U(e.companion?.getActiveSession),"companion.launch":U(e.companion?.launch),"companion.session.write":U(e.companion?.write),"companion.session.closeStdin":U(e.companion?.closeStdin),"companion.session.terminate":U(e.companion?.terminate),"companion.session.ackOutput":U(e.companion?.ackOutput),"companion.openAttachment":U(e.companion?.openAttachment),"companion.showNotification":U(e.companion?.showNotification),"protocol.invoke":U(e.protocol?.invoke)}}function Nf(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&U(t.file)&&U(t.directory)&&U(t.create)&&U(t.stat)&&U(t.list)}function js(e,t){return t?.[e]!==!1}function Df(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function gd(e,t={}){const r={};for(const n of Object.keys(xs)){const o=xs[n].every(a=>e[a]),s=!Df(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=js(n,t.callerCapabilities)&&js(n,t.hostCapabilities)&&o&&s}return r}function pd(e={},t={}){const r=Mf(e),n=gd(r,t);return{ports:Af(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}const Sf=4,Tf=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],_f=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),bf=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Of=["/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 vf(e,t){const r=Rf(e);return r===null||zs(r,bf)?!0:t&&zs(r,Of)}function Cf(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Tf.some(r=>t===r||t.endsWith(`.${r}`))}function Lf(e){const t=e.trim().toLowerCase();return _f.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Rf(e){let t=e;for(let r=0;r<Sf;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Hs(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Hs(t)}function zs(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Hs(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Fs(e){return e instanceof le?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function $(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(nn());let n;try{n=e()}catch(i){return Promise.reject(Fs(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(nn())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(nn()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(Fs(d))))})}function Pf(e){return{[wr]:async(t,r)=>{const n=Ne(e.operationContext,r.signal);if(X(n.signal),t!==void 0)throw m("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw m("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw m("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const o=e.presentation.showAppreciation;if(!o)throw m("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await $(()=>o({name:i.name,author:i.author},n),n.signal)}}}function Dt(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Vs(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function yd(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(w,v){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:w,type:v})).catch(()=>{})}catch{}}function u(w){const v=r.get(w);if(!v)throw new Error("Unknown runtime cache scope");return v}function f(w,v){return w.flatMap((N,C)=>{const _=JSON.stringify(w.slice(0,C+1));return[JSON.stringify([_]),JSON.stringify([_,v])]})}function l(w,v){return JSON.stringify(f(w,v).map(N=>n.get(N)??0))}async function h(w,v){const N=u(w),C=JSON.stringify([JSON.stringify(N),...v?[v]:[]]),_=(n.get(C)??0)+1;n.set(C,_),i.add(C);for(const k of a)k(N,v);if(!e.store){i.delete(C),d(v??"*","invalidation");return}try{await e.store.invalidate(N,v)}catch(k){throw d(v??"*","storage_error"),k}n.get(C)===_&&i.delete(C),d(v??"*","invalidation")}function y(w){if(c)throw new Error("Runtime cache manager disposed");const v=o.get(w.namespace);if(v){if(v.sourceCodec!==w.codec||v.definition.codec.version!==w.codec.version||JSON.stringify(v.definition.policy)!==JSON.stringify(w.policy))throw new Error("Conflicting runtime cache namespace");return v.cache}if(!w.namespace||!w.codec.version)throw new Error("Invalid runtime cache definition");const N=Object.freeze({...w.policy}),C=Object.freeze({version:w.codec.version,encode:w.codec.encode.bind(w.codec),decode:w.codec.decode.bind(w.codec),validate:w.codec.validate.bind(w.codec),clone:w.codec.clone.bind(w.codec)}),_=w.namespace;for(const S of[N.ttlMs,N.memoryMaxEntries,N.diskMaxEntries,N.diskMaxBytes,N.maxEntryBytes])if(!Number.isFinite(S)||S<0)throw new Error("Invalid runtime cache policy");const k=new Map,F=new Map,j=new Map;let g=!1;function I(S,E,L){if(c||g||S.aborted||l(E,_)!==L)throw Dt()}function b(S){return N.ttlMs>0&&N.persistence==="memory-and-disk"&&!!e.store&&!f(S,_).some(E=>i.has(E))}function D(S,E,L){const R=t();return S.envelopeVersion===1&&JSON.stringify(S.address)===JSON.stringify(E)&&Vs(S.revisions,L)&&S.payload.byteLength<=N.maxEntryBytes&&Number.isFinite(S.cachedAt)&&Number.isFinite(S.expiresAt)&&S.cachedAt<=R&&S.cachedAt>=0&&S.expiresAt>S.cachedAt&&Math.min(S.expiresAt,S.cachedAt+N.ttlMs)>R}function P(S,E,L,R,x){if(!(N.ttlMs<=0||N.memoryMaxEntries<1)){for(const[z,H]of k)Math.min(H.entry.expiresAt,H.entry.cachedAt+N.ttlMs)<=t()&&k.delete(z);for(k.delete(S);k.size>=Math.floor(N.memoryMaxEntries);){const z=k.keys().next();if(z.done)break;k.delete(z.value)}k.set(S,{entry:E,value:L,epoch:R,persistent:x})}}async function p(S,E,L,R){const x={namespace:_,codecVersion:C.version,scopeIds:E,key:S.key},z=JSON.stringify(x);let H=[],V=b(E);if(V)try{H=await e.store.readRevisions(E,_)}catch{V=!1,d(_,"storage_error")}I(R.signal,E,L);async function G(){if(!V)return!0;try{return Vs(H,await e.store.readRevisions(E,_))}catch{return V=!1,d(_,"storage_error"),!1}}const K=k.get(z);if(N.ttlMs>0&&K&&K.epoch===L&&D(K.entry,x,H)&&K.persistent===V&&await G())return I(R.signal,E,L),d(_,"memory_hit"),K.value;if(k.delete(z),V){let Y,ie;try{Y=await e.store.read(x,N.maxEntryBytes),Y&&D(Y,x,H)?ie=C.decode(Y.payload):Y=void 0}catch{Y=void 0,d(_,"storage_error")}if(I(R.signal,E,L),Y&&await G())return I(R.signal,E,L),P(z,Y,ie,L,!0),d(_,"disk_hit"),ie}d(_,"miss");const Z=C.validate(await S.load(R.signal));I(R.signal,E,L);const J=C.clone(Z);if(!await G()&&V)throw Dt();if(I(R.signal,E,L),N.ttlMs>0){const Y=t();let ie;try{ie=C.encode(J)}catch{return J}const Pe={envelopeVersion:1,address:x,revisions:V?H:[],cachedAt:Y,expiresAt:Y+N.ttlMs,payload:ie};if(V&&ie.byteLength<=N.maxEntryBytes){let ge=!0,he=!1;try{ge=await e.store.publish(Pe,N),he=ge}catch{d(_,"storage_error")}if(I(R.signal,E,L),!ge)throw Dt();he&&d(_,"published")}I(R.signal,E,L),P(z,Pe,J,L,V)}return J}async function T(S){if(c||g||S.signal?.aborted)return Promise.reject(Dt());const E=u(S.scope),L=l(E,_);let R;if(b(E)){const V=new AbortController;j.set(V,E);const G=()=>V.abort();S.signal?.addEventListener("abort",G,{once:!0});let K=()=>{};try{R=await Promise.race([e.store.readRevisions(E,_),new Promise((Z,J)=>{const Y=()=>J(Dt());V.signal.addEventListener("abort",Y,{once:!0}),K=()=>V.signal.removeEventListener("abort",Y)})])}catch{V.signal.aborted||d(_,"storage_error")}finally{K(),j.delete(V),S.signal?.removeEventListener("abort",G)}}I(S.signal??new AbortController().signal,E,L);const x=JSON.stringify([E,S.key,L,R]);let z=F.get(x);if(z?.controller.signal.aborted&&(z=void 0),!z){const V=new AbortController;z={ids:E,controller:V,waiters:0,promise:Promise.resolve(void 0)};const G=z;G.promise=p(S,E,L,V).finally(()=>{F.get(x)===G&&F.delete(x)}),F.set(x,G)}const H=z;return H.waiters+=1,new Promise((V,G)=>{let K=!1;function Z(Y){K||(K=!0,S.signal?.removeEventListener("abort",J),H.controller.signal.removeEventListener("abort",J),H.waiters-=1,H.waiters===0&&H.controller.abort(),Y())}function J(){Z(()=>G(Dt()))}S.signal?.addEventListener("abort",J,{once:!0}),H.controller.signal.addEventListener("abort",J,{once:!0}),H.promise.then(Y=>Z(()=>{try{I(S.signal??new AbortController().signal,E,L),V(C.clone(Y))}catch(ie){G(ie)}}),Y=>Z(()=>G(Y)))})}function A(S,E){if(E&&E!==_)return;const L=R=>S.every((x,z)=>R[z]===x);for(const[R,x]of k)L(x.entry.address.scopeIds)&&k.delete(R);for(const[R,x]of F)L(x.ids)&&(x.controller.abort(),F.delete(R));for(const[R,x]of j)L(x)&&R.abort()}function O(){if(!g){g=!0,k.clear();for(const S of j.keys())S.abort();j.clear();for(const S of F.values())S.controller.abort();F.clear(),s.delete(O),a.delete(A),o.get(_)?.cache===M&&o.delete(_)}}const M={read:T,invalidateScope:S=>h(S,_),dispose:O};return s.add(O),a.add(A),o.set(_,{definition:{namespace:_,codec:C,policy:N},sourceCodec:w.codec,cache:M}),M}return{createScope(w,v){if(c||!w)throw new Error("Invalid runtime cache scope");const N=Object.freeze({});return r.set(N,[...v?u(v):[],w]),N},register:y,invalidateScope:w=>h(w),dispose(){if(!c){c=!0;for(const w of[...s])w();o.clear(),n.clear(),i.clear()}}}}function kf(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 xf=".hb-runtime-cache-v1",Uf=1e3,Ri=64*1024,St=1e3,jf=2048,tr=32*1024*1024,zf=1024,on=new TextEncoder,Bs=new TextDecoder("utf-8",{fatal:!0});function rr(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Yr(e){const t=await globalThis.crypto.subtle.digest("SHA-256",on.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function ke(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Gs(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function Hf(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function Qs(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function Ff(e,t){const r=e.sandbox.directory(xf),n=r.directory("revisions"),i=r.directory("entries");for(const p of[r,n,i,i.directory("capability-check")])Qs(p,["directory","file","create","stat","list","remove"]),Qs(p.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(p){d=p,o.abort(),t.signal.removeEventListener("abort",s)}function f(p){if(Hf(p))throw u(p),p}function l(){if(d)throw d;if(a.signal.aborted)throw rr()}function h(p,T=a.signal){const A=c.then(()=>{if(T.aborted)throw d??rr();return l(),p()},()=>{if(T.aborted)throw d??rr();return l(),p()}).catch(E=>{throw f(E),E});if(c=A.catch(()=>{}),T.aborted)return Promise.reject(d??rr());let O=()=>{};const M=new Promise((E,L)=>{const R=()=>L(d??rr());T.addEventListener("abort",R,{once:!0}),O=()=>T.removeEventListener("abort",R)}),S=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},Uf);return Promise.race([A,M]).finally(()=>{clearTimeout(S),O()})}async function y(){l(),await n.create({recursive:!0,exclusive:!1},a),l(),await i.create({recursive:!0,exclusive:!1},a),l()}async function w(p,T){const A=n.file(`${await Yr([p,T??null])}.revision`);await N(A);let O=!1;try{await A.create({recursive:!1,exclusive:!0},a),O=!0}catch(E){f(E),l()}if(O){const E=Gs();return await A.write(on.encode(E),a),l(),E}const M=await A.stat(a);if(M.size<1||M.size>128)throw new Error("缓存 revision 文件损坏");const S=Bs.decode(await A.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(S))throw new Error("缓存 revision 文件损坏");return l(),S}async function v(p){const T=await p.list({limit:St},a);if(T.length>=St)throw new Error("缓存目录超过治理上限");return T}async function N(p){try{await p.stat(a);return}catch(A){if(!qr(A))throw A}if((await v(n)).length>=St-1)throw new Error("缓存 metadata 超过治理上限")}async function C(p,T){await y();const A=[];for(let O=0;O<p.length;O+=1){const M=p.slice(0,O+1);A.push(await w(M),await w(M,T))}return A}async function _(p){return r.directory(`entries/${await Yr([p.namespace,p.codecVersion,p.scopeIds])}`)}async function k(p){return(await _(p)).file(`${await Yr(p.key)}.cache`)}async function F(p,T){const A=await p.stat(a);if(A.size<5||A.size>T+Ri+4)throw new Error("缓存条目超过大小限制");const O=await p.read(a);if(l(),O.length!==A.size)throw new Error("缓存条目读取不完整");const M=new DataView(O.buffer,O.byteOffset,O.byteLength).getUint32(0);if(M<1||M>Ri||M+4>O.length)throw new Error("缓存信封损坏");const S=JSON.parse(Bs.decode(O.subarray(4,M+4))),E=O.slice(M+4);if(S.envelopeVersion!==1||!S.address||!Array.isArray(S.address.scopeIds)||!S.address.scopeIds.every(L=>typeof L=="string")||typeof S.address.namespace!="string"||typeof S.address.codecVersion!="string"||typeof S.address.key!="string"||!Array.isArray(S.revisions)||S.revisions.length!==S.address.scopeIds.length*2||!S.revisions.every(L=>typeof L=="string"&&L.length>0)||!Number.isSafeInteger(S.cachedAt)||!Number.isSafeInteger(S.expiresAt)||S.cachedAt<0||S.expiresAt<=S.cachedAt||S.payloadBytes!==E.length||E.length>T)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:S.address,revisions:S.revisions,cachedAt:S.cachedAt,expiresAt:S.expiresAt,payload:E}}async function j(p){if(!p.remove)throw new Error("Host 不支持缓存文件删除");await p.remove(a)}async function g(p){try{if((await p.file.stat(a)).size!==p.size)return!1;const T=await F(p.file,tr);return!ke(T.address,p.entry.address)||!ke(T.revisions,p.entry.revisions)||T.cachedAt!==p.entry.cachedAt||T.expiresAt!==p.entry.expiresAt||!ke(await I(T.payload),await I(p.entry.payload))?!1:(await j(p.file),!0)}catch(T){if(qr(T))return!0;throw T}}async function I(p){const T=await globalThis.crypto.subtle.digest("SHA-256",p);return Array.from(new Uint8Array(T),A=>A.toString(16).padStart(2,"0")).join("")}async function b(){const p=await v(n);let T=0;for(const S of p)if(S.kind==="file"&&(T+=(await S.stat(a)).size,T>tr))throw new Error("缓存扫描超过字节上限");const A=[];let O=0,M=T;for(const S of await v(i)){if(S.kind!=="directory")throw new Error("缓存目录结构损坏");for(const E of await v(S)){if(E.kind!=="file"||++O>jf)throw new Error("缓存文件超过治理上限");const L=(await E.stat(a)).size;if(M+=L,M>tr)throw new Error("缓存扫描超过字节上限");try{const R=await F(E,tr);A.push({file:E,entry:R,size:(await E.stat(a)).size,bucketName:S.name})}catch(R){f(R),l(),qr(R)||await j(E)}}}return{entries:A,metadataBytes:T}}async function D(){for(const p of await v(i))if(p.kind==="directory"&&p.remove&&(await v(p)).length===0)try{await p.remove({recursive:!1},a)}catch(T){f(T),l()}}function P(p){const{payload:T,...A}=p,O=on.encode(JSON.stringify({...A,payloadBytes:T.length}));if(O.length>Ri)throw new Error("缓存信封过大");const M=new Uint8Array(4+O.length+T.length);return new DataView(M.buffer).setUint32(0,O.length),M.set(O,4),M.set(T,O.length+4),M}return{readRevisions:(p,T)=>h(()=>C(p,T)),read:(p,T)=>h(async()=>{l();const A=await k(p);let O;try{O=await F(A,T)}catch(M){if(l(),qr(M))return;throw M}if(!(!ke(O.address,p)||O.expiresAt<=Date.now())&&ke(O.revisions,await C(p.scopeIds,p.namespace)))return O}),publish:(p,T)=>h(async()=>{l();const{address:A}=p;if(!ke(p.revisions,await C(A.scopeIds,A.namespace)))return!1;const O=P(p);if(p.payload.length>T.maxEntryBytes||O.length>T.diskMaxBytes||T.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await y();const M=await _(A),S=await k(A),E=await b(),L=[],R=new Map;for(const H of E.entries){if(H.bucketName===M.name&&H.file.name===S.name)continue;const V=JSON.stringify([H.entry.address.scopeIds,H.entry.address.namespace]);let G=R.get(V);if(G||(G=await C(H.entry.address.scopeIds,H.entry.address.namespace),R.set(V,G)),H.entry.expiresAt<=Date.now()||!ke(H.entry.revisions,G)){if(!await g(H))throw new Error("缓存治理期间条目已变化")}else L.push(H)}L.sort((H,V)=>H.entry.cachedAt-V.entry.cachedAt);function x(){const H=L.filter(V=>V.bucketName===M.name);return L.length+1>zf||O.length+E.metadataBytes+L.reduce((V,G)=>V+G.size,0)>tr||H.length+1>Math.min(T.diskMaxEntries,St-1)||O.length+H.reduce((V,G)=>V+G.size,0)>T.diskMaxBytes}for(;x();){const H=L.filter(K=>K.bucketName===M.name),G=H.length+1>Math.min(T.diskMaxEntries,St-1)||O.length+H.reduce((K,Z)=>K+Z.size,0)>T.diskMaxBytes?H[0]:L[0];if(!G||!await g(G))throw new Error("缓存容量不足或条目已变化");L.splice(L.indexOf(G),1)}await D();const z=await v(i);if(!z.some(H=>H.name===M.name)&&z.length>=St-1)throw new Error("缓存目录超过治理上限");if(await M.create({recursive:!0,exclusive:!1},a),!ke(p.revisions,await C(A.scopeIds,A.namespace)))return!1;try{await S.create({recursive:!1,exclusive:!0},a)}catch(H){f(H),await S.stat(a)}return await S.write(O,a),l(),ke(p.revisions,await C(A.scopeIds,A.namespace))}),invalidate:(p,T)=>h(async()=>{await y();const A=n.file(`${await Yr([p,T??null])}.revision`);await N(A);try{await A.create({recursive:!1,exclusive:!0},a)}catch(O){f(O),await A.stat(a)}await A.write(on.encode(Gs()),a),l();try{const{entries:O}=await b();for(const M of O){if(T!==void 0&&M.entry.address.namespace!==T||!p.every((E,L)=>M.entry.address.scopeIds[L]===E))continue;const S=await C(M.entry.address.scopeIds,M.entry.address.namespace);ke(M.entry.revisions,S)||await g(M)}await D()}catch(O){f(O),l()}})}}function qr(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const Vf="RATE_LIMITED_BY_RUNTIME",Bf="RATE_LIMITED",Ed=20,wd=40,Id=150,Ad=20,Md=1e4,Nd=45e3,Dd=1,Gf=300*1e3,Qf=64;function Tt(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Yf(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function qf(e={}){const t=e.now??Date.now,r=Yf(e.coalesceWindowMs,Id),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,Tt(e.budget?.ratePerSecond,Ed)),burst:Math.max(1,Math.floor(Tt(e.budget?.burst,wd)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(Tt(e.loopDetection?.maxCalls,Ad))),windowMs:Math.max(1,Math.floor(Tt(e.loopDetection?.windowMs,Md)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(Tt(e.circuitBreaker?.failureThreshold,Dd))),openMs:Math.max(1,Math.floor(Tt(e.circuitBreaker?.openMs,Nd)))},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(g){try{e.onReport?.(g)}catch{}}function y(g,I){if(!i)return{exceeded:!1,count:0};const b=a.get(g)??[],D=I-i.windowMs;let P=0;for(;P<b.length&&b[P]<=D;)P+=1;P>0&&b.splice(0,P);const p=b.length>=i.maxCalls;return p||(b.push(I),b.length>i.maxCalls+1&&b.splice(0,b.length-(i.maxCalls+1))),a.set(g,b),{exceeded:p,count:b.length}}function w(g){if(!n)return!0;const I=Math.max(0,g-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+I*n.ratePerSecond),u.updatedAt=g,u.tokens<1?!1:(u.tokens-=1,!0)}function v(g){if(!n)return 0;const I=Math.max(0,g-u.updatedAt)/1e3,b=Math.min(n.burst,u.tokens+I*n.ratePerSecond);return Math.max(0,Math.ceil((1-b)/n.ratePerSecond*1e3))}function N(g,I,b,D,P){if(!o)return;const p=d.get(I),T=(p?.open?0:p?.failures??0)+1;if(T<o.failureThreshold){d.set(I,{open:!1,openedAt:0,openMs:0,failures:T});return}const A=Math.min(Math.max(o.openMs,D),Gf);d.set(I,{open:!0,openedAt:P,openMs:A,failures:T}),f.circuitOpened+=1,h({type:"circuit_opened",capability:g,endpointId:I,status:b,openMs:A,timestamp:P})}function C(g){const I=d.get(g);I&&!I.open&&d.delete(g)}function _(g){for(const[I,b]of s)!b.pending&&b.expiresAt<=g&&s.delete(I);for(;s.size>=Qf;){const I=[...s].find(([,b])=>!b.pending);if(!I)break;s.delete(I[0])}}function k(g,I){if(g===void 0)return;const b=s.get(g);b?.promise===I&&(b.pending=!1)}function F(g,I){if(g===void 0)return;s.get(g)?.promise===I&&s.delete(g)}async function j(g){if(l)return g.load();const I=t();if(o){const p=d.get(g.endpointId);if(p?.open){const T=p.openedAt+p.openMs-I;if(T>0)throw f.circuitRejected+=1,h({type:"circuit_rejected",capability:g.capability,endpointId:g.endpointId,retryAfterMs:T,timestamp:I}),Kf("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:g.endpointId,retryAfterMs:T});d.delete(g.endpointId)}}const b=y(g.endpointId,I);b.exceeded&&i?c.has(g.endpointId)||(c.add(g.endpointId),h({type:"loop_detected",capability:g.capability,endpointId:g.endpointId,count:b.count,windowMs:i.windowMs,timestamp:I})):c.delete(g.endpointId);const D=r>0?g.coalesceKey:void 0;if(D!==void 0){const p=s.get(D);if(p&&(p.pending||p.expiresAt>I))return f.coalesced+=1,h({type:"coalesced",capability:g.capability,endpointId:g.endpointId,timestamp:I}),p.promise;p&&s.delete(D)}if(b.exceeded&&i)throw f.loopRejected+=1,Ys("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:g.capability,endpointId:g.endpointId,count:b.count,windowMs:i.windowMs});if(!w(I)){f.budgetRejected+=1;const p=v(I);throw h({type:"budget_exhausted",capability:g.capability,endpointId:g.endpointId,retryAfterMs:p,timestamp:I}),Ys("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:g.capability,endpointId:g.endpointId,retryAfterMs:p})}D!==void 0&&_(I);const P=g.load().then(p=>(k(D,P),C(g.endpointId),p),p=>{F(D,P);const T=$f(p);throw T!==void 0&&N(g.capability,g.endpointId,T,Wf(p),I),p});return D!==void 0&&s.set(D,{endpointId:g.endpointId,promise:P,expiresAt:I+r,pending:!0}),P}return{execute:j,invalidateCoalescing(g){if(g===void 0){s.clear();return}for(const[I,b]of s)g.includes(b.endpointId)&&s.delete(I)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,g])=>g.open).map(([g])=>g)}},dispose(){l||(l=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function $f(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 Wf(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 Ys(e,t){return{code:Vf,message:e,data:t}}function Kf(e,t){return{code:Bf,message:e,data:t}}const Sd=3e4,Td=6e4,Do=1440*60*1e3;function Zf(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??Sd)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??Td)):0,steamGameListTtlMs:t?Jf(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:Ed,burst:wd},coalesceWindowMs:r?.coalesceWindowMs??Id,loopDetection:r?.loopDetection??{maxCalls:Ad,windowMs:Md},circuitBreaker:r?.circuitBreaker??{failureThreshold:Dd,openMs:Nd}}}}function Jf(e){return e===void 0||!Number.isFinite(e)?Do:Math.max(0,Math.floor(e))}function Xf(e){return typeof e=="object"&&e!==null}function ae(e,t){const r=e.data;if(!Xf(r)||typeof r.status!="string")throw new Error(t);return r}const _d={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},eh={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 ae(e,"工坊小程序详情加载失败")}};function Ur(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function th(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function rh(e){const t=ae(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=th(r.consent_challenge)),{...t,result:n}}const nh={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=>({...Ur(e.runtimeContext),challenge:e.challenge}),parse:e=>ae(e,"小程序授权取消接口响应异常")},ih={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=>Ur(e.runtimeContext),parse:e=>ae(e,"小程序授权撤销接口响应异常")},oh={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=>Ur(e.runtimeContext),parse(e){const t=ae(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}:{}}}}},sh={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=>({...Ur(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>rh(e)},ah={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=>({...Ur(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=ae(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},ch=64;function bd(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??ch)),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 y=n();for(c(y),i.delete(f);i.size>=r;){const w=i.keys().next();if(w.done)break;i.delete(w.value)}i.set(f,{expiresAt:y+t,value:l})}function u(f,l){if(a)return l();if(t>0){const v=i.get(f);if(v&&v.expiresAt>n())return Promise.resolve(v.value);v&&i.delete(f)}const h=o.get(f);if(h)return h;const y=s,w=l().then(v=>(d(f,v,y),v)).finally(()=>{o.get(f)===w&&o.delete(f)});return o.set(f,w),w}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 dh(e,t){return t?e?"server":"local":"legacy"}function uh(e,t){if(e==="local")throw m("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const lh=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],fh=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),hh=/authorization|cookie|pkey|password|secret|token/i,Od=/authorization|cookie|pkey|token|password|secret/i;function xe(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function mh(e){for(const t of Object.keys(e))if(!fh.has(t))throw new le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of lh)if(Object.prototype.hasOwnProperty.call(e,t)&&xe(e,t)!==void 0)throw new le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(xe(e,"bodyEncoding")!==void 0&&xe(e,"bodyEncoding")!=="json"&&xe(e,"bodyEncoding")!=="form")throw new le("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(xe(e,"failurePresentation")!==void 0&&xe(e,"failurePresentation")!=="none")throw new le("endpoint failurePresentation 必须为 none");if(xe(e,"auth")!==void 0&&xe(e,"auth")!=="none"&&xe(e,"auth")!=="optional"&&xe(e,"auth")!=="required")throw new le("endpoint auth 必须为 none、optional 或 required")}function hr(e){if(Array.isArray(e))return e.map(hr);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))hh.test(n)||(r[n]=hr(i));return r}function qs(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Od.test(r)||(t[r]=n);return t}function gh(e){if(!e)return;const t=Object.keys(e).find(r=>Od.test(r));if(t)throw new le(`endpoint 禁止声明 credential-bearing header: ${t}`)}class jr 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 $s=1440*60*1e3,ph=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function yh(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,$s):void 0}if(!ph.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,$s):void 0}function Eh(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 vd(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class Bt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,vd(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class zr extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,vd(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function wh(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:hr(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:qs(o),method:e.method,metadata:{endpointId:e.id},query:hr(n),timeout:e.timeout,url:r},data:hr(a.data),headers:qs(a.headers)||{},status:a.status,statusText:a.statusText}}async function Mi(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(mh(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;gh(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 Bt({endpointId:t.id,cause:h})}if(f.status<200||f.status>=300)throw new jr({endpointId:t.id,status:f.status,responseData:f.data,retryAfterMs:yh(f.headers)});const l=wh(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(l,r)}catch(h){throw new zr({endpointId:t.id,cause:h})}return l.data},d=n.gate;if(!d)return c();const u=Eh(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const Ih=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),Ah=new Set(Vt),cs="steam_account",Cd=new Set(Vt.filter(e=>e!==cs)),Mh=1e3;function Nh(e){const t=new Set,r=bd({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??Sd))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??dh(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 m("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let E;try{E=await e.authorizationContext.get(e.operationContext)}catch(R){throw To(R)?Pi(R.code,R.message,R):Pi("REQUEST_FAILED","读取 Runtime auth context 失败",R)}if(E.steamAccount!==c||E.userDataMode!==d)throw m("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const L=E.token.trim();if(!L)throw m("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:L}}const h=e.account.onChange(E=>{if(y(),w("heybox_app_login_change",E?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),E&&e.account.getAccountKey){const L=i;F().then(R=>{!o&&i===L&&w("heybox_app_login_change",R)}).catch(()=>{})}});function y(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function w(E,L){E==="user_info_authorization_change"&&Oh(L)&&r.invalidate();for(const R of t)try{R(E,L)}catch{}}function v(){const E=e.identity.get()?.miniProgramId?.trim();if(!E)throw m("INVALID_STATE","当前能力缺少 canonical 小程序身份");return E}function N(){if(o||e.operationContext.signal.aborted)throw m("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function C(){N();let E;try{E=await e.account.getCurrentUserId(e.operationContext)}catch(L){throw Js(L,e.operationContext.signal,"读取小黑盒账号失败")}return typeof E=="string"&&E.trim()?E.trim():void 0}async function _(E,L){const R=await C();if(i!==L||R!==E)throw m("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function k(E,L,R=v()){if(!e.account.getAccountKey)throw m("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let x;try{x=await e.account.getAccountKey(R,E,e.operationContext)}catch{throw N(),m("REQUEST_FAILED","读取本地账号标识失败")}if(await _(E,L),v()!==R)throw m("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof x!="string"||!x.trim())throw m("INVALID_RESPONSE","Host 返回了无效的账号标识");return x}async function F(){const E=v(),L=i,R=await C();if(N(),i!==L)throw m("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return R?{isHeyboxAppLoggedIn:!0,accountKey:await k(R,L,E)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function j(E){N();try{await e.account.ensureAuthenticated({trustedUserGesture:E,reason:"runtime_auth",signal:e.operationContext.signal})}catch(R){throw Js(R,e.operationContext.signal,"小黑盒登录失败")}const L=await C();if(!L)throw m("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return L}async function g(E,L,R=e.operationContext.signal){try{if(R.aborted)throw So();return await bh(Mi(e.network,E,L,{...e.operationContext,credentials:"heybox-session",signal:R,...f?{gate:f}:{}}),R)}catch(x){throw e.operationContext.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):x instanceof le?m("REQUEST_UNSUPPORTED",x.message):x instanceof zr?m("INVALID_RESPONSE","授权接口响应不合法"):x instanceof Bt?m("REQUEST_FAILED","授权请求失败"):x instanceof jr?u&&(x.status===403||x.status===429)?m("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:x.status,...x.retryAfterMs===void 0?{}:{retryAfterMs:x.retryAfterMs}}):m("REQUEST_FAILED",x.message):To(x)?x:m("REQUEST_FAILED","授权请求失败")}}async function I(E,L){await g(nh,{runtimeContext:{miniProgramId:E,...await l()},challenge:L}).catch(()=>{})}function b(E){const L=async()=>{const x=Ks(e.operationContext.signal);a=x;try{return await E(x.signal)}finally{a===x&&(a=void 0),x.abort()}},R=s.then(L,L);return s=R.then(()=>{},()=>{}),R}async function D(E,L,R,x,z){if(!R)throw await I(E,L.challenge),m("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await I(E,L.challenge),m("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return b(async H=>{await _(x,z);const V=await P(E,L.displayedScopes,H);await _(x,z);let G;try{G=await e.authPresentation.confirmAuthorization({miniProgramId:E,scopes:L.displayedScopes,...V,signal:H})}catch(Z){throw e.operationContext.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await _(x,z),await I(E,L.challenge),Pi("REQUEST_FAILED","授权确认界面执行失败",Z))}if(await _(x,z),G.status!=="granted")throw await I(E,L.challenge),m("AUTHORIZATION_CANCELLED","用户取消授权");const K=Th(G.grantedScopes,L.displayedScopes,c);if(!K.includes("identity"))throw await I(E,L.challenge),m("AUTHORIZATION_CANCELLED","用户拒绝授权");return K})}async function P(E,L,R){const x=Ks(R),z=setTimeout(()=>x.abort(),Mh);try{const H=_h(e.miniProgramPresentation),[V,G]=await Promise.all([H?Promise.resolve(H):p(E,x.signal),L.includes("profile")?T(x.signal):Promise.resolve(void 0)]);return{...V?{miniProgram:V}:{},...G?{userProfile:G}:{}}}finally{clearTimeout(z),x.abort()}}async function p(E,L){try{const R=e.identity.get()?.version?.trim(),x=await g(eh,{mini_program_id:E,...R?{miniprogram_version:R}:{}},L),z=_t(x,"小程序公开资料"),H=Pt(z.name),V=Pt(z.icon_url);return H||V?{...H?{name:H}:{},...V?{avatarUrl:V}:{}}:void 0}catch{return}}async function T(E){try{const L=await g(_d,void 0,E),R=_t(L,"账号基础信息"),x=Pt(R.display_username),z=Pt(R.display_avatar);return x||z?{...x?{nickname:x}:{},...z?{avatar:z}:{}}:void 0}catch{return}}async function A(E,L){if(uh(d,"auth.login"),!c&&E.includes(cs))throw m("INVALID_PARAMS","auth.login 参数不合法");const R=v(),x=await j(L),z=i,H=await g(sh,{runtimeContext:{miniProgramId:R,...await l()},scopes:E});await _(x,z);const V=_t(H,"小程序登录"),G=Zs(V,"loginCode"),K=Zs(V,"consentChallenge");if(G===K)throw m("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let Z;if(G)Z=Ws(V.loginCode,c);else{const Y=Dh(V.consentChallenge,c),ie=await D(R,Y,L,x,z);await _(x,z);const Pe=await g(ah,{runtimeContext:{miniProgramId:R,...await l()},challenge:Y.challenge,selectedScopes:ie});if(await _(x,z),Z=Ws(_t(Pe,"小程序登录确认"),c),Z.scopes.some(ge=>!ie.includes(ge)))throw m("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const Y of Z.scopes)n.add(Y);r.invalidate();const J=e.account.getAccountKey?await k(x,z,R):void 0;return w("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...J===void 0?{}:{accountKey:J}}),w("user_info_authorization_change",ki(n,c)),{...Z,...J===void 0?{}:{accountKey:J}}}async function O(E,L){const R=i,x=await g(oh,{runtimeContext:{miniProgramId:L,...await l()}});await _(E,R);const z=Sh(_t(x,"用户本地身份"),c);for(const H of c?Vt:Cd)n.add(H);return w("user_info_authorization_change",ki(n,c)),z}function M(E){N();const L=v(),R=`${E}\0${L}\0${i}\0${c}`;return r.read(R,()=>O(E,L))}async function S(E){if(!E)throw m("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const L=v(),R=i,x=await C();if(!x)throw m("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const z=await g(ih,{runtimeContext:{miniProgramId:L,...await l()}});await _(x,R),_t(z,"用户授权撤销"),y(),w("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:F,login:A,async confirmGameSaves(E){if(!E)throw m("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw m("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const L=v(),R=await j(E),x=i;await b(async z=>{await _(R,x);const H=await P(L,["identity"],z),V=await e.authPresentation.confirmAuthorization({miniProgramId:L,scopes:["identity","game_saves"],...H,signal:z});if(await _(R,x),V.status!=="granted"||!V.grantedScopes.includes("game_saves")||!V.grantedScopes.includes("identity"))throw m("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:M,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>ki(n,c),revoke:S,onEvent(E){return t.add(E),()=>t.delete(E)},dispose(){o||(o=!0,y(),r.dispose(),h(),t.clear())}}}function Pi(e,t,r){const n=m(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function _t(e,t){if(!Q(e))throw m("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":Ih.has(r)?r:"REQUEST_FAILED";throw m(n,r)}if(!Q(e.result))throw m("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Ws(e,t){if(!Q(e))throw m("INVALID_RESPONSE","login code 必须是对象");const r=Jn(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 m("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function Dh(e,t){if(!Q(e))throw m("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Jn(e.requestedScopes,"challenge requestedScopes",t),n=Jn(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 m("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function Sh(e,t){if(!Q(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw m("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw m("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 Th(e,t,r){const n=Jn(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw m("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Pt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function _h(e){const t=Pt(e?.name),r=Pt(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Ks(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 bh(e,t){return t.aborted?Promise.reject(So()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(So()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function So(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Jn(e,t,r){const n=r?Ah:Cd;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw m("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function ki(e,t){const r=t?Vt:Vt.filter(n=>n!==cs);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function Zs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Oh(e){return Q(e)?Object.values(e).some(t=>t==="denied"):!1}function To(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Js(e,t,r){return t.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):To(e)?e:m("REQUEST_FAILED",r)}const vh=new Set(Vt);function Ch(e){return{[wn]:async t=>{if(t!==void 0)throw m("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[In]:async(t,r)=>e.authorization.login(Lh(t),r.trustedUserGesture)}}function Lh(e){if(e===void 0)return["identity"];if(!Q(e)||Object.keys(e).some(t=>t!=="scopes"))throw Xs();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!vh.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Xs();return[...e.scopes]}function Xs(){return m("INVALID_PARAMS","auth.login 参数不合法")}const Rh={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 ae(e,"排行榜记录删除接口响应异常")}},Ph={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 ae(e,"当前排行榜记录接口响应异常")}},kh={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 ae(e,"排行榜信息接口响应异常")}},xh={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 ae(e,"排行榜列表接口响应异常")}},Uh={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 ae(e,"排行榜提交接口响应异常")}},jh={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 ds(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await $(()=>Mi(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(ti(i)||dr(i,"REQUEST_UNSUPPORTED")||dr(i,"RATE_LIMITED")||dr(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof le)throw B("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof Bt&&dr(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof jr){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw B("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw B("UNAUTHORIZED","当前用户未登录");const o=zh(i.responseData);if(te(o)&&typeof o.status=="string"&&o.status!=="ok"){const s=te(o.result)?Ge(o.result.error_code):void 0;if(o.status==="login"||o.status==="relogin"||Xn(o.result)||Xn(o)||s&&/^[A-Z][A-Z0-9_]+$/.test(s))throw Ld(o,e.subject)}throw B("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof Bt?ei(e.subject):i instanceof zr?re(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):re(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function Fe(e,t,r){if(!te(e)||typeof e.status!="string")throw re(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Ld(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw re(`${t} 响应缺少 result`);return e.result}function us(e,t){try{return e.onChange(t)}catch(r){if(dr(r,hd))return()=>{};throw r}}function Ld(e,t){if(e.status==="login"||e.status==="relogin")throw B("UNAUTHORIZED",Ge(e.msg)||"当前用户未登录");if(te(e.result)){const i=Ge(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw B(i,Ge(e.result.message)||Ge(e.msg)||`${t}请求失败`)}const r=Xn(e.result)??Xn(e),n=Ge(r?.user_message)||Ge(e.msg)||Ge(r?.developer_message)||`${t}请求失败`;throw r?B(Hh(r),n,{status:e.status,sbe:r}):B("HEYBOX_API_ERROR",n,{status:e.status})}function zh(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function Xn(e){return te(e)&&te(e.sbe)?e.sbe:void 0}function Hh(e){const t=Ge(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 jh[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 te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function dr(e,t){return te(e)&&e.code===t}function B(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function re(e){return B("INVALID_RESPONSE",e)}function ei(e){return B("REQUEST_FAILED",`${e}请求失败`)}function ti(e){return e instanceof Error&&e.name==="AbortError"}const Fh="default",ot="排行榜",Vh=/^[A-Za-z0-9_-]{1,64}$/,Bh=300*1e3,Gh=250,Qh=3;class Yh{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=us(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(Uh,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=Fe(i,Qe,ot);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),xi(o,Qe)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=nr("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(xh,{miniProgramId:r,...t}),s=Fe(o,Oe,ot);if(!te(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw re(`${Oe} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw re(`${Oe} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>xi(a,Oe)),...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=nr("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(Ph,{miniProgramId:n,...t}),c=Fe(a,et,ot);if(!te(c))throw re(`${et} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:xi(c.entry,et)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Rh,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=Fe(i,yt,ot);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!te(o)||typeof o.deleted!="boolean")throw re(`${yt} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",nr("info"),async()=>{const i=await this.request(kh,{miniProgramId:r,...t}),o=Fe(i,He,ot);if(!te(o)||typeof o.key!="string"||!Vh.test(o.key))throw re(`${He} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw re(`${He} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw re(`${He} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw re(`${He} 返回的 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=nr(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>=Gh&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Bh,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>=Qh)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)ea(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){ea(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await $(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw ti(n)?n:ei(ot)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw B("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw B("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return nr(t,r??Fh)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw B("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return ds({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:ot,assertUsable:()=>this.assertUsable()},t,r)}dispose(){this.disposed||(this.disposed=!0,this.accountGeneration+=1,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.buckets.clear(),this.inflight.clear())}assertUsable(){if(X(this.options.operationContext.signal),this.disposed)throw B("INVALID_STATE","Cloud capability 已释放")}}function qh(e){return new Yh(e)}function xi(e,t){if(!te(e))throw re(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw re(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw re(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw re(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw re(`${t} 返回的 score 必须是有限数字`);if(!te(e.extra))throw re(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw re(`${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 ea(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function nr(...e){return JSON.stringify(e)}const $h={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 ae(e,"云端存储删除接口响应异常")}},ta={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 ae(e,"云端存储读取接口响应异常")}},ra={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 ae(e,"云端存储 key 列表接口响应异常")}},Wh={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 ae(e,"云端存储写入接口响应异常")}},st="云端存储",Kh=3e4,Zh=128,Jh=500;class Xh{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=us(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=Fe(await this.request(ra,{}),Et,st);if(this.assertAccountGeneration(t),!te(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw re("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"?Jh: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=Fe(await this.request($h,{key:t}),Ht,st);if(this.assertAccountGeneration(r.generation),!te(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw re("删除结果不合法");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 re("云存储版本超出安全整数范围");const o=Fe(await this.request(Wh,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),zt,st);if(this.assertAccountGeneration(r.generation),!te(o)||o.success!==!0)throw re("云存储写入结果不合法");const s=na({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw re("写入版本凭证不匹配");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(ta,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=na(Fe(c,jt,st));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>=Zh&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+Kh,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([ta.id,ra.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(B("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(B("UNAUTHORIZED","登录状态已变化,请重试")),this.options.requestGate?.invalidateCoalescing()}purge(t){this.accountGeneration+=1;for(const r of this.timers.values())clearTimeout(r);this.timers.clear();for(const r of[...this.unfinished])this.finish(r,t);this.queues.clear(),this.blockedKeys.clear(),this.cache.clear(),this.inflight.clear(),this.keyGenerations.clear(),this.boundScope=void 0,this.boundUserId=void 0}async requireCurrentUser(t){this.assertAccountGeneration(t);const r=this.readMiniProgramId();let n;try{n=await $(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw ti(o)?o:ei(st)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),B("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),B("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw B("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw B("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw B("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw B("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await $(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw ti(s)?s:ei(st)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw B("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return ds({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:st,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(X(this.options.operationContext.signal),this.disposed)throw B("INVALID_STATE","Cloud capability 已释放")}}function em(e){return new Xh(e)}function na(e){if(!te(e))throw re("云存储读取结果必须是对象");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 re("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw re("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const tm=/^[A-Za-z0-9_-]{1,64}$/,ia=20,rm=100,oa=2048,nm=/^[A-Za-z0-9_-]{1,128}$/,sa=16*1024;function im(e){const t=qh(e),r=em(e);return{handlers:{[Qe]:async i=>t.submit(om(i)),[Oe]:async i=>t.getList(sm(i)),[et]:async i=>t.getCurrentUserEntry(Ui(i,et)),[yt]:async i=>t.deleteCurrentUserEntry(Ui(i,yt)),[He]:async i=>t.getInfo(Ui(i,He)),[jt]:async i=>r.getItem(aa(i,jt)),[zt]:async i=>{const{key:o,value:s}=am(i);return r.setItem(o,s)},[Ht]:async i=>r.removeItem(aa(i,Ht)),[Et]:async i=>(dm(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function om(e){const t=Zt(e,Qe,!1);if(Jt(t,["key","score","extra"],Qe),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw Ee("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...ls(t.key,Qe),score:t.score,...t.extra===void 0?{}:{extra:um(t.extra)}}}function sm(e){if(e===void 0)return{limit:ia};const t=Zt(e,Oe,!0);Jt(t,["key","limit","cursor"],Oe);const r=t.limit===void 0?ia:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>rm)throw Ee("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw Ee("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...ls(t.key,Oe),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Ui(e,t){if(e===void 0)return{};const r=Zt(e,t,!0);return Jt(r,["key"],t),ls(r.key,t)}function aa(e,t){const r=Zt(e,t,!1);return Jt(r,["key"],t),Rd(r.key,t)}function am(e){const t=zt,r=Zt(e,t,!1);Jt(r,["key","value"],t);const n=Rd(r.key,t);if(typeof r.value!="string")throw Ee("INVALID_PARAMS",`${t} value 必须是字符串`);if(cm(r.value))throw Ee("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>sa)throw Ee("INVALID_PARAMS",`${t} value 不能超过 ${sa} 字节`);return{key:n,value:r.value}}function cm(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 dm(e){const t=Zt(e,Et,!0);Jt(t,[],Et)}function Rd(e,t){if(typeof e!="string"||!nm.test(e))throw Ee("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function Zt(e,t,r){if(e===void 0&&r)return{};if(!Pd(e))throw Ee("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Jt(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Ee("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function ls(e,t){if(e===void 0)return{};if(typeof e!="string"||!tm.test(e))throw Ee("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function um(e){if(!Pd(e))throw Ee("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw Ee("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw Ee("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>oa)throw Ee("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${oa} 字节`);return e}function Pd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ee(e,t){return{code:e,message:t}}const lm={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 ae(e,"游戏存档接口响应异常")}};function kd(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw m("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 m("FILE_IO_FAILED","无法生成安全文件标识")}}function xd(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):_o,remove:o?s=>e.remove(s):jd,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):_o,stat:s=>e.stat(s)})}function Ud(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=>xd(e.file(a),n,{allowRemove:o}),directory:a=>Ud(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):_o,remove:s?(a,c)=>e.remove(a,c):jd,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function _o(){return Promise.reject(m("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function jd(){return Promise.reject(m("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const fm=new Set(["METHOD_FORBIDDEN","FILE_PICKER_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_ENCODING_INVALID","DIRECTORY_LIST_LIMIT_EXCEEDED","DIRECTORY_NOT_EMPTY","FILE_IO_FAILED"]),hm={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 vr(e){const t=fs(e),r=t&&fm.has(t)?m(t,hm[t]??"文件操作失败"):m("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Be(e){try{return e()}catch(t){throw vr(t)}}function fs(e){try{if(!Q(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const ca=1024;class hs{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new hs(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 $r(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Be(()=>{if(!Array.isArray(t))throw m("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw m("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>ca)throw m("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw m("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>$r(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 ua(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Ft(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!Ft(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}resolveFileEntry(t){this.assertCanonicalDetail();const r=gm(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Cr(r.relativePath);ji(n.origin,i);const o=this.prepareFile(Be(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=pm(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==="."?".":Cr(r.relativePath);ji(n.origin,i);const o=this.prepareDirectory(i==="."?n.hostHandle:Be(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return fa(t),$r(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Be(()=>{if(!Array.isArray(r))throw m("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw m("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw m("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&Q(a)&&typeof a.name=="string"&&zd(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Be(()=>{if(Q(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return $r(n.handle,da(t.ref,n.handle.name))}if(Q(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return ua(n.handle,mm(t.ref,n.handle.name))}throw m("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Hr(r);ji(t.origin,n);const i=this.prepareFile(Be(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:da(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw m("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Be(()=>{fa(t);const i=n??t.mode;return la(t.mode,i),{handle:xd(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Be(()=>{Em(t,i);const o=n??t.mode;return la(t.mode,o),{handle:Ud(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>ca)throw m("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=kd();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw m("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!ym(t))throw m("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw m("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw m("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw De("files.sandbox");return this.prepareDirectory(Be(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw m("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw De("files")}}function Cr(e){if(!os(e))throw m("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function ji(e,t){if(e==="sandbox"&&zd(t))throw m("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function zd(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function Hr(e,t="文件名"){const r=Cr(e);if(r.includes("/"))throw m("INVALID_PARAMS",`${t} 只能是 basename`);return r}function da(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Cr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function mm(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Cr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function $r(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function ua(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function la(e,t){if(t==="readwrite"&&e!=="readwrite")throw m("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function gm(e){return Ft(e)||Hd(),e}function pm(e){return id(e)||Hd(),e}function Hd(){throw m("INVALID_PARAMS","文件引用不合法")}function ym(e){return/^[0-9a-f]{32}$/.test(e)}function fa(e){if(!Q(e)||e.kind!=="file"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.create!="function"||typeof e.read!="function"||typeof e.write!="function"||typeof e.stat!="function")throw m("FILE_IO_FAILED","Host 返回了无效 File handle");Hr(e.name,"Host File name")}function Em(e,t=!1){if(!Q(e)||e.kind!=="directory"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.file!="function"||typeof e.directory!="function"||typeof e.create!="function"||typeof e.stat!="function"||typeof e.list!="function")throw m("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw m("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&Hr(e.name,"Host Directory name")}const wm=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Im=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Am=new Set(["range","if-range","a-im"]),Mm=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"]),Nm=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Wr={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Dm{constructor(t){this.signal=t}phase="initial";transition(t){if(Wr[t]<=Wr[this.phase])throw m("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Wr[this.phase]<Wr.committed&&this.signal.aborted)throw Bd()}normalizeHostError(t,r){return this.throwIfCancelled(),gs(t,r,this.signal)}}async function Fd(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw De("network.download");const o=Ne(r.operationContext,t.signal),s=new Dm(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await bm(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=vm(c);Cm(c,u);const f=Lm(c.status,u);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw m("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const l=Om(e,a,u,i);let h=0;const y=Tm(f.expectedBytes,e.maxBytes);Hi(t,zi(0,f));const w={...o,onProgress(C){!Number.isSafeInteger(C)||C<h||y!==void 0&&C>y||(h=C,Hi(t,zi(h,f)))}};s.transition("transfer"),d=!0;let v;try{v=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}},w)}catch(C){throw s.normalizeHostError(C,"transfer")}s.transition("committed"),h=Sm(v,f,h,e.maxBytes),Hi(t,zi(h,f));const N=i.describeFile(l.handle,l.ref);return s.transition("completed"),N}finally{d||_m(n.network,c.body)}}function Sm(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 Tm(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function _m(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function bm(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return bo(i.handle.mode),await zm(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return bo(n.handle.mode),await Hm(n.handle,r),{kind:"directory",...n}}function Om(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Pm(e,r),o=n.deriveFile(t,i);return bo(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function vm(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 m("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!Q(e.headers))throw m("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!wm.has(r)||!Array.isArray(n)||n.length===0)throw m("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw m("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Cm(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw m("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:jm(t,Im)});if((t["content-range"]?.length??0)>0)throw m("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Lm(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw m("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw m("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw m("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=Rm(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 Rm(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function zi(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Hi(e,t){try{e.postProgress(t)}catch{}}function Pm(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=km(i);if(o&&sn(o))return o}for(const i of r){const o=xm(i);if(o&&sn(o))return o}if(e.suggestedName!==void 0)return ms(e.suggestedName);const n=Um(e.url);return n&&sn(n)?n:"download.bin"}function km(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 xm(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 Um(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function ms(e){try{Hr(e,"suggestedName")}catch{throw m("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!sn(e))throw m("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function sn(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Nm.test(e))}function jm(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function zm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Vd()}catch(r){throw gs(r,"file",t.signal)}}async function Hm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Vd()}catch(r){throw gs(r,"file",t.signal)}}function bo(e){if(e!=="readwrite")throw m("FILE_ACCESS_DENIED","下载目标只允许读取")}const Fm={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 gs(e,t,r){if(r.aborted)return Bd();const n=Vm(e);if(n&&Mm.has(n)){const o=m(n,Fm[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?m("DOWNLOAD_TIMEOUT","下载网络请求超时"):m("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?m("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):m("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function Vm(e){return Q(e)&&typeof e.code=="string"?e.code:void 0}function Vd(){return m("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Bd(){return m("DOWNLOAD_CANCELLED","下载已取消")}function Bm(e){if(!e)return;const t=Object.keys(e).find(r=>Am.has(r.trim().toLowerCase()));if(t)throw m("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}function Oo(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=>Oo(r,t+1)):te(e)&&Object.values(e).every(r=>Oo(r,t+1))}function Gm(e,t){const r=t==="2358720"?"blackMythWukong":t==="3678970"?"taskbarHero":t==="4115450"?"phantomBladeZero":void 0;if(!r)return{status:"unsupported"};const n={status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}};if(!te(e))return n;if(e.status==="unsupported")return{status:"unsupported"};if(e.game!==r)return n;if(e.status==="empty")return{status:"empty"};if(e.status==="failed"){if(["UNAUTHORIZED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED"].includes(String(e.error_code)))throw B(String(e.error_code),"账号或授权已变化");return n}return e.status!=="ready"||!te(e.data)||!Oo(e.data)?n:{status:"ready",data:e.data}}function Qm(e){const t=new Map,r=new Map,n=a=>`hb_runtime_game_save_sync_v1_${[a.miniProgramId,a.userId,a.gameId].map(encodeURIComponent).join(":")}`;async function i(a,c,d){const u=n(a),f=r.get(u)??Promise.resolve();let l;const h=new Promise(w=>{l=w}),y=f.then(()=>h);r.set(u,y);try{return await $(()=>f,c.signal),X(c.signal),await d()}finally{l(),r.get(u)===y&&y.then(()=>{r.get(u)===y&&r.delete(u)})}}async function o(a,c){const d=n(a);if(t.has(d))return t.get(d);if(e)try{const u=await $(()=>e.getRaw(d,c),c.signal);if(!u)return;const f=JSON.parse(u);if(!f||typeof f!="object")return;const l=f;return l.version!==1||l.miniProgramId!==a.miniProgramId||l.userId!==a.userId||l.gameId!==a.gameId||typeof l.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(l.accountId)||typeof l.taskId!="string"||!/^[1-9][0-9]{0,19}$/.test(l.taskId)?void 0:(t.set(d,l),l)}catch{X(c.signal);return}}async function s(a,c,d){X(d.signal);const u=n(a),f=c?{...a,version:1,taskId:c}:void 0;if(t.set(u,f),!!e)try{await $(()=>e.setRaw(u,f?JSON.stringify(f):"",d),d.signal)}catch{X(d.signal)}}return{run:i,async get(a,c){const d=await o(a,c);if(d&&d.accountId!==a.accountId){await s(a,void 0,c);return}return d?.taskId},set:s,async remove(a,c,d){await i(a,d,async()=>{const u=await o(a,d);u?.taskId===c&&u.accountId===a.accountId&&await s(a,void 0,d)})},clear(a){for(const c of t.values())c&&i(c,a,()=>s(c,void 0,a)).catch(()=>{})}}}const Fi=8*1024*1024,ha=32*1024*1024,Ym=2e3,qm=5*6e4;function $m(e){const t=Qm(e.storage);let r=0,n=!1,i,o=0;const s=new Set,a={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},c=g=>g.remove(a),d=new Set;let u=new AbortController,f;const l=()=>{u.abort(),u=new AbortController,f=void 0},h=(g=!0)=>{g&&t.clear(a),r++,l();for(const I of d)I.abort();for(const I of s)c(I).catch(()=>{});s.clear(),o=0},y=us(e.account,g=>{i&&g!==i&&(h(),i=void 0)}),w=e.authorization.onEvent(()=>h());function v(g,I,b,D){if(N(b),D.signal.aborted||!g.account_id||!e.presentation?.showSteamLoginRequired)return;const P=`${g.account_id}:${g.game_id}:${g.task_id??"sync"}`;if(f!==P){f=P;try{e.presentation.showSteamLoginRequired({userId:I,accountId:g.account_id},Ne(e.operationContext,u.signal))}catch{}}}function N(g){if(n||e.operationContext.signal.aborted)throw B("RUNTIME_DESTROYED","小程序已关闭");if(g!==r)throw B("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function C(g,I,b){if(N(I),await e.account.getCurrentUserId(b)!==g)throw h(),B("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");N(I)}async function _(g,I,b,D){if(await C(I,b,D),!e.authorizationContext)throw B("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const P=await e.authorizationContext.get(D);if(!P.token||P.expiresAt<=Date.now())throw B("UNAUTHORIZED","小程序运行上下文已过期");const p=await ds({network:e.network,operationContext:D,subject:"游戏存档",assertUsable:()=>N(b),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},lm,{...g,runtime_auth_context_token:P.token});if(await C(I,b,D),p.status==="failed"&&te(p.result)&&p.result.error_code==="RECENT_SAVE_AVAILABLE")throw B("RECENT_SAVE_AVAILABLE",typeof p.msg=="string"&&p.msg?p.msg:"已有近期存档,请直接查询使用");const T=Fe(p,g.action,"游戏存档");if(!te(T))throw B("INVALID_RESPONSE","存档响应不合法");return T}async function k(g,I,b){const D=Wm(g,I),P=r;if(N(P),g==="file"&&(!e.transfer||!e.files))throw B("METHOD_FORBIDDEN","宿主不支持存档文件读取");const p=new AbortController;d.add(p);let T=!1;const A=g==="sync"?setTimeout(()=>{T=!0,p.abort()},qm):void 0,O=Ne(Ne(e.operationContext,b.signal),p.signal);try{const M=await e.account.getCurrentUserId(O);if(!M)throw B("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==M)throw h(),B("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=M,g==="sync"||g==="parsed"){if(g==="sync"&&l(),!D.account_id){const G=await _({action:"check",game_id:D.game_id},M,P,O);D.account_id=Lr(G.account_id)}if(g==="sync")return await F(D,M,P,O)}const S=await _({action:g,...D},M,P,O);if(g==="list")return Km(S);if(g==="parsed")return Gm(S.parsed_data,D.game_id);const E=Gd(S.file);if(E.fileId!==D.file_id)throw B("INVALID_RESPONSE","文件标识不匹配");if(E.sizeBytes>Fi)throw B("FILE_TOO_LARGE","首期存档文件上限为 8 MiB");if(o+E.sizeBytes>ha)throw B("FILE_QUOTA_EXCEEDED","当前会话存档文件已达 32 MiB");const L={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:ct(S.download_url)},timeout:6e4};if(!sf(L)||new URL(ct(S.download_url)).pathname!=="/cloud_archive/"+D.file_id+".zip"||ri(S.expires_at)<=Date.now())throw B("INVALID_RESPONSE","存档下载地址无效");const R=".hb-game-saves/"+kd()+".zip",x=e.files.sandbox.file(R);if(!x.remove)throw B("METHOD_FORBIDDEN","宿主不支持存档临时文件清理");await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},O);const z=e.fileRegistry.createTransferScope();let H=!1,V=!1;try{await x.create({recursive:!0,exclusive:!0},O),V=!0;const G=z.registerFile(x,"game-save","readwrite");await Fd({request:L,url:new URL(ct(S.download_url)),to:G.ref,targetKind:"file",maxBytes:Fi},{...b,signal:O.signal,postProgress:()=>{}},{transfer:e.transfer,fileRegistry:z,operationContext:O}),await C(M,P,O);const K=await x.stat(O);if(K.size===void 0||!Number.isSafeInteger(K.size)||K.size<0||K.size>Fi)throw B("FILE_TOO_LARGE","存档文件超过 8 MiB");if(await C(M,P,O),o+K.size>ha)throw B("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达 32 MiB");if(O.signal.aborted)throw B("DOWNLOAD_CANCELLED","存档下载已取消");const Z=K.size,J=async ge=>{try{N(P),await _({action:"check",game_id:D.game_id,account_id:D.account_id},M,P,ge)}catch(he){throw te(he)&&["GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","UNAUTHORIZED"].includes(String(he.code))?(h(),B("FILE_ACCESS_REVOKED","游戏存档授权已失效")):he}},Y=async()=>{throw B("FILE_ACCESS_DENIED","存档文件只读")},ie={kind:"file",mode:"read",name:E.name,create:Y,write:Y,async read(ge){await J(ge);const he=await x.read(ge);try{if(await C(M,P,ge),!(he instanceof Uint8Array)||he.byteLength!==Z)throw B("INVALID_RESPONSE","存档文件长度不匹配");return he}catch(Li){throw he instanceof Uint8Array&&he.fill(0),Li}},async stat(ge){return await J(ge),{kind:"file",size:Z,modifiedAt:E.modifiedAt}}},Pe=e.fileRegistry.registerFile(ie,"game-save","read");return s.add(x),o+=Z,H=!0,Pe}finally{z.dispose(),V&&!H&&await c(x)}}catch(M){throw T?B("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):M}finally{A!==void 0&&clearTimeout(A),d.delete(p)}}async function F(g,I,b,D){const P=e.identity.get()?.miniProgramId;if(!P)throw B("INVALID_STATE","小程序身份尚未确认");const p={miniProgramId:P,userId:I,gameId:g.game_id,accountId:g.account_id},T=O=>_({action:"status",...g,task_id:O},I,b,D);let A;try{const O=await t.run(p,D,async()=>{await C(I,b,D);const S=await t.get(p,D);if(S){A=S;try{return{taskId:S,status:await T(S)}}catch(L){if(!te(L)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(L.code)))throw L;await t.set(p,void 0,D),A=void 0}}const E=await _({action:"sync",...g},I,b,D);return A=Lr(E.task_id),await t.set(p,A,D),await C(I,b,D),{taskId:A,status:void 0}});A=O.taskId;let M=O.status;for(;;){if(N(b),D.signal.aborted)throw B("REQUEST_CANCELLED","已停止等待存档同步");if(M??=await T(A),M.state==="succeeded"||M.state==="failed"){if(await t.remove(p,A,D),await C(I,b,D),M.state==="succeeded")return{state:"succeeded"};throw B(M.error_code?ct(M.error_code):"SYNC_FAILED",M.message?ct(M.message):"存档同步失败")}if(M.state!=="syncing"&&M.state!=="uploading")throw B("INVALID_RESPONSE","同步状态不合法");M=void 0,await Zm(Ym,D.signal)}}catch(O){if(te(O)){const M=String(O.code);M==="STEAM_LOGIN_REQUIRED"&&v({...g,task_id:A},I,b,D),A&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(M)&&await t.remove(p,A,a)}throw O}}return{handlers:{"gameSaves.list":(g,I)=>k("list",g,I),"gameSaves.sync":(g,I)=>k("sync",g,I),"gameSaves.readParsedData":(g,I)=>k("parsed",g,I),"gameSaves.getFile":(g,I)=>k("file",g,I)},allowsRead(g,I){return["file.readBytes","file.readText","file.stat","file.exists"].includes(g)&&te(I)&&e.fileRegistry.isGameSaveRef(I.target)},dispose(){n||(n=!0,h(!1),y(),w())}}}function Wm(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!te(t)||Object.keys(t).some(i=>!r.includes(i)))throw B("INVALID_PARAMS","存档参数不合法");const n=ur(t.gameId);if(Number(n)>2147483647)throw B("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:ur(t.accountId)}:{},...e==="file"?{save_id:ur(t.saveId),file_id:ur(t.fileId)}:{}}}function ur(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw B("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function Lr(e){try{return ur(e)}catch{throw B("INVALID_RESPONSE","服务端存档标识无效")}}function ct(e){if(typeof e!="string")throw B("INVALID_RESPONSE","服务端存档字段无效");return e}function ri(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw B("INVALID_RESPONSE","服务端存档数值无效");return e}function Gd(e){if(!te(e))throw B("INVALID_RESPONSE","存档文件信息无效");return{fileId:Lr(e.file_id),name:ct(e.name),originalPath:ct(e.original_path),sizeBytes:ri(e.size_bytes),modifiedAt:ri(e.modified_at)}}function Km(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw B("INVALID_RESPONSE","存档列表无效");return{accountId:Lr(e.account_id),saves:e.saves.map(t=>{if(!te(t)||!Array.isArray(t.files)||t.files.length>200)throw B("INVALID_RESPONSE","存档文件列表无效");return{saveId:Lr(t.save_id),createdAt:ri(t.created_at),files:t.files.map(Gd)}})}}function Zm(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(o),t.removeEventListener("abort",i),n(B("REQUEST_CANCELLED","已停止等待存档同步"))},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}const Jm=new Set(["stdio","attachments","notifications"]),Qd=new Set(["windows-x64","macos-arm64"]),Xm=new Set(["unsigned","valid","invalid","unknown"]),eg=/^[a-f0-9]{64}$/,tg=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),rg=new Set(ld),ng=new Set([...ld,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Yd=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 ig(e){const t=async(n,i,o,s)=>{const a=og(n);try{ze(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return ze(i.signal),c}catch(c){throw Co(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw m("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw m("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>sg(d,i)).catch(d=>{throw Co(d)});ze(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(ze(o.signal),c.status!=="granted")throw m("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[ui]:(n,i)=>t(n,i,async(o,s)=>vo(await e.companion.getInfo(o,s),o)),[li]:(n,i)=>t(n,i,async(o,s)=>ma(await e.companion.getPreparationStatus(o,s))),[fi]:(n,i)=>t(n,i,async(o,s)=>{const a=ma(await e.companion.getPreparationStatus(o,s));return ze(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),ze(i.signal),vo(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress($d(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[hi]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[mi]:(n,i)=>t(n,i,async(o,s)=>ga(await e.companion.getActiveSession(o,s),o)),[gi]:(n,i)=>t(n,i,async(o,s)=>{const a=ga(await e.companion.getActiveSession(o,s),o);return ze(i.signal),a||(await r("launch",o,i),ze(i.signal),Wd(await e.companion.launch(o,s),o))}),[pi]:(n,i)=>bt(n,i,e,"write"),[yi]:(n,i)=>bt(n,i,e,"closeStdin"),[Ei]:(n,i)=>bt(n,i,e,"terminate"),[wi]:(n,i)=>bt(n,i,e,"ackOutput"),[Ii]:async(n,i)=>{const o=await bt(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Ai]:(n,i)=>bt(n,i,e,"showNotification")}}function og(e){if(!Q(e)||typeof e.alias!="string"||!ql.test(e.alias))throw m("INVALID_PARAMS","Companion alias 不合法");return e.alias}function ze(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function bt(e,t,r,n){if(!Q(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw m("INVALID_PARAMS","Companion Session controller 不合法");try{ze(t.signal);const i=await r.companion[n](ag(e,n),{...r.operationContext,signal:t.signal});return ze(t.signal),i}catch(i){throw Co(i)}}function Le(){throw m("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function qd(e){return!Array.isArray(e)||e.some(t=>!Jm.has(t))?Le():Object.freeze([...new Set(e)])}function vo(e,t){return!Q(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Qd.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!Xm.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?Le():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:qd(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function sg(e,t){const r=vo(e,t);return!Q(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!eg.test(e.sha256)?Le():Object.freeze({...r,sha256:e.sha256})}function $d(e){return Q(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):Le():Le()}function ma(e){return Q(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:$d(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&Q(e.error)&&typeof e.error.code=="string"&&rg.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:Yd[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):Le():Le()}function Wd(e,t){return!Q(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Qd.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?Le():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:qd(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function ga(e,t){return e===void 0?void 0:Wd(e,t)}function ag(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!ad(r.data))throw m("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 m("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw m("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw m("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function cg(e){return!Q(e)||!tg.has(String(e.reason))?Le():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):Le():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?Le():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function dg(e){if(!Q(e)||!Q(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,r=t.sessionId;if(e.type==="companion.session.output")return!Number.isSafeInteger(t.controllerGeneration)||Number(t.controllerGeneration)<0||t.stream!=="stdout"&&t.stream!=="stderr"||!Number.isSafeInteger(t.sequence)||Number(t.sequence)<0||!ad(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:cg(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 Co(e,t){return Q(e)&&typeof e.code=="string"&&ng.has(e.code)?m(e.code,Yd[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&Q(e)&&e.name==="AbortError"?m(t,"Companion 准备已取消"):m("COMPANION_HOST_FAILED","Companion Host 操作失败")}const pa=5e3,ya=1e4;function pe(e){throw{code:"INVALID_PARAMS",message:e}}function ps(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Kd(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&pe(`${r} 不支持字段: ${n.join(", ")}`)}function ug(e){if(e===void 0)return{intensity:"light",delay:0};if(!ps(e))return pe("device.vibrate 参数必须是对象");Kd(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return pe("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>pa?pe(`device.vibrate delay 必须是 0-${pa} 的整数毫秒`):{intensity:r,delay:n}}function lg(e){return ps(e)?(Kd(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?pe("device.setClipboard text 必须是非空字符串"):e.text.length>ya?pe(`device.setClipboard text 不能超过 ${ya} 字符`):{text:e.text}):pe("device.setClipboard 参数必须是对象")}function fg(e){return typeof e=="string"?e.trim()?e:pe("device.executeProtocol 协议字符串不能为空"):ps(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?pe("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(Lo(e,new Set),e):pe("device.executeProtocol 参数必须是协议字符串或协议对象")}function Lo(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||pe("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":pe("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":pe(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&pe("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)Lo(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&pe("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))Lo(i,t);t.delete(r)}function hg(e){return{[Yn]:async t=>{X(e.operationContext.signal),await $(()=>e.presentation.vibrate(ug(t),e.operationContext),e.operationContext.signal)},[qn]:async t=>{X(e.operationContext.signal),await $(()=>e.presentation.setClipboard(lg(t),e.operationContext),e.operationContext.signal)},[$n]:async(t,r)=>{const n=Ne(e.operationContext,r.signal);X(n.signal);const i=fg(t);await $(()=>e.protocol.invoke(i,n),n.signal)}}}const Ea=1e3,mg=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function gg(e){const t=r=>Ne(e.operationContext,r.signal);return{files:{[Pn]:async(r,n)=>{Vi(n);const i=Bi(e.picker),o=pg(r),s=await Ie(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[kn]:async(r,n)=>{Vi(n);const i=Bi(e.picker),o=yg(r),s=await Ie(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[xn]:async(r,n)=>{Vi(n);const i=Bi(e.picker),o=Eg(r).suggestedName,s=t(n);if(!i.saveFile)throw De("files.saveFile");const a=await Ie(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[Mr]:async(r,n)=>{const i=Me(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);Ot(o.mode),await Ie(()=>o.create(wa(i),t(n)))},[Nr]:async(r,n)=>{const i=Me(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),Ot(o.handle.mode),!o.handle.remove)throw De(Nr);await Ie(()=>o.handle.remove(t(n)))},[Un]:async(r,n)=>{const i=Me(r);return Ia(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!Q(o)||o.kind!=="file")throw Ma()})},[Dr]:async(r,n)=>{const i=Me(r),o=Aa(await Ie(()=>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 m("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[jn]:async(r,n)=>{const i=Me(r,["content"]);typeof i.content!="string"&&_e("content 必须是字符串");const o=e.registry.resolveFile(i.target);Ot(o.mode),await Ie(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[Sr]:async(r,n)=>{const i=Me(r),o=await Ie(()=>e.registry.resolveFile(i.target).read(t(n)));return Aa(o)},[zn]:async(r,n)=>{const i=Me(r,["content"]),o=e.registry.resolveFile(i.target);Ot(o.mode),await Ie(()=>o.write(Ig(i.content),t(n)))},[Tr]:async(r,n)=>{const i=Me(r),o=await Ie(()=>e.registry.resolveFile(i.target).stat(t(n)));return Ag(o)}},directory:{[Hn]:async(r,n)=>{const i=Me(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);Ot(o.mode),await Ie(()=>o.create(wa(i),t(n)))},[_r]:async(r,n)=>{const i=Me(r,["recursive"]);if(Q(i.target)&&i.target.relativePath===".")throw m("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),Ot(o.handle.mode),!o.handle.remove)throw De(_r);await Ie(()=>o.handle.remove({recursive:i.recursive===void 0?!1:ni(i.recursive,"recursive")},t(n)))},[Fn]:async(r,n)=>{const i=Me(r);return Ia(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!Q(o)||o.kind!=="directory")throw Ma()})},[Vn]:async(r,n)=>{const i=Me(r,["limit"]),o=wg(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await Ie(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function pg(e){if(e===void 0)return{mode:"read",multiple:!1};Q(e)||_e("pickFiles 参数必须是对象"),Ni(e,["mode","accept","multiple"]);const t=Zd(e.mode,"read"),r=e.multiple===void 0?!1:ni(e.multiple,"multiple");let n;return e.accept!==void 0&&((!Array.isArray(e.accept)||e.accept.some(i=>typeof i!="string"||!/^\.[a-z0-9][a-z0-9._-]*$/i.test(i)))&&_e("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function yg(e){return e===void 0?{mode:"read"}:(Q(e)||_e("pickDirectory 参数必须是对象"),Ni(e,["mode"]),{mode:Zd(e.mode,"read")})}function Eg(e){return Q(e)||_e("saveFile 参数必须是对象"),Ni(e,["suggestedName"]),{suggestedName:Hr(e.suggestedName,"suggestedName")}}function Me(e,t=[]){return(!Q(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&_e("文件操作参数必须包含 target"),Ni(e,["target",...t]),e}function wa(e){return{recursive:e.recursive===void 0?!1:ni(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:ni(e.exclusive,"exclusive")}}function Zd(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&_e("mode 必须是 read 或 readwrite"),e)}function ni(e,t){return typeof e!="boolean"&&_e(`${t} 必须是布尔值`),e}function wg(e){if(e===void 0)return Ea;if((!Number.isSafeInteger(e)||e<=0)&&_e("limit 必须是正整数"),e>Ea)throw m("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Ni(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&_e(`不支持字段: ${r.join(", ")}`)}function Ot(e){if(e!=="readwrite")throw m("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Vi(e){if(!e.trustedUserGesture)throw m("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Bi(e){if(!e)throw De("files.external");return e}async function Ia(e){try{return await e(),!0}catch(t){if(mg.has(fs(t)??""))return!1;throw vr(t)}}async function Ie(e){try{return await e()}catch(t){throw vr(t)}}function Ig(e){return e instanceof Uint8Array||_e("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&_e("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Aa(e){if(!(e instanceof Uint8Array))throw m("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Ma(){return m("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Ag(e){if(!Q(e)||e.kind!=="file"||!Mg(e.size))throw m("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Ng(e[t]))throw m("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 Mg(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Ng(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function _e(e){throw m("INVALID_PARAMS",e)}const Dg=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),Gi={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function Sg(e){if(e instanceof le)return m("REQUEST_UNSUPPORTED",Gi.REQUEST_UNSUPPORTED);const t=Jd(e);return t!==void 0&&Dg.has(t)?m(t,Gi[t]??"媒体操作失败"):m("MEDIA_PREPARE_FAILED",Gi.MEDIA_PREPARE_FAILED)}function Jd(e){try{if(!Q(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Tg=["source","mediaType","maxCount"],an=Object.freeze({source:"album",mediaType:"all",maxCount:1});function _g(e){if(e===void 0)return an;if(!Pl(e))throw m("INVALID_PARAMS",Og(e));return bg(e)}function bg(e){return Object.freeze({source:e.source??an.source,mediaType:e.mediaType??an.mediaType,maxCount:e.maxCount??an.maxCount})}function Og(e){if(!Q(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!Tg.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 vg=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),Cg={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class Lg{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=Rg(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>kg(s,i[a]));if(!kl(o))throw Ve("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(xg).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=Jd(n);throw i!==void 0&&vg.has(i)?n:Ve("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function Na(e,t){if(e.signal.aborted)throw m("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw m("REQUEST_CANCELLED","media.pick 已取消")}function Rg(e,t){if(!Array.isArray(e))throw Ve("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw Ve("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw Ve("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw Ve("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw Ve("Host 返回了稀疏媒体结果");Pg(e[n],n)}return e}function Pg(e,t){if(!Q(e))throw Ve(`第 ${t+1} 项不是对象`);if(!sd({...e,file:Cg}))throw Ve(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!Q(e.file))throw Ve(`第 ${t+1} 项缺少文件句柄`)}function kg(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 xg(e){return"handleId"in e.ref?e.ref.handleId:void 0}function Ve(e){return m("MEDIA_PREPARE_FAILED",e)}function Ug(e){const t=e.media?new Lg(e.registry,e.media,e.operationContext):void 0;return{handlers:{[br]:async(n,i)=>{const o=_g(n);zg(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw De(br);const c=Ne(e.operationContext,i.signal);Na(e.operationContext,i.signal);const d=await jg(s,o,c,e.operationContext,i.signal);Na(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function jg(e,t,r,n,i){try{return await $(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?m("REQUEST_CANCELLED","media.pick 已取消"):Sg(o)}}function zg(e){if(!e.trustedUserGesture)throw m("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Kr=4294967296;function Hg(e){const t=new Fg;return t.write(e),t.finish()}class Fg{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<Kr?(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=Vg(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<Kr)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/Kr),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Kr)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Vg(e){const t=new Uint8Array(Bg(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 Bg(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 Xd(e){Ro(e);const t=Hg(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 Ro(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)Ro(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");Ro(s,t+1,r)}r.delete(e)}const Gg=["pc","console","mobile"],Qg=["game","wiki"];function ii(e){throw{code:"INVALID_PARAMS",message:e}}function Yg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rt(e,t){return typeof e!="string"||!e.trim()?ii(t):e.trim()}function Da(e,t,r){return typeof e!="string"||!t.includes(e)?ii(r):e}function qg(e){const t={target:"game_detail",appId:rt(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Da(e.gameType,Gg,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Da(e.page,Qg,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=rt(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=rt(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function $g(e){return{target:"user_detail",userId:rt(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Wg(e){const t={target:"post_detail",linkId:rt(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=rt(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=rt(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Kg(e){const t={target:"mini_program",miniProgramId:rt(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Zg(e){return Yg(e)?e.target==="game_detail"?qg(e):e.target==="user_detail"?$g(e):e.target==="post_detail"?Wg(e):e.target==="mini_program"?Kg(e):ii("navigation.openAppPage target 不支持"):ii("navigation.openAppPage options 必须是对象")}function Jg(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 Xg(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function ep(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 tp(e){const t=e;return t.target==="game_detail"?Jg(t):t.target==="user_detail"?Xg(t):ep(t)}const rp="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",np="data-hb-sdk-fullscreen-exit",ip=3e3,op=2e3,Sa="var(--white-70a,rgba(255,255,255,.7))",Ta="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function sp(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(np,""),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 ${Sa}`,`box-shadow:${Ta}`,"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=rp,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(v=op){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")},v)}function y(){l(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Sa,t.style.boxShadow=Ta,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),h()}async function w(){if(!(s||a)){if(!o){y();return}a=!0,clearTimeout(c),l();try{await e()}catch{}finally{a=!1,s||y()}}}return t.addEventListener("click",w),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(ip),{dispose(){s=!0,clearTimeout(c),l(),t.removeEventListener("click",w),window.removeEventListener("resize",f),t.remove()}}}const eu=1e4;function tu(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()},eu);return{signal:r.signal,async run(s){try{return await $(s,r.signal)}catch(a){throw n??a}},dispose(){clearTimeout(o),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function _a(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 Qi(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function ir(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function ap(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(y){if(!y.hideCapsule){c();return}a??=sp(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",c,{once:!0});function u(y,w){if(n===y){if(n=void 0,clearTimeout(y.timer),e.operationContext.signal.removeEventListener("abort",f),"error"in w)y.controller.abort();else if(i={options:y.options,result:w.result},o=y.options,d(y.options),e.onApplied?.(y.options),w.result.supported&&!Qi(s,y.options)){s={...y.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:y.source})}catch{}}for(const v of y.subscribers)v.dispose(),"error"in w?v.reject(w.error):v.resolve(w.result);y.subscribers.clear()}}function f(){n&&u(n,{error:ir()})}function l(y,w){return new Promise((v,N)=>{const C=()=>{y.subscribers.delete(_),_.dispose(),N(ir()),y.subscribers.size===0&&u(y,{error:ir()})},_={resolve:v,reject:N,dispose:()=>w?.removeEventListener("abort",C)};y.subscribers.add(_),w?.addEventListener("abort",C,{once:!0}),w?.aborted&&C()})}const h={async runDisplayRequest(y,w,v){const N=++t,C=tu(w,e.operationContext.signal);try{return await C.run(async()=>{if(await v(C.signal),C.signal.aborted)throw ir();if(_a(y),N<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=N,h.apply(y,C.signal)})}finally{C.dispose()}},async apply(y,w,v="api"){if(X(e.operationContext.signal),w?.aborted)throw ir();const N=_a(y),C=n?.options??o,_={mode:N.orientation??C.mode,hideCapsule:N.fullscreen??C.hideCapsule};_.mode==="landscape"&&(_.hideCapsule=!0);const k=e.presentation.applyOrientation;if(!k)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&Qi(n.options,_))return l(n,w);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&Qi(i.options,_))return i.result;i=void 0;const F={options:_,source:v,controller:new AbortController,subscribers:new Set};n=F;const j=l(F,w);return e.operationContext.signal.addEventListener("abort",f,{once:!0}),w||(F.timer=setTimeout(()=>{u(F,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},eu)),$(()=>k.call(e.presentation,_,{...e.operationContext,signal:F.controller.signal}),F.controller.signal).then(g=>u(F,{result:g??{supported:!0}}),g=>u(F,{error:g})),j},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return h}function ru(e){throw{code:"INVALID_PARAMS",message:e}}function ba(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&ru(`${t} 不支持参数`)}function cp(e){return{[Wn]:async t=>{X(e.operationContext.signal),ba(t,"navigation.close"),await $(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Kn]:async t=>{X(e.operationContext.signal),ba(t,"navigation.reload"),await $(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[Zn]:async(t,r)=>{const n=Ne(e.operationContext,r?.signal);X(n.signal);const i=Zg(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Xd(i.extra)}catch{ru("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=tu(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}X(n.signal),await $(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await $(()=>e.presentation.openAppPage(tp(i),n),n.signal)}}}const Oa={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function dp(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw De("network.upload");const o=Ne(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw m("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(l){throw s(),vr(l)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw m("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw m("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,y=await n.upload(a,{...h,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:f});if(u=!0,!Number.isSafeInteger(y.uploadedBytes)||y.uploadedBytes<d||y.uploadedBytes>c.size)throw m("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(y.status>=200&&y.status<300&&y.uploadedBytes!==c.size)throw m("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:y.uploadedBytes,total:c.size,lengthComputable:!0}),y}catch(l){u=!0;const h=fs(l);throw h&&Oa[h]?m(h,Oa[h]):o.signal.aborted?m("UPLOAD_CANCELLED","上传已取消"):h?.startsWith("FILE_")||h?.startsWith("DIRECTORY_")?vr(l):m("UPLOAD_NETWORK_FAILED","上传网络失败")}}const ys="withCredentials",up=new Set(["url","method","params","data","headers","timeout",ys]),lp=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",ys]),fp=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),va=3e4,Po=2*1024*1024,hp=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,nu=/[\u0000-\u0008\u000A-\u001F\u007F]/,mp=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,gp="network.request 不支持 multipart/form-data,请使用专用上传能力";function pp(e){const t=yp(e.runtimePermissions),r=Cp(e.allowedHttpOrigins);return{[Rn]:async(n,i)=>{const o=wp(n,{permission:t,allowedHttpOrigins:r}),s=await dp(o,i,e),{uploadedBytes:a,...c}=s;return La(c)},[Ln]:async(n,i)=>{const o=Ip(n,{permission:t,allowedHttpOrigins:r});return Fd(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Cn]:async(n,i)=>{const o=Ne(e.operationContext,i?.signal);X(o.signal);const s=Ep(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await $(()=>e.network.request(s,o),o.signal)}catch(c){throw Rp(c)?c:Pp(c,"REQUEST_UNSUPPORTED")?q("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):q("REQUEST_FAILED","网络请求失败")}return La(a)}}}function yp(e){const t=Ce(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Ep(e,t){const r=Gt(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!up.has(c));if(n.length>0)throw q("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);iu(r,"network.request");const i=Es(r,t,"network.request"),o=Mp(r.method),s=r.data;s!==void 0&&Sp(s),_p(i.headers,s);const a=bp(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 wp(e,t){const r=Gt(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 q("INVALID_PARAMS","network.upload 包含不支持的字段");const i=Es(r,t,"network.upload");if(i.official)throw q("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw q("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!Ft(r.from))throw q("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw q("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw q("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw q("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 q("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(u=>u.toLowerCase()==="content-type"))throw q("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=Ca(r.fieldName),c=r.fields===void 0?void 0:Gt(r.fields,"fields 必须是字符串字典");for(const[u,f]of Object.entries(c??{}))if(Ca(u),typeof f!="string"||u===a)throw q("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw q("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||nu.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw q("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>Po)throw q("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:ms(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function Ca(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw q("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function Ip(e,t){const r=Gt(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!lp.has(c));if(n.length>0)throw q("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);iu(r,"network.download");const i=Es(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw q("INVALID_PARAMS","network.download timeout 必须是有限正数");Bm(i.headers);const o=Ft(r.to),s=id(r.to);if(!o&&!s)throw q("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw q("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw q("INVALID_PARAMS","suggestedName 必须是字符串");a=ms(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw q("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw q("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 Es(e,t,r){const n=Ap(e.url,t.allowedHttpOrigins,r),i=Cf(n);if(i&&!t.permission.useOfficialDomain)throw q("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(vf(n.pathname,i))throw q("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Gt(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Np(e.headers,r),timeout:Dp(e.timeout,r)}}function Ap(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw q("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw q("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Mp(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw q("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!fp.has(t))throw q("INVALID_PARAMS","network.request method 不合法");return t}function Np(e,t="network.request"){const r=Gt(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!hp.test(s)||typeof o!="string"||nu.test(o))throw q("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Lf(s))throw q("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function iu(e,t){const r=e[ys];if(r!==void 0&&typeof r!="boolean")throw q("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Dp(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw q("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>va)throw q("INVALID_PARAMS",`${t} timeout 不能超过 ${va}ms`);return e}}function Sp(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw q("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Tp(e)>Po)throw q("INVALID_PARAMS",`network.request data 不能超过 ${Po} 字节`)}function Tp(e){if(typeof e=="string")return Yi(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return Yi(e.toString());try{const t=JSON.stringify(e);return t?Yi(t):0}catch{throw q("INVALID_PARAMS","network.request data 必须可序列化")}}function _p(e,t){const r=ou(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 q("INVALID_PARAMS",gp)}function bp(e,t,r){if(t===void 0)return;const n=ou(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)||vp(t))?"form":Op(t)?"json":void 0}function ou(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function Op(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function vp(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Cp(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&&Lp(n.hostname)&&t.add(n.origin)}catch{}return t}function Lp(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 La(e){return Object.keys(e.headers).some(Ra)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Ra(t)))}:e}function Ra(e){const t=e.trim().toLowerCase();return mp.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Rp(e){return e instanceof Error&&e.name==="AbortError"}function Pp(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Gt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw q("INVALID_PARAMS",t);return e}function Yi(e){return new TextEncoder().encode(e).length}function q(e,t){return{code:e,message:t}}function kp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xp(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 Up(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=xp(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function jp(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 su(e,t){if(e==null)return{};if(!kp(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=Up(e.topicIds),n=jp(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 zp(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function Hp(e){try{if(zp(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function fe(e){throw{code:"INVALID_PARAMS",message:e}}function Fr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ko(e,t){return typeof e!="string"||!e.trim()?fe(t):e}function Fp(e,t){const r=ko(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?fe(t):r}catch{return fe(t)}}function Vp(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function au(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return fe(`${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 fe(`${t} 缺少有效的小程序分享地址`)}}function Bp(e,t){if(!Fr(e))return fe("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return fe("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!Vp(r))return fe("share.showShareMenu channel 不合法");const n=cu(e.extra,"share.showShareMenu");return{title:ko(e.title,"share.showShareMenu title 必须是非空字符串"),description:ko(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:au(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:Fp(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function cu(e,t){if(e!==void 0)try{return Xd(e)}catch{return fe(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function du(e,t){return e.invalidMessage&&await $(()=>Hp(t.environment),t.operationContext.signal)?fe(e.invalidMessage):e.post}function Pa(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Gp(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Pa(t.windowWidth,0),height:Pa(t.windowHeight,0)}}function xo(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?fe(t):r}function ka(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?fe(t):r}function Qp(e){return Fr(e)?{left:xo(e.left,"share.screenshot rect.left 必须是非负数字"),top:xo(e.top,"share.screenshot rect.top 必须是非负数字"),width:ka(e.width,"share.screenshot rect.width 必须是正数"),height:ka(e.height,"share.screenshot rect.height 必须是正数")}:fe("share.screenshot rect 必须是对象")}function Yp(e,t){if(e!=null&&!Fr(e))return fe("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?fe("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?fe("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?Gp(t):Qp(r.rect),...r.delay===void 0?{}:{delay:xo(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function qp(e,t){X(t.operationContext.signal);const r=Bp(e,t);let n=su(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await du(n,t);return $(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function $p(e,t){if(X(t.operationContext.signal),e!==void 0&&!Fr(e))return fe("share.copyLink 参数必须是对象");const r=cu(e?.extra,"share.copyLink"),n=au(t,"share.copyLink",r);return await $(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Wp(e,t,r){X(t.operationContext.signal);const n=su(Fr(e)?e.post:void 0,{method:"share.screenshot"}),i=await du(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=Kp(),{watermarkTheme:a,...c}=r;let d=!1,u,f;try{d=!0,await $(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),u=await t.prepareScreenshot?.(r.rect,t.operationContext.signal,a),f={status:"fulfilled",value:await $(()=>t.presentation.captureAndShare({...c,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(h){f={status:"rejected",error:h}}finally{u?.()}const l=d?await Zp(t.presentation,s,t.operationContext.signal):void 0;if(f.status==="rejected")throw f.error;if(l)throw l;return f.value}function Kp(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Zp(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await $(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function Jp(e){let t=Promise.resolve();return{[Tn]:(r,n)=>$p(r,e),[_n]:(r,n)=>qp(r,e),[bn]:async(r,n)=>{const i=Ne(e.operationContext,n.signal);X(i.signal);const o=Yp(r,e.presentation),s=t.then(()=>Wp(r,{...e,operationContext:i},o));return t=s.then(()=>{},()=>{}),$(()=>s,i.signal)}}}const xa=new WeakMap;function uu(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return cf(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${md(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function lu(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=xa.get(t);f||(f=new Map,xa.set(t,f));const l=f.get(u)??Promise.resolve(),h=async()=>(X(c.signal,{preserveReason:!0}),d(u)),y=l.catch(()=>{}).then(()=>e.lock?e.lock(u,h):h());f.set(u,y);try{return await y}finally{f.get(u)===y&&f.delete(u)}},o=async(c,d,u=!1)=>{const f=Nt(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(y=>y.key.startsWith(f)&&y.value!=="").map(y=>y.key.slice(f.length)))];const l=await e.storage.getRaw(Qr(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>ks||h.some(y=>typeof y!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(y)))throw new Error("本地数据索引异常");return[...new Set(h)]},s=async(c,d)=>{if(e.diagnostics){const l=Nt(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){X(d.signal,{preserveReason:!0});const h=await Promise.all(f.slice(l,l+16).map(async y=>{const w=await e.storage.getRaw(Nt(c,y),d);return w!==void 0&&w!==""?{area:"local",key:y,value:w}:void 0}));for(const y of h)y&&u.push(y)}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(Nt(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>=ks)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const h=[...new Set([...l,c])];await e.storage.setRaw(Qr(f),JSON.stringify(h),u)}X(u.signal,{preserveReason:!0}),await e.storage.setRaw(Nt(f,c),d,u),X(u.signal,{preserveReason:!0})})},list(c){return i(c,d=>s(d,c))},clear(c){return i(c,async d=>{const u=await o(d,c);e.diagnostics||await e.storage.setRaw(Qr(d),JSON.stringify(u),c);for(let f=0;f<u.length;f+=16){X(c.signal,{preserveReason:!0});const h=(await Promise.allSettled(u.slice(f,f+16).map(y=>e.storage.setRaw(Nt(d,y),"",c)))).find(y=>y.status==="rejected");if(h)throw h.reason}X(c.signal,{preserveReason:!0}),await e.storage.setRaw(Qr(d),"[]",c)})}}}function Xp(e,t){return typeof navigator<"u"&&navigator.locks?new Promise((r,n)=>{navigator.locks.request(`hb-miniprogram-storage:${e}`,()=>t().then(r,n)).catch(n)}):t()}const ey=128,ty=/^[A-Za-z0-9_-]+$/;function ry(e){const t=e.scopedStorage??lu({storage:e.storage,resolveScope:()=>uu({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[Ir]:async n=>{X(e.operationContext.signal);const i=Ua(n,Ir,e.storageLimits?.maxKeyLength),o=await $(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:ja(o)}},[Ar]:async n=>{X(e.operationContext.signal);const i=fu(n,"storage.setStorage 参数必须是对象"),o=Ua(i,Ar,e.storageLimits?.maxKeyLength),s=ny(i.data,e.storageLimits?.maxValueBytes);await $(()=>t.set(o,s,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(X(e.operationContext.signal),(await $(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?ht("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:ja(o),serializedValue:o,bytes:hu(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function Ua(e,t,r=ey){const i=fu(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw ht("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!ty.test(i))throw ht("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function ny(e,t){let r;try{r=JSON.stringify(e)}catch{throw ht("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw ht("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&hu(r)>t)throw ht("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function ja(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function fu(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw ht("INVALID_PARAMS",t);return e}function hu(e){return new TextEncoder().encode(e).length}function ht(e,t){return{code:e,message:t}}const za=120;function Je(e){throw{code:"INVALID_PARAMS",message:e}}function ws(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mu(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Je(`${r} 不支持字段: ${n.join(", ")}`)}function iy(e){if(!ws(e))return Je("ui.showToast 参数必须是对象");if(mu(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Je("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>za)return Je(`ui.showToast message 不能超过 ${za} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Je("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function oy(e){return e===void 0?{dismissible:!1}:ws(e)?(mu(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Je("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Je("ui.showLoading 参数必须是对象")}function sy(e){e!==void 0&&(!ws(e)||Object.keys(e).length)&&Je("ui.hideLoading 不支持参数")}function ay(e){return{[Bn]:async t=>{X(e.operationContext.signal),await $(()=>e.presentation.showToast(iy(t),e.operationContext),e.operationContext.signal)},[Gn]:async t=>{X(e.operationContext.signal),await $(()=>e.presentation.showLoading(oy(t),e.operationContext),e.operationContext.signal)},[Qn]:async t=>{X(e.operationContext.signal),sy(t),await $(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const cy={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ae(e,"当前用户首页资料接口响应异常")}},dy=3e4;function uy(e,t,r={}){const n=r.ttlMs??dy,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 Mi(e,cy,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(l){throw t.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):l instanceof le?m("REQUEST_UNSUPPORTED",l.message):l instanceof zr?m("INVALID_RESPONSE","user home_v2 响应不合法"):l instanceof Bt?m("REQUEST_FAILED","user home_v2 请求失败"):l instanceof jr?i&&(l.status===403||l.status===429)?m("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:l.status,...l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs}}):m("REQUEST_FAILED",l.message):fy(l)?l:m("REQUEST_FAILED","user home_v2 请求失败")}return ly(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,y=d().then(w=>(s===h&&(a={userId:f,value:w,expiresAt:Date.now()+n}),w)).finally(()=>{c?.promise===y&&(c=void 0)});return c={userId:f,generation:h,promise:y},y}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function ly(e,t){if(!Q(e))throw m("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 m(n,r)}if(!Q(e.result))throw m("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function fy(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}const hy={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 ae(e,"关注用户接口响应异常")}},my={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 ae(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowStatus 接口响应异常")}},gy={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 ae(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowGuidanceBegin 接口响应异常")}},py={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 ae(e,"Steam 游戏库接口响应异常")}};function yy(e,t=Do){const r=kf({version:"2",validate:wy}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):Do,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 Ha(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 Ey(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 wy(e){if(!Q(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Fa(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw kt();for(const t of e.gameList){if(!Q(t)||!Uo(t.appid)||!Uo(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw kt();for(const r of["image","portraitImage","icon"])Iy(t,r);for(const r of["playtimeForever","playtime2Weeks"])Fa(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw kt()}return e}function Uo(e){return typeof e=="number"&&Number.isFinite(e)}function Fa(e,t){if(e[t]!==void 0&&!Uo(e[t]))throw kt()}function Iy(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw kt()}function kt(){return m("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const gu=20,Ay=100,My=128,pu=0,yu="weeks",Ny=100,Dy=new Set(["weeks","all","achieved"]);function Sy(){return{nickname:"",avatar:""}}function Ty(e){const t=uy(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??yd(),i=yy(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(A,O){const M=JSON.stringify([A,O]);return(!o||o.key!==M)&&(o={key:M,scope:n.createScope(O,n.createScope(A))}),o.scope}function d(){const A=o;o=void 0,A&&n.invalidateScope(A.scope).catch(()=>{}),s.clear()}const u=bd({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??Td))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let l,h,y=0,w=!1;const v=e.account.onChange(()=>{y+=1,t.clear(),u.invalidate(),d()}),N=e.authorization.onEvent((A,O)=>{A==="user_info_authorization_change"&&Object.values(O).some(M=>M==="denied")&&(y+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(w)return;const M=await e.account.getCurrentUserId(e.operationContext);typeof M=="string"&&M.trim()&&await n.invalidateScope(c(_(),M.trim()))}).catch(()=>{}))});function C(){if(w||e.operationContext.signal.aborted)throw m("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function _(){const A=e.identity.get()?.miniProgramId?.trim();if(!A)throw m("INVALID_STATE","用户能力缺少 canonical 小程序身份");return A}async function k(){C(),await a,C();let A;try{A=await e.account.getCurrentUserId(e.operationContext)}catch(O){throw e.operationContext.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):or(O)?O:m("REQUEST_FAILED","读取小黑盒账号失败")}return typeof A=="string"&&A.trim()?A.trim():void 0}async function F(A,O){const M=await k();if(y!==O||M!==A)throw m("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function j(A,O,M=e.operationContext.signal){try{return await Mi(e.network,A,O,{...e.operationContext,signal:M,credentials:"heybox-session",...f?{gate:f}:{}})}catch(S){throw e.operationContext.signal.aborted?m("RUNTIME_DESTROYED","小程序 Runtime 已终止"):S instanceof le?m("REQUEST_UNSUPPORTED",S.message):S instanceof zr?m("INVALID_RESPONSE","用户接口响应不合法"):S instanceof Bt?m("REQUEST_FAILED","用户请求失败"):S instanceof jr?r&&(S.status===403||S.status===429)?m("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:S.status,...S.retryAfterMs===void 0?{}:{retryAfterMs:S.retryAfterMs}}):m("REQUEST_FAILED",S.message):or(S)?S:m("REQUEST_FAILED","用户请求失败")}}async function g(A,O){if(!e.authorizationContext)return{mini_program_id:A};let M;try{M=await $(()=>e.authorizationContext.get({...e.operationContext,signal:O}),O)}catch(S){if(or(S))throw S;const E=m("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(E,"cause",{configurable:!0,value:S}),E}if(!M.token?.trim())throw m("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:A,runtime_auth_context_token:M.token}}async function I(){C();const A=_(),O=y,M=await k();if(!M){if(y!==O)throw m("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const S=await g(A,e.operationContext.signal);await F(M,O);const E=await j(my,S);if(await F(M,O),_()!==A)throw m("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Ga(Ba(E))}function b(A,O){if(!A)return Promise.reject(m("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(O?.aborted)return Promise.reject(m("REQUEST_CANCELLED","关注操作已取消"));if(l)return Promise.reject(m("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(m("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const M=D(O).finally(()=>{l===M&&(l=void 0)});return l=M,M}async function D(A){C();const O=_(),M=new AbortController;h=M;const S=()=>M.abort();e.operationContext.signal.addEventListener("abort",S,{once:!0}),A?.addEventListener("abort",S,{once:!0});let E=()=>{},L=!1;try{try{await $(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:M.signal}),M.signal)}catch(ie){throw or(ie)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(ie.code)?m("FOLLOW_CANCELLED","已取消小黑盒登录"):ie}C();const R=y;E=e.account.onChange(()=>{L=!0,S()});const x=await $(k,M.signal);if(!x)throw m("FOLLOW_CANCELLED","未完成小黑盒登录");const z=async()=>{if(await $(()=>F(x,R),M.signal),C(),_()!==O)throw m("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await z();const H=await g(O,M.signal);await z();const V=ky(),G=await $(()=>j(gy,{...H,request_id:V},M.signal),M.signal);await z();const K=Ba(G);if(K.status!=="notFollowing")return Ga(K);if(K.rateLimited)throw m("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const Z=await $(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:O,signal:M.signal}),M.signal);if(await z(),Z!=="confirmed")throw m("FOLLOW_CANCELLED","已取消关注作者");const J=K.authorId,Y=await $(()=>j(hy,{body:{following_id:J}},M.signal),M.signal);if(await z(),Y.status!=="ok"){const ie=["login","relogin","lack_token"].includes(Y.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw m(ie,typeof Y.msg=="string"&&Y.msg.trim()?Y.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(R){throw C(),L?m("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):A?.aborted?m("REQUEST_CANCELLED","关注操作已取消"):or(R)?R:m("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{E(),e.operationContext.signal.removeEventListener("abort",S),A?.removeEventListener("abort",S),h===M&&(h=void 0)}}async function P(){_();const A=y,O=await k();if(!O)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[M,S]=await Promise.all([e.authorization.getOrCreateLocalIdentity(O),p(O).catch(()=>Sy())]);return await F(O,A),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:M.appUserId,profile:S,...M.steamId?{steam_id:M.steamId}:{}}}}function p(A){return u.read(A,()=>j(_d,void 0).then(O=>{const M=jo(O,"账号基础信息");if(M.display_username!==void 0&&typeof M.display_username!="string")throw m("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(M.display_avatar!==void 0&&typeof M.display_avatar!="string")throw m("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:M.display_username??"",avatar:M.display_avatar??""}}))}async function T(A){const O=_y(A),M=_(),S=y,E=await k();if(!E)return d(),{isLogin:!1,isBound:!1,data:null};const L=await t.get(E);await F(E,S);const R=Eu(L.steam_id_info);if(Object.keys(R).length===0)return await n.invalidateScope(c(M,E)).catch(()=>{}),await F(E,S),s.delete(JSON.stringify([M,E])),{isLogin:!0,isBound:!1,data:null};const x=JSON.stringify([M,E]),z=c(M,E),H=Ha({...O,steamId:void 0},R),V=wu(R.personal_infomation_open??R.personal_information_open),G=JSON.stringify([H??null,V??null]),K=s.get(x);K&&K.identity!==G&&(await n.invalidateScope(z).catch(()=>{}),await F(E,S));const Z={identity:G,scope:n.createScope(G,z)};s.set(x,Z);const J=Ha(O,R),Y=J?i.persistent:i.unresolved,ie=n.createScope(J??"unresolved",Z.scope),Pe=async()=>{if(await F(E,S),_()!==M||s.get(x)?.identity!==G)throw m("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},ge=await Y.read({scope:ie,key:Ey({miniProgramId:M,userId:E,effectiveSteamId:J,personalInformationOpen:V,query:O}),signal:e.operationContext.signal,load:async he=>{const Li=await j(py,{userId:E,...O,personalInformationOpen:V},he);return await Pe(),Ly(jo(Li,"Steam 游戏库"),O)}}).catch(async he=>{throw await Pe(),he});return await Pe(),{isLogin:!0,isBound:!0,data:ge}}return{getFollowStatus:I,requestFollowAuthor:b,getInfo:P,getSteamGameList:T,async invalidateSteamGameListCache(){const A=_(),O=y,M=await k();if(!M)return;const S=c(A,M);await Promise.all([i.persistent.invalidateScope(S),i.unresolved.invalidateScope(S)]),t.clear(),s.delete(JSON.stringify([A,M])),await F(M,O)},dispose(){w||(w=!0,h?.abort(),y+=1,v(),N(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function _y(e){if(e==null)return{limit:gu,offset:pu,sort:yu,includeHidden:!1};if(!Q(e))throw Xe("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Xe(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:by(e.limit),offset:Oy(e.offset),sort:vy(e.sort),includeHidden:Cy(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>My)throw Xe("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Xe("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Ny))}return r}function by(e){if(e===void 0)return gu;if(!Number.isInteger(e)||Number(e)<1)throw Xe("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Ay)}function Oy(e){if(e===void 0)return pu;if(!Number.isInteger(e)||Number(e)<0)throw Xe("user.getSteamGameList offset 必须是非负整数");return Number(e)}function vy(e){if(e===void 0)return yu;if(typeof e!="string"||!Dy.has(e))throw Xe("user.getSteamGameList sort 不支持");return e}function Cy(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Xe("user.getSteamGameList includeHidden 必须是 boolean");return e}function Ly(e,t){if(!Array.isArray(e.game_list))throw m("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(Ry).filter(a=>a!==void 0),n=oi(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=wu(e.is_me);return s!==void 0&&(o.isMe=s),o}function Ry(e){const t=Eu(e),r=oi(t.appid),n=oi(t.steam_appid)??r,i=Is(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};qi(o,"image",t.image),typeof t.vertical_head_image=="string"&&qi(o,"portraitImage",t.vertical_head_image),qi(o,"icon",t.appicon??t.icon),Va(o,"playtimeForever",t.playtime_forever),Va(o,"playtime2Weeks",t.playtime_2weeks);const s=Py(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function jo(e,t){if(!Q(e))throw m("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 m(n,r)}if(!Q(e.result))throw m("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Eu(e){return Q(e)?e:{}}function Is(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Py(e){return Array.isArray(e)?e.map(Is).filter(Boolean):[]}function oi(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function wu(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function qi(e,t,r){const n=Is(r);n&&Object.assign(e,{[t]:n})}function Va(e,t,r){const n=oi(r);n!==void 0&&Object.assign(e,{[t]:n})}function Xe(e){return m("INVALID_PARAMS",e)}function or(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Ba(e){const t=jo(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 m("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Ga(e){return e.status}function ky(){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 xy(e){return{[An]:async t=>(Zr(t,"user.getFollowStatus"),e.user.getFollowStatus()),[Mn]:async(t,r)=>(Zr(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[Nn]:async t=>(Zr(t,"user.getInfo"),e.user.getInfo()),[Dn]:async(t,r)=>{Zr(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Sn]:async t=>e.user.getSteamGameList(t)}}function Zr(e,t){if(e!==void 0)throw m("INVALID_PARAMS",`${t} 不接收入参`)}function Qa(e){throw{code:"INVALID_PARAMS",message:e}}function sr(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Iu(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Jr(e,t,r){return Math.min(Iu(e,t),r)}async function Uy(e){try{return Iu(await e.getNavigationBarHeight(),0)}catch{return 0}}function jy(e,t,r,n){const i=Jr(e.safeArea?.left,0,t),o=Math.max(i,Jr(e.safeArea?.right,t,t)),s=Jr(e.safeArea?.top,n,r),a=Math.max(s,Jr(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Ya(e){const t=e.getViewportMetrics(),r=sr(t.windowWidth,0),n=sr(t.windowHeight,0),i=await Uy(e);return{pixelRatio:sr(t.pixelRatio,1),screenWidth:sr(t.screenWidth,r),screenHeight:sr(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:jy(t,r,n,i),screenTop:i}}function zy(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;Ya(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=ap({...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:{[pt]:async(f,l)=>c.apply(f,l?.signal),[On]:async()=>(X(r.operationContext.signal),Ya(r.presentation)),[vn]:async f=>{if(X(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return Qa("viewport.setNavigationBarStyle 参数必须是对象");const l=f.foregroundStyle;if(l!=="light"&&l!=="dark")return Qa("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await $(()=>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}}const Hy=new Map(tt.map(e=>[e.method,e]));function cn(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function Fy(e){const t=$l(e);return r=>t(r.requirement,r.method)}function Vy(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 By(e){const t=Fy(e.runtimePermissions),r=Ce(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??Gy,c=e.onTrace?a():0,d=e.onTrace?`cap_${++n}`:"";try{if(e.terminalSignal.aborted)throw cn("RUNTIME_DESTROYED","小程序 Runtime 已终止");lf(i,e.effectiveCapabilities);const u=Hy.get(i);if(!u)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const f=t(u),l=!f.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,o)===!0,h=!f.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,o)===!0;if(!f.allowed&&!l&&!h)throw cn(f.code,f.message,f.data);const y=e.handlers[i];if(!y)throw new Error(`Capability method ${i} 缺少 handler`);const w=async C=>{for(const _ of e.policies??[]){const k=await _.evaluate({method:i,payload:o,capability:u});if(e.terminalSignal.aborted||C.aborted)throw Wa();if(!k.allowed)throw cn(k.code,k.message,k.data)}if(e.terminalSignal.aborted||C.aborted)throw Wa()},N=await Vy(async()=>{if(i===pt){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,w)}return await w(e.terminalSignal),y(o,s)},void 0,s,e.terminalSignal);return qa(e.onTrace,$a(d,i,o,c,N),a),N}catch(u){throw qa(e.onTrace,$a(d,i,o,c,{status:"error",error:u}),a),u}}}}function Gy(){return typeof performance>"u"?Date.now():performance.now()}function qa(e,t,r){if(!e)return;const n=r();try{e({...t,timestamp:n,durationMs:Math.max(0,Number.isFinite(n-t.startedAt)?n-t.startedAt:0)})}catch{}}function $a(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:Qy(i.error)}:{},...Yy(t,r,i)}}function Qy(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function Yy(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"&&Au(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 Au(e){return typeof e=="object"&&e!==null}function Wa(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function qy(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=Zf(e.requestPolicy);let n;if(e.files)try{n=Ff(e.files,t)}catch{}const i=yd({store:n}),o=e.onRequestPolicyReport??(r.debugReport?$y:void 0),s=r.enabled?qf({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new hs(e.files,e.miniProgramDetail),c=gg({registry:a,picker:e.picker,operationContext:t}),d=Nh({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,y,w=()=>{},v=()=>{};try{u=zy({operationContext:t,presentation:e.hostPresentation,onDisplayChange:I=>e.eventSink.postEvent("display_change",I),onViewportChange:I=>e.eventSink.postEvent("viewport_change",I)}),l=Ty({authPresentation:e.authPresentation,authorizationContext:e.authorizationContext,account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:d,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:s,requestPolicyEnabled:r.enabled}),w=d.onEvent((I,b)=>e.eventSink.postEvent(I,b)),v=e.hostCompanion?.onSessionEvent?.(I=>{const b=dg(I);!e.terminalSignal.aborted&&b&&e.eventSink.postEvent(b.type,b.payload)})??(()=>{}),h=im({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled}),y=$m({identity:e.identity,storage:e.storage,account:e.account,presentation:e.hostPresentation,network:e.network,authorization:d,authorizationContext:e.authorizationContext,operationContext:t,files:e.files,transfer:e.transfer,fileRegistry:a,requestGate:s,requestPolicyEnabled:r.enabled});const N=ry({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});f=Ug({registry:a,media:e.media,operationContext:t});const C=[{name:"gameSaves",handlers:y.handlers},{name:"auth",handlers:Ch({authorization:d})},{name:"user",handlers:{...xy({user:l,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...Pf({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:Jp({prepareScreenshot:e.prepareScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:u.handlers},{name:"storage",handlers:N.handlers},{name:"network",handlers:pp({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[En]:async()=>{throw cn("CAPABILITY_UNAVAILABLE","当前 Runtime 不支持工作区卡片刷新")}}},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"media",handlers:f.handlers},{name:"ui",handlers:ay({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:hg({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:cp({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:I=>u.applyOrientation({mode:"portrait",hideCapsule:!1},I)}:{}})},{name:"cloud",handlers:h.handlers},{name:"companion",handlers:ig({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],_=Wy(C);let k=!1;const F=()=>{k||(k=!0,e.terminalSignal.removeEventListener("abort",F),u?.dispose(),f?.dispose(),h?.dispose(),y?.dispose(),w(),v(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?F():e.terminalSignal.addEventListener("abort",F,{once:!0});const j=new Set(["file.readText","file.readBytes","file.stat"]),g=(I,b)=>j.has(I)&&Au(b)&&a.isCompanionAttachmentRef(b.target);return{modules:C,handlers:_,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:g,allowsGameSaveAccess:y.allowsRead,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...N.diagnostics?{storageDiagnostics:N.diagnostics}:{},dispose:F}}catch(N){throw u?.dispose(),f?.dispose(),h?.dispose(),y?.dispose(),w(),v(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),N}}function $y(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Wy(e){const t=new Map(tt.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=tt.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==tt.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Ky="heybox-mini-dev:";function Ka(e){try{return Zy(new URL(e))}catch{return!1}}function Zy(e){return e.protocol===Ky}function Jy(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Xy(e)}function Xy(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 eE=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function tE(e,t){const r=[],n=rE(e.environmentInfo,r),i=dn(n?.appVersion,"host.appVersion",r),o=iE(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:nE(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:dn(t.miniProgramId),version:dn(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function rE(e,t){if(e!=null){if(Mu(e))return e;t.push("environmentInfo")}}function nE(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function iE(e,t){if(e==null)return{name:"unknown",version:null};if(!Mu(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=eE.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:dn(e.version,"operatingSystem.version",t)}}function dn(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const oE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",sE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",aE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",cE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function dE(e,t,r,n,i="dark"){X(n);const o=e.defaultView;if(!o||!e.body)throw new Error("截图水印缺少可用的展示窗口");const s=e.createElement("div"),a=i==="light",c=a?"black":"white";s.dataset.miniProgramScreenshotWatermark="",s.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);s.style.cssText=`position:absolute;left:${r.left+o.scrollX}px;top:${r.top+o.scrollY+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const u=e.createElement("div");u.style.cssText=`display:flex;flex-direction:column;align-items:center;width:${r.width/d}px;height:57px;transform:scale(${d});transform-origin:top left;font-family:"PingFang SC",sans-serif;`;const 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?aE:oE,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 y=e.createElement("img");y.src=a?cE:sE,y.style.cssText="width:12px;height:12px;flex-shrink:0;";const w=e.createElement("span");w.textContent=t?.trim()||"小程序工坊",w.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const v=e.createElement("div");v.textContent="小黑盒工坊小程序",v.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(y,w),f.append(l,h),u.append(f,v),s.append(u),e.body.append(s);const N=()=>{s.remove(),n.removeEventListener("abort",N)};n.addEventListener("abort",N,{once:!0});try{return await $(()=>Promise.all([l.decode(),y.decode()]),n),await $(()=>new Promise(C=>{let _=o.requestAnimationFrame(()=>{_=o.requestAnimationFrame(()=>{n.removeEventListener("abort",k),C()})});const k=()=>o.cancelAnimationFrame(_);n.addEventListener("abort",k,{once:!0})}),n),N}catch(C){throw N(),C}}const uE=1,Nu="allow-scripts allow-same-origin",lE="",fE="no-referrer";function hE(e=Nu){return!e.split(/\s+/).includes("allow-same-origin")}function Za(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const mE=new Set(["javascript:","data:","blob:","file:"]),Ja="xiaoheihe.cn";function gE(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(mE.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!IE(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function pE(e,t){const r=new URL(e);return r.searchParams.set(Tl,t),r.toString()}function yE(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=EE(r)??wE(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function EE(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function wE(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function Xa(e){const t=new URL(e);return As(t)?"loopback":Ms(t)?"lan":"production"}function IE(e,t,r){return AE(e)||As(e)||Ms(e)&&NE(t,r)}function AE(e){return e.protocol==="https:"&&TE(e.hostname)}function As(e){return e.protocol==="http:"&&ME(e.hostname)}function ME(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Ms(e){return e.protocol==="http:"&&DE(e.hostname)}function NE(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return As(r)||Ms(r)}catch{return!1}}function DE(e){const t=SE(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function SE(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 TE(e){return e===Ja||e.endsWith(`.${Ja}`)}const _E=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"]),bE=new Set(["url","inline","eval","unknown"]),OE=/^\/(?:\:segment(?:\/\:segment)*)?$/,vE=/^[a-f0-9]{64}$/,CE=255,LE=160,RE=256;function PE(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!_E.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>RE||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!bE.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=kE(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>LE||!OE.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!vE.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 kE(e){if(e!==void 0&&!(typeof e!="string"||e.length>CE))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const xE=/^(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 UE(e){if(!e?.minimumSdkVersion)throw ee("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=ut(e.minimumSdkVersion),r=e.sdkVersion?ut(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=ut("0.6.0");if(!r){if(un(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(un(r,t)<0)throw ee("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:un(r,ut("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function jE(e,t){if(typeof t!="string"||!ut(t))throw ee("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw ee("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function Du(e,t){const r=ut(e),n=ut(t);if(!(!r||!n))return un(r,n)}function ut(e){const t=xE.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 un(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],o=t.prerelease[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const Di=["android","ios","ohos","windows","macos","linux"],zE="0.9.0",HE=Object.freeze(["android","ios","ohos","windows","macos"]),Su="该小程序暂不支持当前平台",FE="PLATFORM_UNSUPPORTED";function VE(e){return typeof e=="string"&&Di.includes(e)}function BE(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 GE(e){const t=e.manifest;if(!WE(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=tc(e.sdkVersion)??tc(t.sdkVersion);return qE(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:YE()}const r=Tu(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function QE(e){const t=BE(e.operatingSystemName);if(!t)return Lt("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Lt("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Di,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=GE({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Lt("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):ec(t,s)}if(r.effectivePlatforms===void 0)return Lt("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=Tu(r.effectivePlatforms);if("reason"in n)return Lt("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=$E(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return ec(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function ec(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Lt("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Lt(e,t={}){return{status:"denied",reason:e,message:Su,...t}}function YE(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:HE,platformsDeclared:!1,policy:"legacy_mobile_default"}}function Tu(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(!VE(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Di.filter(r=>t.has(r)))}}function qE(e){if(typeof e!="string"||!e.trim())return!1;const t=Du(e.trim(),zE);return t!==void 0&&t>=0}function tc(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function $E(e){return e==="explicit"||e==="legacy_mobile_default"}function WE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const KE=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 ZE(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:JE(i.pathname),sanitizedPathnameHash:XE(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function JE(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function XE(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 v=0;v<16;v+=1)o[v]=s.getUint32(a+v*4,!1);for(let v=16;v<64;v+=1){const N=o[v-15],C=o[v-2],_=Ue(N,7)^Ue(N,18)^N>>>3,k=Ue(C,17)^Ue(C,19)^C>>>10;o[v]=o[v-16]+_+o[v-7]+k>>>0}let[c,d,u,f,l,h,y,w]=i;for(let v=0;v<64;v+=1){const N=w+(Ue(l,6)^Ue(l,11)^Ue(l,25))+(l&h^~l&y)+KE[v]+o[v]>>>0,C=(Ue(c,2)^Ue(c,13)^Ue(c,22))+(c&d^c&u^d&u);w=y,y=h,h=l,l=f+N>>>0,f=u,u=d,d=c,c=N+C>>>0}[c,d,u,f,l,h,y,w].forEach((v,N)=>{i[N]=i[N]+v>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function Ue(e,t){return e>>>t|e<<32-t}const ew=1e4,tw=1e4,$i=2e3,rw=2,nw="open-with-native-credential-policy",_u="安全提示",bu="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class iw{nonce=Za();runtimeId=Za();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;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;sdkVersionDecision;platformGateDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;unexpectedDocumentLoadTimer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=pd(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities});this.ports=r.ports,this.primitiveAvailability=r.primitiveAvailability,this.effectiveCapabilities=r.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const n=this.identity.miniProgramId?.trim();if(n)return{miniProgramId:n,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??ew,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics;return t?{storage:t}:{}}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:(hw(),this.startPromise=this.createReadyPromise(),this.setState("starting"),this.setStatus("starting"),this.launch().catch(t=>{this.failRuntime(t)}),this.startPromise)}destroy(){if(this.stateValue==="destroyed")return;const t=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.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;this.runtimePermissions=Wl(t.runtimePermissions),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=UE(t.sdkVersionPolicy);const n=tE(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=QE({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw pw(this.platformGateDecision);if(this.miniProgramDetail=yw(t),this.effectiveCapabilities=gd(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),cw(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(uw(i)),this.launchUrl=i,this.miniProgramSrc=pE(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=as(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:pt,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,qe(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[pt])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=qy({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,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,prepareScreenshot:(n,i,o)=>{const s=this.sdkVersionDecision?.sdkVersion;return!s||(Du(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):dE(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=By({handlers:this.capabilityGraph.handlers,runDisplayRequest:this.capabilityGraph.runDisplayRequest,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,allowsGameSaveAccess:this.capabilityGraph.allowsGameSaveAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:u})=>{const f={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...u?{network:u}:{}};qe(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new tf({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,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.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 aw(t)?t:Ou(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 gE(t,r,{allowPrivateNetwork:Ka(r)||rc(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??fw)({message:bu,title:_u,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Xa(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!Ka(r)&&!rc(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{nc(),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(()=>nc())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",lE),this.iframe.setAttribute("referrerpolicy",fE),this.iframe.setAttribute("sandbox",Nu)}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.lifecycleDisposer=null;for(const r of t)try{r?.()}catch{}}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(),qe(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(),qe(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{jE(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>=rw)){this.failRuntime(ee("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Br,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},$i),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Br})}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(),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(Br,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Br})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&(this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(ee("UNEXPECTED_DOCUMENT_LOAD",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时")))},r.waitingForDocument?tw:$i))}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()},$i))}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()}handleDuplicateBridgeHandshake(){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"}),this.documentRevalidationPending&&this.resendDocumentRevalidationProbe()}handleInternalBridgeEvent(t){if(t.method===bl){this.handleCspViolation(t.payload);return}if(t.method!==_l)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"||!yE(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=PE(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){qe(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=ZE(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:uE,launchUrlType:Xa(t),networkPolicy:nw})}failRuntime(t){const r=ow(t);return this.isInactive()||(this.terminalError=r,this.terminalController.abort(r),this.postBridgeError(r),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),this.setState("failed"),this.teardownIframe(r),qe(this.options.onError,sw(r)),this.rejectReady?.(r)),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.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!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,qe(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){qe(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 ow(e){const t=as(e);return si(e)&&"cause"in e&&Ou(t,e.cause),t}function Ou(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function sw(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function aw(e){return si(e)&&typeof e.code=="string"&&typeof e.message=="string"}function si(e){return!!e&&typeof e=="object"}function qe(e,t){try{e?.(t)}catch{}}function cw(e,t,r){try{e?.(t,r)}catch{}}function rc(e){try{const t=new URL(e);return t.protocol==="http:"&&Jy(t.hostname)}catch{return!1}}function dw(e){try{return new URL(e).origin}catch{return}}function uw(e){return hE()?"*":dw(e)}function lw(e){return`${_u}
2
2
 
3
3
  ${bu}
4
4