@heybox/hb-sdk 0.9.6-alpha.4 → 0.9.6-alpha.5

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 (32) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +2 -0
  3. package/dist/cli-chunks/{artifact-D_M6R8VV.cjs → artifact-DVC4uf_d.cjs} +3 -3
  4. package/dist/cli-chunks/{build-BKNp4DKT.cjs → build-Cnbra2Uh.cjs} +5 -5
  5. package/dist/cli-chunks/{create-qW5pV_nK.cjs → create-BA6LJaSN.cjs} +1 -1
  6. package/dist/cli-chunks/{dev-BCwp9SuY.cjs → dev-DhunXM74.cjs} +339 -227
  7. package/dist/cli-chunks/{dev-context-Cjn8A7zv.cjs → dev-context-ChFPpG-d.cjs} +2 -2
  8. package/dist/cli-chunks/{doctor-DzZ_fxug.cjs → doctor-of3bxqi4.cjs} +1 -1
  9. package/dist/cli-chunks/{games-oeSJAEM6.cjs → games-Cal1suXc.cjs} +1 -1
  10. package/dist/cli-chunks/{index-CET9kH6C.cjs → index-D-tz0KHY.cjs} +18 -17
  11. package/dist/cli-chunks/{index-jyCJyGf8.cjs → index-HKZRLLPE.cjs} +1 -1
  12. package/dist/cli-chunks/{index.esm-buwSxNH8.cjs → index.esm-BEoQF0yq.cjs} +7 -6
  13. package/dist/cli-chunks/{login-B9uQ4Duc.cjs → login-Zl2mfKS3.cjs} +1 -1
  14. package/dist/cli-chunks/{project-vite-xtntRhkc.cjs → project-vite-DEBchdPu.cjs} +1 -1
  15. package/dist/cli-chunks/{remote-C-qyyMIQ.cjs → remote-CRhsafjv.cjs} +6 -6
  16. package/dist/cli-chunks/{runtime-permission-env-D6wAj0cw.cjs → runtime-permission-env-B2j6D1ts.cjs} +2 -2
  17. package/dist/cli-chunks/{skill-av-4cZEX.cjs → skill-O1q_ccfW.cjs} +2 -2
  18. package/dist/cli-chunks/{version-BMiC4gu_.cjs → version-BOBr2N1h.cjs} +1 -1
  19. package/dist/cli.cjs +1 -1
  20. package/dist/devtools/browser-dev-host/assets/browser-dev-host-CTLTrYRi.js +103 -0
  21. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-c9mxCZ3M.js → desktop-app-launch-B8Nuahot.js} +3 -3
  22. package/dist/devtools/browser-dev-host/assets/{index-DNgaNjCW.js → index-DkQhQiKD.js} +4 -4
  23. package/dist/devtools/browser-dev-host/assets/index-QPl84u9f.css +1 -0
  24. package/dist/devtools/browser-dev-host/index.html +3 -3
  25. package/dist/index.cjs.js +1 -1
  26. package/dist/index.esm.js +1 -1
  27. package/dist/vite.cjs.js +1 -1
  28. package/dist/vite.esm.js +1 -1
  29. package/package.json +6 -6
  30. package/skill/skill.json +4 -4
  31. package/dist/devtools/browser-dev-host/assets/browser-dev-host-tfBfReOu.js +0 -103
  32. package/dist/devtools/browser-dev-host/assets/index-DSTlrpnQ.css +0 -1
@@ -0,0 +1,103 @@
1
+ import{H as xs,aK as ll,bf as fl,X as hl,a_ as ml,a$ as gl,aw as zr,bp as $,aV as Kc,k as Zc,am as pl,ax as Jc,aD as yl,bj as ir,aO as Xc,aQ as El,g as ed,ah as td,v as wl,P as rd,az as Il,i as Al,aX as nd,ak as Ml,aG as id,y as Nl,aM as od,u as Dl,aW as Sl,bh as _l,bg as Tl,d as bl,h as Ol}from"./desktop-app-launch-B8Nuahot.js";const An="workspaceCards.requestRefresh",Mn="auth.getAccountState",Nn="auth.login",Dn="user.getFollowStatus",Sn="user.requestFollowAuthor",vl="gameSaves.list",Ll="gameSaves.sync",Cl="gameSaves.getFile",Rl="gameSaves.readParsedData",_n="user.getInfo",Tn="user.revokeAuthorization",bn="user.getSteamGameList",Nr="user.showAppreciation",On="share.copyLink",vn="share.showShareMenu",Ln="share.screenshot",wt="viewport.setDisplay",Cn="viewport.getWindowInfo",Rn="viewport.setNavigationBarStyle",Dr="storage.getStorage",Sr="storage.setStorage",Pn="network.request",kn="network.download",xn="network.upload",Un="files.pickFiles",jn="files.pickDirectory",zn="files.saveFile",_r="file.create",Tr="file.remove",Hn="file.exists",br="file.readText",Fn="file.writeText",Or="file.readBytes",Vn="file.writeBytes",vr="file.stat",Bn="directory.create",Lr="directory.remove",Gn="directory.exists",Qn="directory.list",Cr="media.pick",Yn="ui.showToast",qn="ui.showLoading",Wn="ui.hideLoading",$n="device.vibrate",Kn="device.setClipboard",Zn="device.executeProtocol",Jn="navigation.close",Xn="navigation.reload",ei="navigation.openAppPage",We="cloud.leaderboard.submit",Ce="cloud.leaderboard.getList",rt="cloud.leaderboard.getCurrentUserEntry",It="cloud.leaderboard.deleteCurrentUserEntry",Ve="cloud.leaderboard.getInfo",Qt="cloud.storage.getStorage",Yt="cloud.storage.setStorage",qt="cloud.storage.removeItem",At="cloud.storage.getKeys",mi="companion.getInfo",gi="companion.getPreparationStatus",pi="companion.prepare",yi="companion.cancelPreparation",Ei="companion.getActiveSession",wi="companion.launch",Ii="companion.session.write",Ai="companion.session.closeStdin",Mi="companion.session.terminate",Ni="companion.session.ackOutput",Di="companion.openAttachment",Si="companion.showNotification",nt=[...[vl,Ll,Cl,Rl].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),{method:An,module:"workspaceCards",capability:An,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:Mn,module:"auth",capability:Mn,requirement:{kind:"none"},risk:"low"},{method:Nn,module:"auth",capability:Nn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Dn,module:"user",capability:Dn,requirement:{kind:"none"},risk:"low"},{method:Sn,module:"user",capability:Sn,requirement:{kind:"none"},risk:"high"},{method:_n,module:"user",capability:_n,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Tn,module:"user",capability:Tn,requirement:{kind:"none"},risk:"high"},{method:bn,module:"user",capability:bn,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:Nr,module:"user",capability:Nr,requirement:{kind:"none"},risk:"medium"},{method:On,module:"share",capability:On,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:vn,module:"share",capability:vn,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Ln,module:"share",capability:Ln,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Cn,module:"viewport",capability:Cn,requirement:{kind:"none"},risk:"low"},{method:Rn,module:"viewport",capability:Rn,requirement:{kind:"none"},risk:"low"},{method:wt,module:"viewport",capability:wt,requirement:{kind:"none"},risk:"low"},{method:Dr,module:"storage",capability:Dr,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:Sr,module:"storage",capability:Sr,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Pn,module:"network",capability:Pn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:kn,module:"network",capability:kn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:xn,module:"network",capability:xn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Un,module:"files",capability:Un,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:jn,module:"files",capability:jn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:zn,module:"files",capability:zn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_r,module:"file",capability:_r,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Tr,module:"file",capability:Tr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Hn,module:"file",capability:Hn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:br,module:"file",capability:br,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Fn,module:"file",capability:Fn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Or,module:"file",capability:Or,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Vn,module:"file",capability:Vn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:vr,module:"file",capability:vr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Bn,module:"directory",capability:Bn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Lr,module:"directory",capability:Lr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Gn,module:"directory",capability:Gn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Qn,module:"directory",capability:Qn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Cr,module:"media",capability:Cr,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:Yn,module:"ui",capability:Yn,requirement:{kind:"none"},risk:"low"},{method:qn,module:"ui",capability:qn,requirement:{kind:"none"},risk:"low"},{method:Wn,module:"ui",capability:Wn,requirement:{kind:"none"},risk:"low"},{method:$n,module:"device",capability:$n,requirement:{kind:"none"},risk:"low"},{method:Kn,module:"device",capability:Kn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Zn,module:"device",capability:Zn,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:Jn,module:"navigation",capability:Jn,requirement:{kind:"none"},risk:"medium"},{method:Xn,module:"navigation",capability:Xn,requirement:{kind:"none"},risk:"medium"},{method:ei,module:"navigation",capability:ei,requirement:{kind:"none"},risk:"medium"},{method:We,module:"cloud",capability:We,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ce,module:"cloud",capability:Ce,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:rt,module:"cloud",capability:rt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:It,module:"cloud",capability:It,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ve,module:"cloud",capability:Ve,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Qt,module:"cloud",capability:Qt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:Yt,module:"cloud",capability:Yt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:qt,module:"cloud",capability:qt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:At,module:"cloud",capability:At,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[mi,gi,pi,yi,Ei,wi,Ii,Ai,Mi,Ni,Di,Si].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],lt="heybox:miniprogram",sd=2,Pl="hb_mini_bridge_nonce",ad="sdk.handshake",Yr="runtime.location.probe",kl="sdk.location.report",xl="sdk.csp.violation",cd="operation.progress",Ul="companion.session.output",jl="companion.session.exit",zl="companion.session.ownershipLost";function Hl(e){return!ke(e)||e.namespace!==lt||e.version!==1&&e.version!==2||!ce(e.nonce)?!1:e.type==="handshake"?ce(e.id)&&e.method===ad&&e.error===void 0&&Wl(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||$l(e.error)):e.type==="event"?!ce(e.method)||e.error!==void 0?!1:e.method===cd?e.version===2&&ce(e.id)&&ql(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 ds(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function dd(e){return ke(e)?e.kind==="sandbox"?be(e,["kind"]):e.kind==="directory"&&ce(e.handleId)&&be(e,["kind","handleId"]):!1}function Wt(e){return!ke(e)||e.kind!=="file"?!1:ce(e.handleId)?be(e,["kind","handleId"]):dd(e.root)&&ds(e.relativePath)&&be(e,["kind","root","relativePath"])}function ud(e){return!ke(e)||e.kind!=="directory"?!1:ce(e.handleId)?be(e,["kind","handleId"]):dd(e.root)&&(e.relativePath==="."||ds(e.relativePath))&&be(e,["kind","root","relativePath"])}function Fl(e){return ke(e)&&e.kind==="file"&&ce(e.name)&&Kl(e.mode)&&Wt(e.ref)&&be(e,["kind","name","mode","ref"])}const ld=20,Us=["type","mimeType","size","width","height","previewUrl","file"];function Vl(e){return e===void 0?!0:!(!ke(e)||!be(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&&(!Zl(e.maxCount,1,ld)||e.source==="camera"&&e.maxCount!==1))}function fd(e){if(!ke(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!be(e,t?[...Us,"durationMs"]:Us)||!ce(e.mimeType)||!Xe(e.size)||!js(e.width)||!js(e.height)||!ce(e.previewUrl)||!Gl(e.file)?!1:t?Xe(e.durationMs):!0}function Bl(e){if(!Array.isArray(e)||e.length<1||e.length>ld)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!fd(e[t]))return!1;return!0}function Gl(e){return!Fl(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&ce(e.ref.handleId)}function hd(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function Ql(e){return!ke(e)||!Xe(e.loaded)||typeof e.lengthComputable!="boolean"||!be(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Xe(e.total)&&e.loaded<=e.total:e.total===void 0}function Yl(e){return ke(e)?e.phase==="downloading"?Xe(e.loaded)&&(e.total===void 0||Xe(e.total)&&e.loaded<=e.total)&&be(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Xe(e.processed)&&Xe(e.total)&&e.processed<=e.total&&be(e,["phase","processed","total"]):!1}function ql(e){return Ql(e)||Yl(e)}function Wl(e){return ke(e)&&ce(e.href)&&typeof e.userAgent=="string"&&ce(e.sdkVersion)}function $l(e){return ke(e)&&ce(e.code)&&typeof e.message=="string"}function Kl(e){return e==="read"||e==="readwrite"}function Xe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function js(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Zl(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 be(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function ke(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Mt=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards"],md=[{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(Mt);const Jl=new Set(Mt);function Xl(e){return Jl.has(e)}function Re(e){if(!qr(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(!qr(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),!!Xl(o)){if(o==="network"){const s=n.config;if(!qr(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&&(!qr(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 qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const sn=["network","companion","appProtocol"];function gd(e){if(!or(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>sn.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!or(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(!or(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(!or(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!or(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>sn.indexOf(n.key)-sn.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function ef(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Re(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of sn)!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 us(e){const t=Re(e.runtimePermissions),r=gd(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of Mt)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:md.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=pd(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:Mt.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function pd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function or(e,t){return pd(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const $t=["identity","profile","steam_account"],tf=/^[a-z][a-z0-9-]{0,31}$/,yd=["COMPANION_UNSUPPORTED","COMPANION_PREVIEW_UNSUPPORTED","COMPANION_NOT_DECLARED","COMPANION_TARGET_UNSUPPORTED","COMPANION_NOT_PREPARED","COMPANION_PREPARATION_CANCELLED","COMPANION_DOWNLOAD_FAILED","COMPANION_DESCRIPTOR_UNAVAILABLE","COMPANION_ARCHIVE_INVALID","COMPANION_INTEGRITY_FAILED","COMPANION_ENTRYPOINT_INVALID","COMPANION_USER_CANCELLED","COMPANION_ELEVATION_DENIED","COMPANION_OS_BLOCKED","COMPANION_LAUNCH_FAILED","COMPANION_SESSION_VERSION_MISMATCH","COMPANION_SESSION_OWNERSHIP_LOST","COMPANION_SESSION_EXITED","COMPANION_PIPE_CLOSED","COMPANION_OUTPUT_LIMIT","COMPANION_PROCESS_CRASHED","COMPANION_ATTACHMENT_NOT_FOUND","COMPANION_NOTIFICATION_UNAVAILABLE","COMPANION_TERMINATE_FAILED"];function rf(e){if(e.schema_version!==1||!/^[a-f0-9]{32}$/.test(e.session_id)||!Number.isSafeInteger(e.revision)||e.revision<1||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(e.sdk_version)||!e.declared_permissions||typeof e.declared_permissions!="object"||Array.isArray(e.declared_permissions)||!Array.isArray(e.platforms)||e.platforms.some(r=>!["android","ios","ohos","windows","macos","linux"].includes(r))||new Set(e.platforms).size!==e.platforms.length)throw new Error("开发快照无效");const t={};for(const r of Mt){const n=e.declared_permissions[r];if(n){if(typeof n.enabled!="boolean")throw new Error("开发权限声明无效");t[r]=r==="network"?{enabled:n.enabled,useOfficialDomain:n.useOfficialDomain===!0}:{enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!Mt.includes(r)))throw new Error("开发权限声明无效");if(e.companion_manifest_sha256!==void 0&&!/^[a-f0-9]{64}$/.test(e.companion_manifest_sha256))throw new Error("开发产物摘要无效");return JSON.stringify({schema_version:1,session_id:e.session_id,revision:e.revision,sdk_version:e.sdk_version,declared_permissions:t,platforms:[...e.platforms].sort(),...e.companion_manifest_sha256?{companion_manifest_sha256:e.companion_manifest_sha256}:{}})}function nf(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return rf(t)===e?t:void 0}catch{return}}nt.map(e=>e.method);function of(e){const t=Re(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 sf(e){const t=Re(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 ls(e){return af(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?ee("RUNTIME_ERROR",e.message):ee("UNKNOWN_ERROR","小程序运行时异常",e)}function af(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function cf(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const df=1e3;function uf(e,t=cf()){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<=df}const lf="runtime.gate.probe",Ed=new Set(nt.map(e=>e.method));class ff{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=sd;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:lt,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:lt,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:lt,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:lt,version:2,nonce:this.nonce,type:"event",id:t,method:cd,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=uf(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&&Hl(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:lt,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:ad,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===lf){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,ee("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Ed.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=ls(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:lt,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!hf(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 hf(e){return typeof e=="string"&&Ed.has(e)}function g(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]):mf(e.signal,t);return{...e,signal:r}}function mf(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 gf(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 an(){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:an()}function wd(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 Id="METHOD_FORBIDDEN";function _e(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Id,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 pf=/^[A-Za-z0-9_-]{1,64}$/,zs=1e3;function Ad(e){return pf.test(e)?e:Ef(e)}function yf(e){return`id_${Ad(e.trim())}`}function Ot(e,t){return`hb_miniprogram_${e}_${t}`}function Wr(e){return`hb_miniprogram_keys_${e}`}function Ef(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 Hs={"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"],[An]:["workspaceCards.requestRefresh"],[Mn]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[Nn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Dn]:["account.getCurrentUserId","account.onChange","network.request"],[Sn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[_n]:["account.getCurrentUserId","account.onChange","network.request"],[Tn]:["account.getCurrentUserId","account.onChange","network.request"],[bn]:["account.getCurrentUserId","account.onChange","network.request"],[On]:["presentation.setClipboard"],[vn]:["presentation.showShareMenu"],[Ln]:["presentation.getViewportMetrics","presentation.captureAndShare"],[wt]:["presentation.applyOrientation"],[Cn]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Rn]:["presentation.setNavigationBarStyle"],[Dr]:["storage.getRaw"],[Sr]:["storage.setRaw"],[Pn]:["network.request"],[kn]:["network.stream","files.transfer","files.access"],[xn]:["network.upload","files.access"],[Un]:["files.external"],[jn]:["files.external"],[zn]:["files.save"],[_r]:["files.access"],[Tr]:["files.removeFile"],[Hn]:["files.access"],[br]:["files.access"],[Fn]:["files.access"],[Or]:["files.access"],[Vn]:["files.access"],[vr]:["files.access"],[Bn]:["files.access"],[Lr]:["files.removeDirectory"],[Gn]:["files.access"],[Qn]:["files.access"],[Cr]:["media.pick"],[Nr]:["presentation.showAppreciation"],[Yn]:["presentation.showToast"],[qn]:["presentation.showLoading"],[Wn]:["presentation.hideLoading"],[$n]:["presentation.vibrate"],[Kn]:["presentation.setClipboard"],[Zn]:["protocol.invoke"],[Jn]:["presentation.close"],[Xn]:["presentation.reload"],[ei]:["presentation.openAppPage"],[We]:["account.getCurrentUserId","account.onChange","network.request"],[Ce]:["account.onChange","network.request"],[rt]:["account.getCurrentUserId","account.onChange","network.request"],[It]:["account.getCurrentUserId","account.onChange","network.request"],[Ve]:["account.onChange","network.request"],[Qt]:["account.getCurrentUserId","account.onChange","network.request"],[Yt]:["account.getCurrentUserId","account.onChange","network.request"],[qt]:["account.getCurrentUserId","account.onChange","network.request"],[At]:["account.getCurrentUserId","account.onChange","network.request"],[mi]:["companion.getInfo"],[gi]:["companion.getPreparationStatus"],[pi]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[yi]:["companion.cancelPreparation"],[Ei]:["companion.getActiveSession"],[wi]:["companion.getInfo","companion.launch"],[Ii]:["companion.session.write"],[Ai]:["companion.session.closeStdin"],[Mi]:["companion.session.terminate"],[Ni]:["companion.session.ackOutput"],[Di]:["companion.openAttachment"],[Si]:["companion.showNotification"]},wf=new Set([Nr]);function If(e,t){if(t[e]!==!0)throw wf.has(e)?ee("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):_e(e)}const Af=32*1024*1024,Mf=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Nf(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:Af},i);return Df(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Df(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:Sf(t,Tf(e,"content-type"))}}function Sf(e,t){_f(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||!Mf.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function _f(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 Tf(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function j(e){return typeof e=="function"}function Fs(e){return(...t)=>{throw _e(e)}}function de(e){return async(...t)=>{throw _e(e)}}const bf=(e,t)=>{},Of=()=>()=>{};function vf(e){const t={request:j(e.network?.request)?e.network.request.bind(e.network):de("network.request")},r={...j(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:j(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):de("account.getCurrentUserId"),ensureAuthenticated:j(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):de("account.ensureAuthenticated"),onChange:j(e.account?.onChange)?e.account.onChange.bind(e.account):Of},n={getRaw:j(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):de("storage.getRaw"),setRaw:j(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):de("storage.setRaw")},i={...j(e.presentation?.showSteamLoginRequired)?{showSteamLoginRequired:e.presentation.showSteamLoginRequired.bind(e.presentation)}:{},...j(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...j(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:j(e.presentation?.close)?e.presentation.close.bind(e.presentation):de("presentation.close"),reload:j(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):de("presentation.reload"),openAppPage:j(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):de("presentation.openAppPage"),openWindow:j(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):de("presentation.openWindow"),getViewportMetrics:j(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Fs("presentation.getViewportMetrics"),getNavigationBarHeight:j(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Fs("presentation.getNavigationBarHeight"),setNavigationBarStyle:j(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):de("presentation.setNavigationBarStyle"),showShareMenu:j(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):de("presentation.showShareMenu"),setScreenshotChromeHidden:j(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):bf,captureAndShare:j(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):de("presentation.captureAndShare"),showAppreciation:j(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw ee("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:j(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):de("presentation.showToast"),showLoading:j(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):de("presentation.showLoading"),hideLoading:j(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):de("presentation.hideLoading"),vibrate:j(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):de("presentation.vibrate"),setClipboard:j(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):de("presentation.setClipboard")},o=j(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,j(e.companion?.[c])?e.companion[c].bind(e.companion):de(`companion.${c}`)]));j(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const a={invoke:j(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 Lf(e){const t=Cf(e.files?.sandbox),r=j(e.picker?.pickFiles)&&j(e.picker?.pickDirectory),n=j(e.picker?.saveFile),i=t||r||n||j(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":j(e.account?.getAccountKey),"account.getCurrentUserId":j(e.account?.getCurrentUserId),"account.ensureAuthenticated":j(e.account?.ensureAuthenticated),"account.onChange":j(e.account?.onChange),"network.request":j(e.network?.request),"network.stream":j(e.transfer?.network.open)&&j(e.transfer?.network.release),"network.upload":j(e.transfer?.upload?.upload),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":j(o?.remove),"files.removeDirectory":j(e.files?.sandbox.remove),"files.transfer":j(e.transfer?.files.writeResource),"media.pick":j(e.media?.pick),"storage.getRaw":j(e.scopedStorage?.get)||j(e.storage?.getRaw),"storage.setRaw":j(e.scopedStorage?.set)||j(e.storage?.setRaw),"presentation.close":j(e.presentation?.close),"presentation.reload":j(e.presentation?.reload),"presentation.openAppPage":j(e.presentation?.openAppPage),"presentation.applyOrientation":j(e.presentation?.applyOrientation),"presentation.openWindow":j(e.presentation?.openWindow),"presentation.getViewportMetrics":j(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":j(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":j(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":j(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":j(e.presentation?.captureAndShare),"presentation.showAppreciation":j(e.presentation?.showAppreciation),"presentation.showToast":j(e.presentation?.showToast),"presentation.showLoading":j(e.presentation?.showLoading),"presentation.hideLoading":j(e.presentation?.hideLoading),"presentation.vibrate":j(e.presentation?.vibrate),"presentation.setClipboard":j(e.presentation?.setClipboard),"workspaceCards.requestRefresh":!1,"companion.getInfo":j(e.companion?.getInfo),"companion.getPreparationStatus":j(e.companion?.getPreparationStatus),"companion.prepare":j(e.companion?.prepare),"companion.cancelPreparation":j(e.companion?.cancelPreparation),"companion.getActiveSession":j(e.companion?.getActiveSession),"companion.launch":j(e.companion?.launch),"companion.session.write":j(e.companion?.write),"companion.session.closeStdin":j(e.companion?.closeStdin),"companion.session.terminate":j(e.companion?.terminate),"companion.session.ackOutput":j(e.companion?.ackOutput),"companion.openAttachment":j(e.companion?.openAttachment),"companion.showNotification":j(e.companion?.showNotification),"protocol.invoke":j(e.protocol?.invoke)}}function Cf(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&j(t.file)&&j(t.directory)&&j(t.create)&&j(t.stat)&&j(t.list)}function Vs(e,t){return t?.[e]!==!1}function Rf(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function Md(e,t={}){const r={};for(const n of Object.keys(Hs)){const o=Hs[n].every(a=>e[a]),s=!Rf(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=Vs(n,t.callerCapabilities)&&Vs(n,t.hostCapabilities)&&o&&s}return r}function Nd(e={},t={}){const r=Lf(e),n=Md(r,t);return{ports:vf(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}const Pf=4,kf=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],xf=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),Uf=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],jf=["/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 zf(e,t){const r=Vf(e);return r===null||Bs(r,Uf)?!0:t&&Bs(r,jf)}function Hf(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return kf.some(r=>t===r||t.endsWith(`.${r}`))}function Ff(e){const t=e.trim().toLowerCase();return xf.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Vf(e){let t=e;for(let r=0;r<Pf;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Gs(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Gs(t)}function Bs(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Gs(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Qs(e){return e instanceof le?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function W(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(an());let n;try{n=e()}catch(i){return Promise.reject(Qs(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(an())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(an()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(Qs(d))))})}function Bf(e){return{[Nr]:async(t,r)=>{const n=Ne(e.operationContext,r.signal);if(X(n.signal),t!==void 0)throw g("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw g("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const o=e.presentation.showAppreciation;if(!o)throw g("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await W(()=>o({name:i.name,author:i.author},n),n.signal)}}}function vt(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Ys(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function Dd(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(p,M){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:p,type:M})).catch(()=>{})}catch{}}function u(p){const M=r.get(p);if(!M)throw new Error("Unknown runtime cache scope");return M}function f(p,M){return p.flatMap((w,T)=>{const _=JSON.stringify(p.slice(0,T+1));return[JSON.stringify([_]),JSON.stringify([_,M])]})}function l(p,M){return JSON.stringify(f(p,M).map(w=>n.get(w)??0))}async function m(p,M){const w=u(p),T=JSON.stringify([JSON.stringify(w),...M?[M]:[]]),_=(n.get(T)??0)+1;n.set(T,_),i.add(T);for(const P of a)P(w,M);if(!e.store){i.delete(T),d(M??"*","invalidation");return}try{await e.store.invalidate(w,M)}catch(P){throw d(M??"*","storage_error"),P}n.get(T)===_&&i.delete(T),d(M??"*","invalidation")}function h(p){if(c)throw new Error("Runtime cache manager disposed");const M=o.get(p.namespace);if(M){if(M.sourceCodec!==p.codec||M.definition.codec.version!==p.codec.version||JSON.stringify(M.definition.policy)!==JSON.stringify(p.policy))throw new Error("Conflicting runtime cache namespace");return M.cache}if(!p.namespace||!p.codec.version)throw new Error("Invalid runtime cache definition");const w=Object.freeze({...p.policy}),T=Object.freeze({version:p.codec.version,encode:p.codec.encode.bind(p.codec),decode:p.codec.decode.bind(p.codec),validate:p.codec.validate.bind(p.codec),clone:p.codec.clone.bind(p.codec)}),_=p.namespace;for(const A of[w.ttlMs,w.memoryMaxEntries,w.diskMaxEntries,w.diskMaxBytes,w.maxEntryBytes])if(!Number.isFinite(A)||A<0)throw new Error("Invalid runtime cache policy");const P=new Map,F=new Map,U=new Map;let O=!1;function E(A,I,L){if(c||O||A.aborted||l(I,_)!==L)throw vt()}function S(A){return w.ttlMs>0&&w.persistence==="memory-and-disk"&&!!e.store&&!f(A,_).some(I=>i.has(I))}function v(A,I,L){const k=t();return A.envelopeVersion===1&&JSON.stringify(A.address)===JSON.stringify(I)&&Ys(A.revisions,L)&&A.payload.byteLength<=w.maxEntryBytes&&Number.isFinite(A.cachedAt)&&Number.isFinite(A.expiresAt)&&A.cachedAt<=k&&A.cachedAt>=0&&A.expiresAt>A.cachedAt&&Math.min(A.expiresAt,A.cachedAt+w.ttlMs)>k}function C(A,I,L,k,x){if(!(w.ttlMs<=0||w.memoryMaxEntries<1)){for(const[z,H]of P)Math.min(H.entry.expiresAt,H.entry.cachedAt+w.ttlMs)<=t()&&P.delete(z);for(P.delete(A);P.size>=Math.floor(w.memoryMaxEntries);){const z=P.keys().next();if(z.done)break;P.delete(z.value)}P.set(A,{entry:I,value:L,epoch:k,persistent:x})}}async function y(A,I,L,k){const x={namespace:_,codecVersion:T.version,scopeIds:I,key:A.key},z=JSON.stringify(x);let H=[],V=S(I);if(V)try{H=await e.store.readRevisions(I,_)}catch{V=!1,d(_,"storage_error")}E(k.signal,I,L);async function G(){if(!V)return!0;try{return Ys(H,await e.store.readRevisions(I,_))}catch{return V=!1,d(_,"storage_error"),!1}}const J=P.get(z);if(w.ttlMs>0&&J&&J.epoch===L&&v(J.entry,x,H)&&J.persistent===V&&await G())return E(k.signal,I,L),d(_,"memory_hit"),J.value;if(P.delete(z),V){let Y,ne;try{Y=await e.store.read(x,w.maxEntryBytes),Y&&v(Y,x,H)?ne=T.decode(Y.payload):Y=void 0}catch{Y=void 0,d(_,"storage_error")}if(E(k.signal,I,L),Y&&await G())return E(k.signal,I,L),C(z,Y,ne,L,!0),d(_,"disk_hit"),ne}d(_,"miss");const K=T.validate(await A.load(k.signal));E(k.signal,I,L);const Z=T.clone(K);if(!await G()&&V)throw vt();if(E(k.signal,I,L),w.ttlMs>0){const Y=t();let ne;try{ne=T.encode(Z)}catch{return Z}const ve={envelopeVersion:1,address:x,revisions:V?H:[],cachedAt:Y,expiresAt:Y+w.ttlMs,payload:ne};if(V&&ne.byteLength<=w.maxEntryBytes){let Qe=!0,ye=!1;try{Qe=await e.store.publish(ve,w),ye=Qe}catch{d(_,"storage_error")}if(E(k.signal,I,L),!Qe)throw vt();ye&&d(_,"published")}E(k.signal,I,L),C(z,ve,Z,L,V)}return Z}async function N(A){if(c||O||A.signal?.aborted)return Promise.reject(vt());const I=u(A.scope),L=l(I,_);let k;if(S(I)){const V=new AbortController;U.set(V,I);const G=()=>V.abort();A.signal?.addEventListener("abort",G,{once:!0});let J=()=>{};try{k=await Promise.race([e.store.readRevisions(I,_),new Promise((K,Z)=>{const Y=()=>Z(vt());V.signal.addEventListener("abort",Y,{once:!0}),J=()=>V.signal.removeEventListener("abort",Y)})])}catch{V.signal.aborted||d(_,"storage_error")}finally{J(),U.delete(V),A.signal?.removeEventListener("abort",G)}}E(A.signal??new AbortController().signal,I,L);const x=JSON.stringify([I,A.key,L,k]);let z=F.get(x);if(z?.controller.signal.aborted&&(z=void 0),!z){const V=new AbortController;z={ids:I,controller:V,waiters:0,promise:Promise.resolve(void 0)};const G=z;G.promise=y(A,I,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 J=!1;function K(Y){J||(J=!0,A.signal?.removeEventListener("abort",Z),H.controller.signal.removeEventListener("abort",Z),H.waiters-=1,H.waiters===0&&H.controller.abort(),Y())}function Z(){K(()=>G(vt()))}A.signal?.addEventListener("abort",Z,{once:!0}),H.controller.signal.addEventListener("abort",Z,{once:!0}),H.promise.then(Y=>K(()=>{try{E(A.signal??new AbortController().signal,I,L),V(T.clone(Y))}catch(ne){G(ne)}}),Y=>K(()=>G(Y)))})}function D(A,I){if(I&&I!==_)return;const L=k=>A.every((x,z)=>k[z]===x);for(const[k,x]of P)L(x.entry.address.scopeIds)&&P.delete(k);for(const[k,x]of F)L(x.ids)&&(x.controller.abort(),F.delete(k));for(const[k,x]of U)L(x)&&k.abort()}function R(){if(!O){O=!0,P.clear();for(const A of U.keys())A.abort();U.clear();for(const A of F.values())A.controller.abort();F.clear(),s.delete(R),a.delete(D),o.get(_)?.cache===b&&o.delete(_)}}const b={read:N,invalidateScope:A=>m(A,_),dispose:R};return s.add(R),a.add(D),o.set(_,{definition:{namespace:_,codec:T,policy:w},sourceCodec:p.codec,cache:b}),b}return{createScope(p,M){if(c||!p)throw new Error("Invalid runtime cache scope");const w=Object.freeze({});return r.set(w,[...M?u(M):[],p]),w},register:h,invalidateScope:p=>m(p),dispose(){if(!c){c=!0;for(const p of[...s])p();o.clear(),n.clear(),i.clear()}}}}function Gf(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 Qf=".hb-runtime-cache-v1",Yf=1e3,xi=64*1024,Lt=1e3,qf=2048,sr=32*1024*1024,Wf=1024,cn=new TextEncoder,qs=new TextDecoder("utf-8",{fatal:!0});function ar(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function $r(e){const t=await globalThis.crypto.subtle.digest("SHA-256",cn.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function xe(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ws(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function $f(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function $s(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function Kf(e,t){const r=e.sandbox.directory(Qf),n=r.directory("revisions"),i=r.directory("entries");for(const y of[r,n,i,i.directory("capability-check")])$s(y,["directory","file","create","stat","list","remove"]),$s(y.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(y){d=y,o.abort(),t.signal.removeEventListener("abort",s)}function f(y){if($f(y))throw u(y),y}function l(){if(d)throw d;if(a.signal.aborted)throw ar()}function m(y,N=a.signal){const D=c.then(()=>{if(N.aborted)throw d??ar();return l(),y()},()=>{if(N.aborted)throw d??ar();return l(),y()}).catch(I=>{throw f(I),I});if(c=D.catch(()=>{}),N.aborted)return Promise.reject(d??ar());let R=()=>{};const b=new Promise((I,L)=>{const k=()=>L(d??ar());N.addEventListener("abort",k,{once:!0}),R=()=>N.removeEventListener("abort",k)}),A=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},Yf);return Promise.race([D,b]).finally(()=>{clearTimeout(A),R()})}async function h(){l(),await n.create({recursive:!0,exclusive:!1},a),l(),await i.create({recursive:!0,exclusive:!1},a),l()}async function p(y,N){const D=n.file(`${await $r([y,N??null])}.revision`);await w(D);let R=!1;try{await D.create({recursive:!1,exclusive:!0},a),R=!0}catch(I){f(I),l()}if(R){const I=Ws();return await D.write(cn.encode(I),a),l(),I}const b=await D.stat(a);if(b.size<1||b.size>128)throw new Error("缓存 revision 文件损坏");const A=qs.decode(await D.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(A))throw new Error("缓存 revision 文件损坏");return l(),A}async function M(y){const N=await y.list({limit:Lt},a);if(N.length>=Lt)throw new Error("缓存目录超过治理上限");return N}async function w(y){try{await y.stat(a);return}catch(D){if(!Kr(D))throw D}if((await M(n)).length>=Lt-1)throw new Error("缓存 metadata 超过治理上限")}async function T(y,N){await h();const D=[];for(let R=0;R<y.length;R+=1){const b=y.slice(0,R+1);D.push(await p(b),await p(b,N))}return D}async function _(y){return r.directory(`entries/${await $r([y.namespace,y.codecVersion,y.scopeIds])}`)}async function P(y){return(await _(y)).file(`${await $r(y.key)}.cache`)}async function F(y,N){const D=await y.stat(a);if(D.size<5||D.size>N+xi+4)throw new Error("缓存条目超过大小限制");const R=await y.read(a);if(l(),R.length!==D.size)throw new Error("缓存条目读取不完整");const b=new DataView(R.buffer,R.byteOffset,R.byteLength).getUint32(0);if(b<1||b>xi||b+4>R.length)throw new Error("缓存信封损坏");const A=JSON.parse(qs.decode(R.subarray(4,b+4))),I=R.slice(b+4);if(A.envelopeVersion!==1||!A.address||!Array.isArray(A.address.scopeIds)||!A.address.scopeIds.every(L=>typeof L=="string")||typeof A.address.namespace!="string"||typeof A.address.codecVersion!="string"||typeof A.address.key!="string"||!Array.isArray(A.revisions)||A.revisions.length!==A.address.scopeIds.length*2||!A.revisions.every(L=>typeof L=="string"&&L.length>0)||!Number.isSafeInteger(A.cachedAt)||!Number.isSafeInteger(A.expiresAt)||A.cachedAt<0||A.expiresAt<=A.cachedAt||A.payloadBytes!==I.length||I.length>N)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:A.address,revisions:A.revisions,cachedAt:A.cachedAt,expiresAt:A.expiresAt,payload:I}}async function U(y){if(!y.remove)throw new Error("Host 不支持缓存文件删除");await y.remove(a)}async function O(y){try{if((await y.file.stat(a)).size!==y.size)return!1;const N=await F(y.file,sr);return!xe(N.address,y.entry.address)||!xe(N.revisions,y.entry.revisions)||N.cachedAt!==y.entry.cachedAt||N.expiresAt!==y.entry.expiresAt||!xe(await E(N.payload),await E(y.entry.payload))?!1:(await U(y.file),!0)}catch(N){if(Kr(N))return!0;throw N}}async function E(y){const N=await globalThis.crypto.subtle.digest("SHA-256",y);return Array.from(new Uint8Array(N),D=>D.toString(16).padStart(2,"0")).join("")}async function S(){const y=await M(n);let N=0;for(const A of y)if(A.kind==="file"&&(N+=(await A.stat(a)).size,N>sr))throw new Error("缓存扫描超过字节上限");const D=[];let R=0,b=N;for(const A of await M(i)){if(A.kind!=="directory")throw new Error("缓存目录结构损坏");for(const I of await M(A)){if(I.kind!=="file"||++R>qf)throw new Error("缓存文件超过治理上限");const L=(await I.stat(a)).size;if(b+=L,b>sr)throw new Error("缓存扫描超过字节上限");try{const k=await F(I,sr);D.push({file:I,entry:k,size:(await I.stat(a)).size,bucketName:A.name})}catch(k){f(k),l(),Kr(k)||await U(I)}}}return{entries:D,metadataBytes:N}}async function v(){for(const y of await M(i))if(y.kind==="directory"&&y.remove&&(await M(y)).length===0)try{await y.remove({recursive:!1},a)}catch(N){f(N),l()}}function C(y){const{payload:N,...D}=y,R=cn.encode(JSON.stringify({...D,payloadBytes:N.length}));if(R.length>xi)throw new Error("缓存信封过大");const b=new Uint8Array(4+R.length+N.length);return new DataView(b.buffer).setUint32(0,R.length),b.set(R,4),b.set(N,R.length+4),b}return{readRevisions:(y,N)=>m(()=>T(y,N)),read:(y,N)=>m(async()=>{l();const D=await P(y);let R;try{R=await F(D,N)}catch(b){if(l(),Kr(b))return;throw b}if(!(!xe(R.address,y)||R.expiresAt<=Date.now())&&xe(R.revisions,await T(y.scopeIds,y.namespace)))return R}),publish:(y,N)=>m(async()=>{l();const{address:D}=y;if(!xe(y.revisions,await T(D.scopeIds,D.namespace)))return!1;const R=C(y);if(y.payload.length>N.maxEntryBytes||R.length>N.diskMaxBytes||N.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await h();const b=await _(D),A=await P(D),I=await S(),L=[],k=new Map;for(const H of I.entries){if(H.bucketName===b.name&&H.file.name===A.name)continue;const V=JSON.stringify([H.entry.address.scopeIds,H.entry.address.namespace]);let G=k.get(V);if(G||(G=await T(H.entry.address.scopeIds,H.entry.address.namespace),k.set(V,G)),H.entry.expiresAt<=Date.now()||!xe(H.entry.revisions,G)){if(!await O(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===b.name);return L.length+1>Wf||R.length+I.metadataBytes+L.reduce((V,G)=>V+G.size,0)>sr||H.length+1>Math.min(N.diskMaxEntries,Lt-1)||R.length+H.reduce((V,G)=>V+G.size,0)>N.diskMaxBytes}for(;x();){const H=L.filter(J=>J.bucketName===b.name),G=H.length+1>Math.min(N.diskMaxEntries,Lt-1)||R.length+H.reduce((J,K)=>J+K.size,0)>N.diskMaxBytes?H[0]:L[0];if(!G||!await O(G))throw new Error("缓存容量不足或条目已变化");L.splice(L.indexOf(G),1)}await v();const z=await M(i);if(!z.some(H=>H.name===b.name)&&z.length>=Lt-1)throw new Error("缓存目录超过治理上限");if(await b.create({recursive:!0,exclusive:!1},a),!xe(y.revisions,await T(D.scopeIds,D.namespace)))return!1;try{await A.create({recursive:!1,exclusive:!0},a)}catch(H){f(H),await A.stat(a)}return await A.write(R,a),l(),xe(y.revisions,await T(D.scopeIds,D.namespace))}),invalidate:(y,N)=>m(async()=>{await h();const D=n.file(`${await $r([y,N??null])}.revision`);await w(D);try{await D.create({recursive:!1,exclusive:!0},a)}catch(R){f(R),await D.stat(a)}await D.write(cn.encode(Ws()),a),l();try{const{entries:R}=await S();for(const b of R){if(N!==void 0&&b.entry.address.namespace!==N||!y.every((I,L)=>b.entry.address.scopeIds[L]===I))continue;const A=await T(b.entry.address.scopeIds,b.entry.address.namespace);xe(b.entry.revisions,A)||await O(b)}await v()}catch(R){f(R),l()}})}}function Kr(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const Zf="RATE_LIMITED_BY_RUNTIME",Jf="RATE_LIMITED",Sd=20,_d=40,Td=150,bd=20,Od=1e4,vd=45e3,Ld=1,Xf=300*1e3,eh=64;function Ct(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function th(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function rh(e={}){const t=e.now??Date.now,r=th(e.coalesceWindowMs,Td),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,Ct(e.budget?.ratePerSecond,Sd)),burst:Math.max(1,Math.floor(Ct(e.budget?.burst,_d)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(Ct(e.loopDetection?.maxCalls,bd))),windowMs:Math.max(1,Math.floor(Ct(e.loopDetection?.windowMs,Od)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(Ct(e.circuitBreaker?.failureThreshold,Ld))),openMs:Math.max(1,Math.floor(Ct(e.circuitBreaker?.openMs,vd)))},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 m(O){try{e.onReport?.(O)}catch{}}function h(O,E){if(!i)return{exceeded:!1,count:0};const S=a.get(O)??[],v=E-i.windowMs;let C=0;for(;C<S.length&&S[C]<=v;)C+=1;C>0&&S.splice(0,C);const y=S.length>=i.maxCalls;return y||(S.push(E),S.length>i.maxCalls+1&&S.splice(0,S.length-(i.maxCalls+1))),a.set(O,S),{exceeded:y,count:S.length}}function p(O){if(!n)return!0;const E=Math.max(0,O-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+E*n.ratePerSecond),u.updatedAt=O,u.tokens<1?!1:(u.tokens-=1,!0)}function M(O){if(!n)return 0;const E=Math.max(0,O-u.updatedAt)/1e3,S=Math.min(n.burst,u.tokens+E*n.ratePerSecond);return Math.max(0,Math.ceil((1-S)/n.ratePerSecond*1e3))}function w(O,E,S,v,C){if(!o)return;const y=d.get(E),N=(y?.open?0:y?.failures??0)+1;if(N<o.failureThreshold){d.set(E,{open:!1,openedAt:0,openMs:0,failures:N});return}const D=Math.min(Math.max(o.openMs,v),Xf);d.set(E,{open:!0,openedAt:C,openMs:D,failures:N}),f.circuitOpened+=1,m({type:"circuit_opened",capability:O,endpointId:E,status:S,openMs:D,timestamp:C})}function T(O){const E=d.get(O);E&&!E.open&&d.delete(O)}function _(O){for(const[E,S]of s)!S.pending&&S.expiresAt<=O&&s.delete(E);for(;s.size>=eh;){const E=[...s].find(([,S])=>!S.pending);if(!E)break;s.delete(E[0])}}function P(O,E){if(O===void 0)return;const S=s.get(O);S?.promise===E&&(S.pending=!1)}function F(O,E){if(O===void 0)return;s.get(O)?.promise===E&&s.delete(O)}async function U(O){if(l)return O.load();const E=t();if(o){const y=d.get(O.endpointId);if(y?.open){const N=y.openedAt+y.openMs-E;if(N>0)throw f.circuitRejected+=1,m({type:"circuit_rejected",capability:O.capability,endpointId:O.endpointId,retryAfterMs:N,timestamp:E}),oh("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:O.endpointId,retryAfterMs:N});d.delete(O.endpointId)}}const S=h(O.endpointId,E);S.exceeded&&i?c.has(O.endpointId)||(c.add(O.endpointId),m({type:"loop_detected",capability:O.capability,endpointId:O.endpointId,count:S.count,windowMs:i.windowMs,timestamp:E})):c.delete(O.endpointId);const v=r>0?O.coalesceKey:void 0;if(v!==void 0){const y=s.get(v);if(y&&(y.pending||y.expiresAt>E))return f.coalesced+=1,m({type:"coalesced",capability:O.capability,endpointId:O.endpointId,timestamp:E}),y.promise;y&&s.delete(v)}if(S.exceeded&&i)throw f.loopRejected+=1,Ks("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:O.capability,endpointId:O.endpointId,count:S.count,windowMs:i.windowMs});if(!p(E)){f.budgetRejected+=1;const y=M(E);throw m({type:"budget_exhausted",capability:O.capability,endpointId:O.endpointId,retryAfterMs:y,timestamp:E}),Ks("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:O.capability,endpointId:O.endpointId,retryAfterMs:y})}v!==void 0&&_(E);const C=O.load().then(y=>(P(v,C),T(O.endpointId),y),y=>{F(v,C);const N=nh(y);throw N!==void 0&&w(O.capability,O.endpointId,N,ih(y),E),y});return v!==void 0&&s.set(v,{endpointId:O.endpointId,promise:C,expiresAt:E+r,pending:!0}),C}return{execute:U,invalidateCoalescing(O){if(O===void 0){s.clear();return}for(const[E,S]of s)O.includes(S.endpointId)&&s.delete(E)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,O])=>O.open).map(([O])=>O)}},dispose(){l||(l=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function nh(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 ih(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 Ks(e,t){return{code:Zf,message:e,data:t}}function oh(e,t){return{code:Jf,message:e,data:t}}const Cd=3e4,Rd=6e4,bo=1440*60*1e3;function sh(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??Cd)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??Rd)):0,steamGameListTtlMs:t?ah(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:Sd,burst:_d},coalesceWindowMs:r?.coalesceWindowMs??Td,loopDetection:r?.loopDetection??{maxCalls:bd,windowMs:Od},circuitBreaker:r?.circuitBreaker??{failureThreshold:Ld,openMs:vd}}}}function ah(e){return e===void 0||!Number.isFinite(e)?bo:Math.max(0,Math.floor(e))}function ch(e){return typeof e=="object"&&e!==null}function ae(e,t){const r=e.data;if(!ch(r)||typeof r.status!="string")throw new Error(t);return r}const Pd={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},dh={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 Hr(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function uh(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function lh(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=uh(r.consent_challenge)),{...t,result:n}}const fh={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=>({...Hr(e.runtimeContext),challenge:e.challenge}),parse:e=>ae(e,"小程序授权取消接口响应异常")},hh={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=>Hr(e.runtimeContext),parse:e=>ae(e,"小程序授权撤销接口响应异常")},mh={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=>Hr(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}:{}}}}},gh={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=>({...Hr(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>lh(e)},ph={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=>({...Hr(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}}}},yh=64;function kd(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??yh)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(f){for(const[l,m]of i)m.expiresAt<=f&&i.delete(l)}function d(f,l,m){if(a||t<=0||m!==s)return;const h=n();for(c(h),i.delete(f);i.size>=r;){const p=i.keys().next();if(p.done)break;i.delete(p.value)}i.set(f,{expiresAt:h+t,value:l})}function u(f,l){if(a)return l();if(t>0){const M=i.get(f);if(M&&M.expiresAt>n())return Promise.resolve(M.value);M&&i.delete(f)}const m=o.get(f);if(m)return m;const h=s,p=l().then(M=>(d(f,M,h),M)).finally(()=>{o.get(f)===p&&o.delete(f)});return o.set(f,p),p}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 Eh(e,t){return t?e?"server":"local":"legacy"}function wh(e,t){if(e==="local")throw g("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const Ih=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],Ah=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Mh=/authorization|cookie|pkey|password|secret|token/i,xd=/authorization|cookie|pkey|token|password|secret/i;function Ue(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Nh(e){for(const t of Object.keys(e))if(!Ah.has(t))throw new le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of Ih)if(Object.prototype.hasOwnProperty.call(e,t)&&Ue(e,t)!==void 0)throw new le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Ue(e,"bodyEncoding")!==void 0&&Ue(e,"bodyEncoding")!=="json"&&Ue(e,"bodyEncoding")!=="form")throw new le("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Ue(e,"failurePresentation")!==void 0&&Ue(e,"failurePresentation")!=="none")throw new le("endpoint failurePresentation 必须为 none");if(Ue(e,"auth")!==void 0&&Ue(e,"auth")!=="none"&&Ue(e,"auth")!=="optional"&&Ue(e,"auth")!=="required")throw new le("endpoint auth 必须为 none、optional 或 required")}function Er(e){if(Array.isArray(e))return e.map(Er);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Mh.test(n)||(r[n]=Er(i));return r}function Zs(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))xd.test(r)||(t[r]=n);return t}function Dh(e){if(!e)return;const t=Object.keys(e).find(r=>xd.test(r));if(t)throw new le(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Fr 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 Js=1440*60*1e3,Sh=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function _h(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,Js):void 0}if(!Sh.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,Js):void 0}function Th(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 Ud(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class Kt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Ud(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Vr extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Ud(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function bh(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:Er(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Zs(o),method:e.method,metadata:{endpointId:e.id},query:Er(n),timeout:e.timeout,url:r},data:Er(a.data),headers:Zs(a.headers)||{},status:a.status,statusText:a.statusText}}async function _i(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(Nh(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;Dh(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(m){throw m instanceof le?m:new Kt({endpointId:t.id,cause:m})}if(f.status<200||f.status>=300)throw new Fr({endpointId:t.id,status:f.status,responseData:f.data,retryAfterMs:_h(f.headers)});const l=bh(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(l,r)}catch(m){throw new Vr({endpointId:t.id,cause:m})}return l.data},d=n.gate;if(!d)return c();const u=Th(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const Oh=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),vh=new Set($t),fs="steam_account",jd=new Set($t.filter(e=>e!==fs)),Lh=1e3;function Ch(e){const t=new Set,r=kd({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??Cd))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??Eh(e.networkEnabled===!0,c),u=e.requestPolicyEnabled!==!1,f=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function l(){if(!c&&!e.authorizationContext)return{};if(!e.authorizationContext)throw g("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let I;try{I=await e.authorizationContext.get(e.operationContext)}catch(k){throw vo(k)?Ui(k.code,k.message,k):Ui("REQUEST_FAILED","读取 Runtime auth context 失败",k)}if(I.steamAccount!==c||I.userDataMode!==d)throw g("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const L=I.token.trim();if(!L)throw g("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:L}}const m=e.account.onChange(I=>{if(h(),p("heybox_app_login_change",I?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),I&&e.account.getAccountKey){const L=i;F().then(k=>{!o&&i===L&&p("heybox_app_login_change",k)}).catch(()=>{})}});function h(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function p(I,L){I==="user_info_authorization_change"&&jh(L)&&r.invalidate();for(const k of t)try{k(I,L)}catch{}}function M(){const I=e.identity.get()?.miniProgramId?.trim();if(!I)throw g("INVALID_STATE","当前能力缺少 canonical 小程序身份");return I}function w(){if(o||e.operationContext.signal.aborted)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function T(){w();let I;try{I=await e.account.getCurrentUserId(e.operationContext)}catch(L){throw ra(L,e.operationContext.signal,"读取小黑盒账号失败")}return typeof I=="string"&&I.trim()?I.trim():void 0}async function _(I,L){const k=await T();if(i!==L||k!==I)throw g("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function P(I,L,k=M()){if(!e.account.getAccountKey)throw g("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let x;try{x=await e.account.getAccountKey(k,I,e.operationContext)}catch{throw w(),g("REQUEST_FAILED","读取本地账号标识失败")}if(await _(I,L),M()!==k)throw g("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof x!="string"||!x.trim())throw g("INVALID_RESPONSE","Host 返回了无效的账号标识");return x}async function F(){const I=M(),L=i,k=await T();if(w(),i!==L)throw g("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return k?{isHeyboxAppLoggedIn:!0,accountKey:await P(k,L,I)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function U(I){w();try{await e.account.ensureAuthenticated({trustedUserGesture:I,reason:"runtime_auth",signal:e.operationContext.signal})}catch(k){throw ra(k,e.operationContext.signal,"小黑盒登录失败")}const L=await T();if(!L)throw g("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return L}async function O(I,L,k=e.operationContext.signal){try{if(k.aborted)throw Oo();return await Uh(_i(e.network,I,L,{...e.operationContext,credentials:"heybox-session",signal:k,...f?{gate:f}:{}}),k)}catch(x){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):x instanceof le?g("REQUEST_UNSUPPORTED",x.message):x instanceof Vr?g("INVALID_RESPONSE","授权接口响应不合法"):x instanceof Kt?g("REQUEST_FAILED","授权请求失败"):x instanceof Fr?u&&(x.status===403||x.status===429)?g("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:x.status,...x.retryAfterMs===void 0?{}:{retryAfterMs:x.retryAfterMs}}):g("REQUEST_FAILED",x.message):vo(x)?x:g("REQUEST_FAILED","授权请求失败")}}async function E(I,L){await O(fh,{runtimeContext:{miniProgramId:I,...await l()},challenge:L}).catch(()=>{})}function S(I){const L=async()=>{const x=ea(e.operationContext.signal);a=x;try{return await I(x.signal)}finally{a===x&&(a=void 0),x.abort()}},k=s.then(L,L);return s=k.then(()=>{},()=>{}),k}async function v(I,L,k,x,z){if(!k)throw await E(I,L.challenge),g("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await E(I,L.challenge),g("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return S(async H=>{await _(x,z);const V=await C(I,L.displayedScopes,H);await _(x,z);let G;try{G=await e.authPresentation.confirmAuthorization({miniProgramId:I,scopes:L.displayedScopes,...V,signal:H})}catch(K){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await _(x,z),await E(I,L.challenge),Ui("REQUEST_FAILED","授权确认界面执行失败",K))}if(await _(x,z),G.status!=="granted")throw await E(I,L.challenge),g("AUTHORIZATION_CANCELLED","用户取消授权");const J=kh(G.grantedScopes,L.displayedScopes,c);if(!J.includes("identity"))throw await E(I,L.challenge),g("AUTHORIZATION_CANCELLED","用户拒绝授权");return J})}async function C(I,L,k){const x=ea(k),z=setTimeout(()=>x.abort(),Lh);try{const H=xh(e.miniProgramPresentation),[V,G]=await Promise.all([H?Promise.resolve(H):y(I,x.signal),L.includes("profile")?N(x.signal):Promise.resolve(void 0)]);return{...V?{miniProgram:V}:{},...G?{userProfile:G}:{}}}finally{clearTimeout(z),x.abort()}}async function y(I,L){try{const k=e.identity.get()?.version?.trim(),x=await O(dh,{mini_program_id:I,...k?{miniprogram_version:k}:{}},L),z=Rt(x,"小程序公开资料"),H=Ht(z.name),V=Ht(z.icon_url);return H||V?{...H?{name:H}:{},...V?{avatarUrl:V}:{}}:void 0}catch{return}}async function N(I){try{const L=await O(Pd,void 0,I),k=Rt(L,"账号基础信息"),x=Ht(k.display_username),z=Ht(k.display_avatar);return x||z?{...x?{nickname:x}:{},...z?{avatar:z}:{}}:void 0}catch{return}}async function D(I,L){if(wh(d,"auth.login"),!c&&I.includes(fs))throw g("INVALID_PARAMS","auth.login 参数不合法");const k=M(),x=await U(L),z=i,H=await O(gh,{runtimeContext:{miniProgramId:k,...await l()},scopes:I});await _(x,z);const V=Rt(H,"小程序登录"),G=ta(V,"loginCode"),J=ta(V,"consentChallenge");if(G===J)throw g("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let K;if(G)K=Xs(V.loginCode,c);else{const Y=Rh(V.consentChallenge,c),ne=await v(k,Y,L,x,z);await _(x,z);const ve=await O(ph,{runtimeContext:{miniProgramId:k,...await l()},challenge:Y.challenge,selectedScopes:ne});if(await _(x,z),K=Xs(Rt(ve,"小程序登录确认"),c),K.scopes.some(Qe=>!ne.includes(Qe)))throw g("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const Y of K.scopes)n.add(Y);r.invalidate();const Z=e.account.getAccountKey?await P(x,z,k):void 0;return p("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...Z===void 0?{}:{accountKey:Z}}),p("user_info_authorization_change",ji(n,c)),{...K,...Z===void 0?{}:{accountKey:Z}}}async function R(I,L){const k=i,x=await O(mh,{runtimeContext:{miniProgramId:L,...await l()}});await _(I,k);const z=Ph(Rt(x,"用户本地身份"),c);for(const H of c?$t:jd)n.add(H);return p("user_info_authorization_change",ji(n,c)),z}function b(I){w();const L=M(),k=`${I}\0${L}\0${i}\0${c}`;return r.read(k,()=>R(I,L))}async function A(I){if(!I)throw g("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const L=M(),k=i,x=await T();if(!x)throw g("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const z=await O(hh,{runtimeContext:{miniProgramId:L,...await l()}});await _(x,k),Rt(z,"用户授权撤销"),h(),p("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:F,login:D,async confirmGameSaves(I){if(!I)throw g("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw g("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const L=M(),k=await U(I),x=i;await S(async z=>{await _(k,x);const H=await C(L,["identity"],z),V=await e.authPresentation.confirmAuthorization({miniProgramId:L,scopes:["identity","game_saves"],...H,signal:z});if(await _(k,x),V.status!=="granted"||!V.grantedScopes.includes("game_saves")||!V.grantedScopes.includes("identity"))throw g("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:b,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>ji(n,c),revoke:A,onEvent(I){return t.add(I),()=>t.delete(I)},dispose(){o||(o=!0,h(),r.dispose(),m(),t.clear())}}}function Ui(e,t,r){const n=g(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function Rt(e,t){if(!Q(e))throw g("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":Oh.has(r)?r:"REQUEST_FAILED";throw g(n,r)}if(!Q(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Xs(e,t){if(!Q(e))throw g("INVALID_RESPONSE","login code 必须是对象");const r=ti(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!r.includes("identity"))throw g("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function Rh(e,t){if(!Q(e))throw g("INVALID_RESPONSE","授权 challenge 必须是对象");const r=ti(e.requestedScopes,"challenge requestedScopes",t),n=ti(e.displayedScopes,"challenge displayedScopes",t);if(typeof e.challenge!="string"||!e.challenge.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!Number.isInteger(e.consentUiVersion)||Number(e.consentUiVersion)<0||!r.length||!r.includes("identity")||!n.length||!n.includes("identity")||r.some(i=>!n.includes(i)))throw g("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function Ph(e,t){if(!Q(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw g("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw g("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const n=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return n?{appUserId:r,steamId:n}:{appUserId:r}}function kh(e,t,r){const n=ti(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw g("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Ht(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function xh(e){const t=Ht(e?.name),r=Ht(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function ea(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 Uh(e,t){return t.aborted?Promise.reject(Oo()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Oo()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Oo(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function ti(e,t,r){const n=r?vh:jd;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw g("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function ji(e,t){const r=t?$t:$t.filter(n=>n!==fs);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function ta(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function jh(e){return Q(e)?Object.values(e).some(t=>t==="denied"):!1}function vo(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}function ra(e,t,r){return t.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):vo(e)?e:g("REQUEST_FAILED",r)}const zh=new Set($t);function Hh(e){return{[Mn]:async t=>{if(t!==void 0)throw g("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[Nn]:async(t,r)=>e.authorization.login(Fh(t),r.trustedUserGesture)}}function Fh(e){if(e===void 0)return["identity"];if(!Q(e)||Object.keys(e).some(t=>t!=="scopes"))throw na();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!zh.has(t))||new Set(e.scopes).size!==e.scopes.length)throw na();return[...e.scopes]}function na(){return g("INVALID_PARAMS","auth.login 参数不合法")}const Vh={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,"排行榜记录删除接口响应异常")}},Bh={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,"当前排行榜记录接口响应异常")}},Gh={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,"排行榜信息接口响应异常")}},Qh={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,"排行榜列表接口响应异常")}},Yh={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,"排行榜提交接口响应异常")}},qh={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 hs(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await W(()=>_i(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(ii(i)||mr(i,"REQUEST_UNSUPPORTED")||mr(i,"RATE_LIMITED")||mr(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof le)throw B("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof Kt&&mr(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Fr){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=Wh(i.responseData);if(te(o)&&typeof o.status=="string"&&o.status!=="ok"){const s=te(o.result)?qe(o.result.error_code):void 0;if(o.status==="login"||o.status==="relogin"||ri(o.result)||ri(o)||s&&/^[A-Z][A-Z0-9_]+$/.test(s))throw zd(o,e.subject)}throw B("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof Kt?ni(e.subject):i instanceof Vr?ie(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):ie(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function Be(e,t,r){if(!te(e)||typeof e.status!="string")throw ie(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw zd(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw ie(`${t} 响应缺少 result`);return e.result}function ms(e,t){try{return e.onChange(t)}catch(r){if(mr(r,Id))return()=>{};throw r}}function zd(e,t){if(e.status==="login"||e.status==="relogin")throw B("UNAUTHORIZED",qe(e.msg)||"当前用户未登录");if(te(e.result)){const i=qe(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw B(i,qe(e.result.message)||qe(e.msg)||`${t}请求失败`)}const r=ri(e.result)??ri(e),n=qe(r?.user_message)||qe(e.msg)||qe(r?.developer_message)||`${t}请求失败`;throw r?B($h(r),n,{status:e.status,sbe:r}):B("HEYBOX_API_ERROR",n,{status:e.status})}function Wh(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function ri(e){return te(e)&&te(e.sbe)?e.sbe:void 0}function $h(e){const t=qe(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 qh[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 qe(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function mr(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 ie(e){return B("INVALID_RESPONSE",e)}function ni(e){return B("REQUEST_FAILED",`${e}请求失败`)}function ii(e){return e instanceof Error&&e.name==="AbortError"}const Kh="default",dt="排行榜",Zh=/^[A-Za-z0-9_-]{1,64}$/,Jh=300*1e3,Xh=250,em=3;class tm{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=ms(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(Yh,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=Be(i,We,dt);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),zi(o,We)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=cr("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(Qh,{miniProgramId:r,...t}),s=Be(o,Ce,dt);if(!te(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw ie(`${Ce} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw ie(`${Ce} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>zi(a,Ce)),...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=cr("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(Bh,{miniProgramId:n,...t}),c=Be(a,rt,dt);if(!te(c))throw ie(`${rt} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:zi(c.entry,rt)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Vh,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=Be(i,It,dt);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!te(o)||typeof o.deleted!="boolean")throw ie(`${It} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",cr("info"),async()=>{const i=await this.request(Gh,{miniProgramId:r,...t}),o=Be(i,Ve,dt);if(!te(o)||typeof o.key!="string"||!Zh.test(o.key))throw ie(`${Ve} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw ie(`${Ve} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw ie(`${Ve} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw ie(`${Ve} 返回的 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=cr(t,n),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,f=o?.generation,l=i().then(m=>(this.assertAccountGeneration(u),o&&s&&o.generation===f&&(r==="list"?s.size>=Xh&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Jh,value:m})),m)).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>=em)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)ia(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){ia(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 W(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw ii(n)?n:ni(dt)}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 cr(t,r??Kh)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw B("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return hs({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:dt,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 rm(e){return new tm(e)}function zi(e,t){if(!te(e))throw ie(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw ie(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw ie(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw ie(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw ie(`${t} 返回的 score 必须是有限数字`);if(!te(e.extra))throw ie(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw ie(`${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 ia(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function cr(...e){return JSON.stringify(e)}const nm={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,"云端存储删除接口响应异常")}},oa={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,"云端存储读取接口响应异常")}},sa={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 列表接口响应异常")}},im={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,"云端存储写入接口响应异常")}},ut="云端存储",om=3e4,sm=128,am=500;class cm{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=ms(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=Be(await this.request(sa,{}),At,ut);if(this.assertAccountGeneration(t),!te(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw ie("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"?am: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=Be(await this.request(nm,{key:t}),qt,ut);if(this.assertAccountGeneration(r.generation),!te(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw ie("删除结果不合法");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 ie("云存储版本超出安全整数范围");const o=Be(await this.request(im,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),Yt,ut);if(this.assertAccountGeneration(r.generation),!te(o)||o.success!==!0)throw ie("云存储写入结果不合法");const s=aa({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw ie("写入版本凭证不匹配");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(oa,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=aa(Be(c,Qt,ut));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>=sm&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+om,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([oa.id,sa.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 W(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw ii(o)?o:ni(ut)}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 W(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw ii(s)?s:ni(ut)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw B("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return hs({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:ut,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(X(this.options.operationContext.signal),this.disposed)throw B("INVALID_STATE","Cloud capability 已释放")}}function dm(e){return new cm(e)}function aa(e){if(!te(e))throw ie("云存储读取结果必须是对象");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 ie("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw ie("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const um=/^[A-Za-z0-9_-]{1,64}$/,ca=20,lm=100,da=2048,fm=/^[A-Za-z0-9_-]{1,128}$/,ua=16*1024;function hm(e){const t=rm(e),r=dm(e);return{handlers:{[We]:async i=>t.submit(mm(i)),[Ce]:async i=>t.getList(gm(i)),[rt]:async i=>t.getCurrentUserEntry(Hi(i,rt)),[It]:async i=>t.deleteCurrentUserEntry(Hi(i,It)),[Ve]:async i=>t.getInfo(Hi(i,Ve)),[Qt]:async i=>r.getItem(la(i,Qt)),[Yt]:async i=>{const{key:o,value:s}=pm(i);return r.setItem(o,s)},[qt]:async i=>r.removeItem(la(i,qt)),[At]:async i=>(Em(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function mm(e){const t=rr(e,We,!1);if(nr(t,["key","score","extra"],We),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{...gs(t.key,We),score:t.score,...t.extra===void 0?{}:{extra:wm(t.extra)}}}function gm(e){if(e===void 0)return{limit:ca};const t=rr(e,Ce,!0);nr(t,["key","limit","cursor"],Ce);const r=t.limit===void 0?ca:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>lm)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{...gs(t.key,Ce),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Hi(e,t){if(e===void 0)return{};const r=rr(e,t,!0);return nr(r,["key"],t),gs(r.key,t)}function la(e,t){const r=rr(e,t,!1);return nr(r,["key"],t),Hd(r.key,t)}function pm(e){const t=Yt,r=rr(e,t,!1);nr(r,["key","value"],t);const n=Hd(r.key,t);if(typeof r.value!="string")throw Ee("INVALID_PARAMS",`${t} value 必须是字符串`);if(ym(r.value))throw Ee("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>ua)throw Ee("INVALID_PARAMS",`${t} value 不能超过 ${ua} 字节`);return{key:n,value:r.value}}function ym(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 Em(e){const t=rr(e,At,!0);nr(t,[],At)}function Hd(e,t){if(typeof e!="string"||!fm.test(e))throw Ee("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function rr(e,t,r){if(e===void 0&&r)return{};if(!Fd(e))throw Ee("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function nr(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Ee("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function gs(e,t){if(e===void 0)return{};if(typeof e!="string"||!um.test(e))throw Ee("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function wm(e){if(!Fd(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>da)throw Ee("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${da} 字节`);return e}function Fd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ee(e,t){return{code:e,message:t}}const Im={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 Lo(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw g("FILE_IO_FAILED","当前环境缺少安全随机数能力");try{const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}catch{throw g("FILE_IO_FAILED","无法生成安全文件标识")}}function Vd(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):Co,remove:o?s=>e.remove(s):Gd,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Co,stat:s=>e.stat(s)})}function Bd(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=>Vd(e.file(a),n,{allowRemove:o}),directory:a=>Bd(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Co,remove:s?(a,c)=>e.remove(a,c):Gd,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Co(){return Promise.reject(g("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Gd(){return Promise.reject(g("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Am=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"]),Mm={METHOD_FORBIDDEN:"当前 Host 未开放该文件能力",FILE_PICKER_CANCELLED:"已取消文件选择",FILE_ACCESS_REVOKED:"文件授权已失效",FILE_ACCESS_DENIED:"当前文件授权不允许此操作",FILE_NOT_FOUND:"文件不存在",DIRECTORY_NOT_FOUND:"目录不存在",FILE_ALREADY_EXISTS:"文件已存在",DIRECTORY_ALREADY_EXISTS:"目录已存在",FILE_TYPE_MISMATCH:"文件类型不匹配",FILE_TOO_LARGE:"文件超过大小限制",FILE_QUOTA_EXCEEDED:"文件配额已用尽",FILE_ENCODING_INVALID:"文件编码不合法",DIRECTORY_LIST_LIMIT_EXCEEDED:"目录项数量超过限制",DIRECTORY_NOT_EMPTY:"目录不为空",FILE_IO_FAILED:"文件操作失败"};function Rr(e){const t=ps(e),r=t&&Am.has(t)?g(t,Mm[t]??"文件操作失败"):g("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Ye(e){try{return e()}catch(t){throw Rr(t)}}function ps(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 fa=1024;class ys{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new ys(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 Zr(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Ye(()=>{if(!Array.isArray(t))throw g("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw g("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>fa)throw g("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw g("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>Zr(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 ma(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Wt(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!Wt(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Dm(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Pr(r.relativePath);Fi(n.origin,i);const o=this.prepareFile(Ye(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Sm(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==="."?".":Pr(r.relativePath);Fi(n.origin,i);const o=this.prepareDirectory(i==="."?n.hostHandle:Ye(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return pa(t),Zr(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Ye(()=>{if(!Array.isArray(r))throw g("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw g("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw g("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&Q(a)&&typeof a.name=="string"&&Qd(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Ye(()=>{if(Q(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Zr(n.handle,ha(t.ref,n.handle.name))}if(Q(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return ma(n.handle,Nm(t.ref,n.handle.name))}throw g("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Br(r);Fi(t.origin,n);const i=this.prepareFile(Ye(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:ha(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw g("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Ye(()=>{pa(t);const i=n??t.mode;return ga(t.mode,i),{handle:Vd(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Ye(()=>{Tm(t,i);const o=n??t.mode;return ga(t.mode,o),{handle:Bd(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>fa)throw g("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Lo();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw g("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!_m(t))throw g("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw g("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw g("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw _e("files.sandbox");return this.prepareDirectory(Ye(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw g("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw _e("files")}}function Pr(e){if(!ds(e))throw g("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Fi(e,t){if(e==="sandbox"&&Qd(t))throw g("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function Qd(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function Br(e,t="文件名"){const r=Pr(e);if(r.includes("/"))throw g("INVALID_PARAMS",`${t} 只能是 basename`);return r}function ha(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Pr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Nm(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Pr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Zr(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function ma(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function ga(e,t){if(t==="readwrite"&&e!=="readwrite")throw g("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Dm(e){return Wt(e)||Yd(),e}function Sm(e){return ud(e)||Yd(),e}function Yd(){throw g("INVALID_PARAMS","文件引用不合法")}function _m(e){return/^[0-9a-f]{32}$/.test(e)}function pa(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 g("FILE_IO_FAILED","Host 返回了无效 File handle");Br(e.name,"Host File name")}function Tm(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 g("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw g("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&Br(e.name,"Host Directory name")}const bm=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Om=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),vm=new Set(["range","if-range","a-im"]),Lm=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"]),Cm=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Jr={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Rm{constructor(t){this.signal=t}phase="initial";transition(t){if(Jr[t]<=Jr[this.phase])throw g("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Jr[this.phase]<Jr.committed&&this.signal.aborted)throw $d()}normalizeHostError(t,r){return this.throwIfCancelled(),ws(t,r,this.signal)}}async function qd(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw _e("network.download");const o=Ne(r.operationContext,t.signal),s=new Rm(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Um(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=zm(c);Hm(c,u);const f=Fm(c.status,u);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw g("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const l=jm(e,a,u,i);let m=0;const h=km(f.expectedBytes,e.maxBytes);Bi(t,Vi(0,f));const p={...o,onProgress(T){!Number.isSafeInteger(T)||T<m||h!==void 0&&T>h||(m=T,Bi(t,Vi(m,f)))}};s.transition("transfer"),d=!0;let M;try{M=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}},p)}catch(T){throw s.normalizeHostError(T,"transfer")}s.transition("committed"),m=Pm(M,f,m,e.maxBytes),Bi(t,Vi(m,f));const w=i.describeFile(l.handle,l.ref);return s.transition("completed"),w}finally{d||xm(n.network,c.body)}}function Pm(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 km(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function xm(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Um(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Ro(i.handle.mode),await Wm(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Ro(n.handle.mode),await $m(n.handle,r),{kind:"directory",...n}}function jm(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Bm(e,r),o=n.deriveFile(t,i);return Ro(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function zm(e){if(!e||typeof e!="object"||!Number.isInteger(e.status)||e.status<100||e.status>599||e.statusText!==void 0&&typeof e.statusText!="string"||!e.body||typeof e.body!="object")throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!Q(e.headers))throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!bm.has(r)||!Array.isArray(n)||n.length===0)throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Hm(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw g("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:qm(t,Om)});if((t["content-range"]?.length??0)>0)throw g("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Fm(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw g("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw g("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw g("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=Vm(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 Vm(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Vi(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Bi(e,t){try{e.postProgress(t)}catch{}}function Bm(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=Gm(i);if(o&&dn(o))return o}for(const i of r){const o=Qm(i);if(o&&dn(o))return o}if(e.suggestedName!==void 0)return Es(e.suggestedName);const n=Ym(e.url);return n&&dn(n)?n:"download.bin"}function Gm(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 Qm(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 Ym(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Es(e){try{Br(e,"suggestedName")}catch{throw g("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!dn(e))throw g("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function dn(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Cm.test(e))}function qm(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Wm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Wd()}catch(r){throw ws(r,"file",t.signal)}}async function $m(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Wd()}catch(r){throw ws(r,"file",t.signal)}}function Ro(e){if(e!=="readwrite")throw g("FILE_ACCESS_DENIED","下载目标只允许读取")}const Km={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 ws(e,t,r){if(r.aborted)return $d();const n=Zm(e);if(n&&Lm.has(n)){const o=g(n,Km[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?g("DOWNLOAD_TIMEOUT","下载网络请求超时"):g("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?g("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):g("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function Zm(e){return Q(e)&&typeof e.code=="string"?e.code:void 0}function Wd(){return g("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function $d(){return g("DOWNLOAD_CANCELLED","下载已取消")}function Jm(e){if(!e)return;const t=Object.keys(e).find(r=>vm.has(r.trim().toLowerCase()));if(t)throw g("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}function Po(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=>Po(r,t+1)):te(e)&&Object.values(e).every(r=>Po(r,t+1))}function Xm(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)||!Po(e.data)?n:{status:"ready",data:e.data}}function eg(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 m=new Promise(p=>{l=p}),h=f.then(()=>m);r.set(u,h);try{return await W(()=>f,c.signal),X(c.signal),await d()}finally{l(),r.get(u)===h&&h.then(()=>{r.get(u)===h&&r.delete(u)})}}async function o(a,c){const d=n(a);if(t.has(d))return t.get(d);if(e)try{const u=await W(()=>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 W(()=>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 Gi=8*1024*1024,ya=32*1024*1024,tg=2e3,rg=5*6e4;function ng(e){const t=eg(e.storage);let r=0,n=!1,i,o=0;const s=new Set,a=new Map,c={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},d=E=>E.remove(c),u=new Set;let f=new AbortController,l;const m=()=>{f.abort(),f=new AbortController,l=void 0},h=(E=!0)=>{E&&t.clear(c),r++,m();for(const S of u)S.abort();for(const S of s)d(S).catch(()=>{});s.clear(),a.clear(),o=0},p=ms(e.account,E=>{i&&E!==i&&(h(),i=void 0)}),M=e.authorization.onEvent(()=>h());function w(E,S,v,C){if(T(v),C.signal.aborted||!E.account_id||!e.presentation?.showSteamLoginRequired)return;const y=`${E.account_id}:${E.game_id}:${E.task_id??"sync"}`;if(l!==y){l=y;try{e.presentation.showSteamLoginRequired({userId:S,accountId:E.account_id},Ne(e.operationContext,f.signal))}catch{}}}function T(E){if(n||e.operationContext.signal.aborted)throw B("RUNTIME_DESTROYED","小程序已关闭");if(E!==r)throw B("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function _(E,S,v){if(T(S),await e.account.getCurrentUserId(v)!==E)throw h(),B("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");T(S)}async function P(E,S,v,C){if(await _(S,v,C),!e.authorizationContext)throw B("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const y=await e.authorizationContext.get(C);if(!y.token||y.expiresAt<=Date.now())throw B("UNAUTHORIZED","小程序运行上下文已过期");const N=await hs({network:e.network,operationContext:C,subject:"游戏存档",assertUsable:()=>T(v),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},Im,{...E,runtime_auth_context_token:y.token});if(await _(S,v,C),N.status==="failed"&&te(N.result)&&N.result.error_code==="RECENT_SAVE_AVAILABLE")throw B("RECENT_SAVE_AVAILABLE",typeof N.msg=="string"&&N.msg?N.msg:"已有近期存档,请直接查询使用");const D=Be(N,E.action,"游戏存档");if(!te(D))throw B("INVALID_RESPONSE","存档响应不合法");return D}async function F(E,S,v){const C=ig(E,S),y=r;if(T(y),E==="file"&&(!e.transfer||!e.files))throw B("METHOD_FORBIDDEN","宿主不支持存档文件读取");const N=new AbortController;u.add(N);let D=!1;const R=E==="sync"?setTimeout(()=>{D=!0,N.abort()},rg):void 0,b=Ne(Ne(e.operationContext,v.signal),N.signal);try{const A=await e.account.getCurrentUserId(b);if(!A)throw B("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==A)throw h(),B("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=A,E==="sync"||E==="parsed"){if(E==="sync"&&m(),!C.account_id){const J=await P({action:"check",game_id:C.game_id},A,y,b);C.account_id=kr(J.account_id)}if(E==="sync")return await U(C,A,y,b)}const I=await P({action:E,...C},A,y,b);if(E==="list")return og(I);if(E==="parsed")return Xm(I.parsed_data,C.game_id);const L=Kd(I.file);if(L.fileId!==C.file_id)throw B("INVALID_RESPONSE","文件标识不匹配");if(L.sizeBytes>Gi)throw B("FILE_TOO_LARGE","首期存档文件上限为 8 MiB");if(o+L.sizeBytes>ya)throw B("FILE_QUOTA_EXCEEDED","当前会话存档文件已达 32 MiB");const k={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:ft(I.download_url)},timeout:6e4};if(!wd(k)||new URL(ft(I.download_url)).pathname!=="/cloud_archive/"+C.file_id+".zip"||oi(I.expires_at)<=Date.now())throw B("INVALID_RESPONSE","存档下载地址无效");const x=".hb-game-saves/"+Lo()+".zip",z=e.files.sandbox.file(x);if(!z.remove)throw B("METHOD_FORBIDDEN","宿主不支持存档临时文件清理");await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},b);const H=e.fileRegistry.createTransferScope();let V=!1,G=!1;try{await z.create({recursive:!0,exclusive:!0},b),G=!0;const J=H.registerFile(z,"game-save","readwrite");await qd({request:k,url:new URL(ft(I.download_url)),to:J.ref,targetKind:"file",maxBytes:Gi},{...v,signal:b.signal,postProgress:()=>{}},{transfer:e.transfer,fileRegistry:H,operationContext:b}),await _(A,y,b);const K=await z.stat(b);if(K.size===void 0||!Number.isSafeInteger(K.size)||K.size<0||K.size>Gi)throw B("FILE_TOO_LARGE","存档文件超过 8 MiB");if(await _(A,y,b),o+K.size>ya)throw B("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达 32 MiB");if(b.signal.aborted)throw B("DOWNLOAD_CANCELLED","存档下载已取消");const Z=K.size,Y=async ye=>{try{T(y),await P({action:"check",game_id:C.game_id,account_id:C.account_id},A,y,ye)}catch(Le){throw te(Le)&&["GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","UNAUTHORIZED"].includes(String(Le.code))?(h(),B("FILE_ACCESS_REVOKED","游戏存档授权已失效")):Le}},ne=async()=>{throw B("FILE_ACCESS_DENIED","存档文件只读")},ve={kind:"file",mode:"read",name:L.name,create:ne,write:ne,async read(ye){await Y(ye);const Le=await z.read(ye);try{if(await _(A,y,ye),!(Le instanceof Uint8Array)||Le.byteLength!==Z)throw B("INVALID_RESPONSE","存档文件长度不匹配");return Le}catch(ul){throw Le instanceof Uint8Array&&Le.fill(0),ul}},async stat(ye){return await Y(ye),{kind:"file",size:Z,modifiedAt:L.modifiedAt}}},Qe=e.fileRegistry.registerFile(ve,"game-save","read");return s.add(z),o+=Z,a.set(Lo(),{file:ve,sizeBytes:Z}),V=!0,Qe}finally{H.dispose(),G&&!V&&await d(z)}}catch(A){throw D?B("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):A}finally{R!==void 0&&clearTimeout(R),u.delete(N)}}async function U(E,S,v,C){const y=e.identity.get()?.miniProgramId;if(!y)throw B("INVALID_STATE","小程序身份尚未确认");const N={miniProgramId:y,userId:S,gameId:E.game_id,accountId:E.account_id},D=b=>P({action:"status",...E,task_id:b},S,v,C);let R;try{const b=await t.run(N,C,async()=>{await _(S,v,C);const I=await t.get(N,C);if(I){R=I;try{return{taskId:I,status:await D(I)}}catch(k){if(!te(k)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(k.code)))throw k;await t.set(N,void 0,C),R=void 0}}const L=await P({action:"sync",...E},S,v,C);return R=kr(L.task_id),await t.set(N,R,C),await _(S,v,C),{taskId:R,status:void 0}});R=b.taskId;let A=b.status;for(;;){if(T(v),C.signal.aborted)throw B("REQUEST_CANCELLED","已停止等待存档同步");if(A??=await D(R),A.state==="succeeded"||A.state==="failed"){if(await t.remove(N,R,C),await _(S,v,C),A.state==="succeeded")return{state:"succeeded"};throw B(A.error_code?ft(A.error_code):"SYNC_FAILED",A.message?ft(A.message):"存档同步失败")}if(A.state!=="syncing"&&A.state!=="uploading")throw B("INVALID_RESPONSE","同步状态不合法");A=void 0,await sg(tg,C.signal)}}catch(b){if(te(b)){const A=String(b.code);A==="STEAM_LOGIN_REQUIRED"&&w({...E,task_id:R},S,v,C),R&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(A)&&await t.remove(N,R,c)}throw b}}return{handlers:{"gameSaves.list":(E,S)=>F("list",E,S),"gameSaves.sync":(E,S)=>F("sync",E,S),"gameSaves.readParsedData":(E,S)=>F("parsed",E,S),"gameSaves.getFile":(E,S)=>F("file",E,S)},diagnostics:{async getSnapshot(){const E=r;return i&&await _(i,E,e.operationContext),T(E),Array.from(a,([S,v])=>({id:S,name:v.file.name,sizeBytes:v.sizeBytes}))},async readFile(E,S){const v=r;T(v);const C=a.get(E);if(!C)throw B("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const y=Ne(e.operationContext,S);y.signal.throwIfAborted();const N=await C.file.read(y);try{return y.signal.throwIfAborted(),T(v),{name:C.file.name,bytes:N}}catch(D){throw N.fill(0),D}}},allowsRead(E,S){return["file.readBytes","file.readText","file.stat","file.exists"].includes(E)&&te(S)&&e.fileRegistry.isGameSaveRef(S.target)},dispose(){n||(n=!0,h(!1),p(),M())}}}function ig(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=gr(t.gameId);if(Number(n)>2147483647)throw B("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:gr(t.accountId)}:{},...e==="file"?{save_id:gr(t.saveId),file_id:gr(t.fileId)}:{}}}function gr(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw B("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function kr(e){try{return gr(e)}catch{throw B("INVALID_RESPONSE","服务端存档标识无效")}}function ft(e){if(typeof e!="string")throw B("INVALID_RESPONSE","服务端存档字段无效");return e}function oi(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw B("INVALID_RESPONSE","服务端存档数值无效");return e}function Kd(e){if(!te(e))throw B("INVALID_RESPONSE","存档文件信息无效");return{fileId:kr(e.file_id),name:ft(e.name),originalPath:ft(e.original_path),sizeBytes:oi(e.size_bytes),modifiedAt:oi(e.modified_at)}}function og(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw B("INVALID_RESPONSE","存档列表无效");return{accountId:kr(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:kr(t.save_id),createdAt:oi(t.created_at),files:t.files.map(Kd)}})}}function sg(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 ag=new Set(["stdio","attachments","notifications"]),Zd=new Set(["windows-x64","macos-arm64"]),cg=new Set(["unsigned","valid","invalid","unknown"]),dg=/^[a-f0-9]{64}$/,ug=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),lg=new Set(yd),fg=new Set([...yd,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Jd=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 hg(e){const t=async(n,i,o,s)=>{const a=mg(n);try{Fe(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Fe(i.signal),c}catch(c){throw xo(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw g("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>gg(d,i)).catch(d=>{throw xo(d)});Fe(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Fe(o.signal),c.status!=="granted")throw g("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[mi]:(n,i)=>t(n,i,async(o,s)=>ko(await e.companion.getInfo(o,s),o)),[gi]:(n,i)=>t(n,i,async(o,s)=>Ea(await e.companion.getPreparationStatus(o,s))),[pi]:(n,i)=>t(n,i,async(o,s)=>{const a=Ea(await e.companion.getPreparationStatus(o,s));return Fe(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Fe(i.signal),ko(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(eu(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[yi]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Ei]:(n,i)=>t(n,i,async(o,s)=>wa(await e.companion.getActiveSession(o,s),o)),[wi]:(n,i)=>t(n,i,async(o,s)=>{const a=wa(await e.companion.getActiveSession(o,s),o);return Fe(i.signal),a||(await r("launch",o,i),Fe(i.signal),tu(await e.companion.launch(o,s),o))}),[Ii]:(n,i)=>Pt(n,i,e,"write"),[Ai]:(n,i)=>Pt(n,i,e,"closeStdin"),[Mi]:(n,i)=>Pt(n,i,e,"terminate"),[Ni]:(n,i)=>Pt(n,i,e,"ackOutput"),[Di]:async(n,i)=>{const o=await Pt(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Si]:(n,i)=>Pt(n,i,e,"showNotification")}}function mg(e){if(!Q(e)||typeof e.alias!="string"||!tf.test(e.alias))throw g("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Fe(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function Pt(e,t,r,n){if(!Q(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw g("INVALID_PARAMS","Companion Session controller 不合法");try{Fe(t.signal);const i=await r.companion[n](pg(e,n),{...r.operationContext,signal:t.signal});return Fe(t.signal),i}catch(i){throw xo(i)}}function Pe(){throw g("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Xd(e){return!Array.isArray(e)||e.some(t=>!ag.has(t))?Pe():Object.freeze([...new Set(e)])}function ko(e,t){return!Q(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Zd.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!cg.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?Pe():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Xd(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function gg(e,t){const r=ko(e,t);return!Q(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!dg.test(e.sha256)?Pe():Object.freeze({...r,sha256:e.sha256})}function eu(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}):Pe():Pe()}function Ea(e){return Q(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:eu(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"&&lg.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:Jd[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):Pe():Pe()}function tu(e,t){return!Q(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Zd.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?Pe():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Xd(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function wa(e,t){return e===void 0?void 0:tu(e,t)}function pg(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!hd(r.data))throw g("INVALID_PARAMS","Companion write data 不合法");return{...n,data:new Uint8Array(r.data)}}if(t==="ackOutput"){if(r.stream!=="stdout"&&r.stream!=="stderr"||!Number.isSafeInteger(r.sequence)||Number(r.sequence)<0)throw g("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw g("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw g("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function yg(e){return!Q(e)||!ug.has(String(e.reason))?Pe():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):Pe():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?Pe():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Eg(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||!hd(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:yg(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 xo(e,t){return Q(e)&&typeof e.code=="string"&&fg.has(e.code)?g(e.code,Jd[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"?g(t,"Companion 准备已取消"):g("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Ia=5e3,Aa=1e4;function ge(e){throw{code:"INVALID_PARAMS",message:e}}function Is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ru(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&ge(`${r} 不支持字段: ${n.join(", ")}`)}function wg(e){if(e===void 0)return{intensity:"light",delay:0};if(!Is(e))return ge("device.vibrate 参数必须是对象");ru(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return ge("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Ia?ge(`device.vibrate delay 必须是 0-${Ia} 的整数毫秒`):{intensity:r,delay:n}}function Ig(e){return Is(e)?(ru(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?ge("device.setClipboard text 必须是非空字符串"):e.text.length>Aa?ge(`device.setClipboard text 不能超过 ${Aa} 字符`):{text:e.text}):ge("device.setClipboard 参数必须是对象")}function Ag(e){return typeof e=="string"?e.trim()?e:ge("device.executeProtocol 协议字符串不能为空"):Is(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?ge("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(Uo(e,new Set),e):ge("device.executeProtocol 参数必须是协议字符串或协议对象")}function Uo(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||ge("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":ge("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":ge(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&ge("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)Uo(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&ge("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))Uo(i,t);t.delete(r)}function Mg(e){return{[$n]:async t=>{X(e.operationContext.signal),await W(()=>e.presentation.vibrate(wg(t),e.operationContext),e.operationContext.signal)},[Kn]:async t=>{X(e.operationContext.signal),await W(()=>e.presentation.setClipboard(Ig(t),e.operationContext),e.operationContext.signal)},[Zn]:async(t,r)=>{const n=Ne(e.operationContext,r.signal);X(n.signal);const i=Ag(t);await W(()=>e.protocol.invoke(i,n),n.signal)}}}const Ma=1e3,Ng=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function Dg(e){const t=r=>Ne(e.operationContext,r.signal);return{files:{[Un]:async(r,n)=>{Qi(n);const i=Yi(e.picker),o=Sg(r),s=await Ie(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[jn]:async(r,n)=>{Qi(n);const i=Yi(e.picker),o=_g(r),s=await Ie(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[zn]:async(r,n)=>{Qi(n);const i=Yi(e.picker),o=Tg(r).suggestedName,s=t(n);if(!i.saveFile)throw _e("files.saveFile");const a=await Ie(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[_r]:async(r,n)=>{const i=De(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);kt(o.mode),await Ie(()=>o.create(Na(i),t(n)))},[Tr]:async(r,n)=>{const i=De(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),kt(o.handle.mode),!o.handle.remove)throw _e(Tr);await Ie(()=>o.handle.remove(t(n)))},[Hn]:async(r,n)=>{const i=De(r);return Da(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!Q(o)||o.kind!=="file")throw _a()})},[br]:async(r,n)=>{const i=De(r),o=Sa(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 g("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Fn]:async(r,n)=>{const i=De(r,["content"]);typeof i.content!="string"&&Oe("content 必须是字符串");const o=e.registry.resolveFile(i.target);kt(o.mode),await Ie(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[Or]:async(r,n)=>{const i=De(r),o=await Ie(()=>e.registry.resolveFile(i.target).read(t(n)));return Sa(o)},[Vn]:async(r,n)=>{const i=De(r,["content"]),o=e.registry.resolveFile(i.target);kt(o.mode),await Ie(()=>o.write(Og(i.content),t(n)))},[vr]:async(r,n)=>{const i=De(r),o=await Ie(()=>e.registry.resolveFile(i.target).stat(t(n)));return vg(o)}},directory:{[Bn]:async(r,n)=>{const i=De(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);kt(o.mode),await Ie(()=>o.create(Na(i),t(n)))},[Lr]:async(r,n)=>{const i=De(r,["recursive"]);if(Q(i.target)&&i.target.relativePath===".")throw g("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),kt(o.handle.mode),!o.handle.remove)throw _e(Lr);await Ie(()=>o.handle.remove({recursive:i.recursive===void 0?!1:si(i.recursive,"recursive")},t(n)))},[Gn]:async(r,n)=>{const i=De(r);return Da(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!Q(o)||o.kind!=="directory")throw _a()})},[Qn]:async(r,n)=>{const i=De(r,["limit"]),o=bg(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 Sg(e){if(e===void 0)return{mode:"read",multiple:!1};Q(e)||Oe("pickFiles 参数必须是对象"),Ti(e,["mode","accept","multiple"]);const t=nu(e.mode,"read"),r=e.multiple===void 0?!1:si(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)))&&Oe("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function _g(e){return e===void 0?{mode:"read"}:(Q(e)||Oe("pickDirectory 参数必须是对象"),Ti(e,["mode"]),{mode:nu(e.mode,"read")})}function Tg(e){return Q(e)||Oe("saveFile 参数必须是对象"),Ti(e,["suggestedName"]),{suggestedName:Br(e.suggestedName,"suggestedName")}}function De(e,t=[]){return(!Q(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Oe("文件操作参数必须包含 target"),Ti(e,["target",...t]),e}function Na(e){return{recursive:e.recursive===void 0?!1:si(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:si(e.exclusive,"exclusive")}}function nu(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&Oe("mode 必须是 read 或 readwrite"),e)}function si(e,t){return typeof e!="boolean"&&Oe(`${t} 必须是布尔值`),e}function bg(e){if(e===void 0)return Ma;if((!Number.isSafeInteger(e)||e<=0)&&Oe("limit 必须是正整数"),e>Ma)throw g("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Ti(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&Oe(`不支持字段: ${r.join(", ")}`)}function kt(e){if(e!=="readwrite")throw g("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Qi(e){if(!e.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Yi(e){if(!e)throw _e("files.external");return e}async function Da(e){try{return await e(),!0}catch(t){if(Ng.has(ps(t)??""))return!1;throw Rr(t)}}async function Ie(e){try{return await e()}catch(t){throw Rr(t)}}function Og(e){return e instanceof Uint8Array||Oe("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Oe("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Sa(e){if(!(e instanceof Uint8Array))throw g("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function _a(){return g("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function vg(e){if(!Q(e)||e.kind!=="file"||!Lg(e.size))throw g("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Cg(e[t]))throw g("FILE_IO_FAILED",`Host 返回了无效 ${t}`);return{kind:"file",size:e.size,...e.modifiedAt===void 0?{}:{modifiedAt:e.modifiedAt},...e.createdAt===void 0?{}:{createdAt:e.createdAt}}}function Lg(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Cg(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Oe(e){throw g("INVALID_PARAMS",e)}const Rg=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),qi={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function Pg(e){if(e instanceof le)return g("REQUEST_UNSUPPORTED",qi.REQUEST_UNSUPPORTED);const t=iu(e);return t!==void 0&&Rg.has(t)?g(t,qi[t]??"媒体操作失败"):g("MEDIA_PREPARE_FAILED",qi.MEDIA_PREPARE_FAILED)}function iu(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 kg=["source","mediaType","maxCount"],un=Object.freeze({source:"album",mediaType:"all",maxCount:1});function xg(e){if(e===void 0)return un;if(!Vl(e))throw g("INVALID_PARAMS",jg(e));return Ug(e)}function Ug(e){return Object.freeze({source:e.source??un.source,mediaType:e.mediaType??un.mediaType,maxCount:e.maxCount??un.maxCount})}function jg(e){if(!Q(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!kg.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 zg=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),Hg={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class Fg{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=Vg(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>Gg(s,i[a]));if(!Bl(o))throw Ge("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(Qg).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=iu(n);throw i!==void 0&&zg.has(i)?n:Ge("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function Ta(e,t){if(e.signal.aborted)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw g("REQUEST_CANCELLED","media.pick 已取消")}function Vg(e,t){if(!Array.isArray(e))throw Ge("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw Ge("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw Ge("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw Ge("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw Ge("Host 返回了稀疏媒体结果");Bg(e[n],n)}return e}function Bg(e,t){if(!Q(e))throw Ge(`第 ${t+1} 项不是对象`);if(!fd({...e,file:Hg}))throw Ge(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!Q(e.file))throw Ge(`第 ${t+1} 项缺少文件句柄`)}function Gg(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 Qg(e){return"handleId"in e.ref?e.ref.handleId:void 0}function Ge(e){return g("MEDIA_PREPARE_FAILED",e)}function Yg(e){const t=e.media?new Fg(e.registry,e.media,e.operationContext):void 0;return{handlers:{[Cr]:async(n,i)=>{const o=xg(n);Wg(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw _e(Cr);const c=Ne(e.operationContext,i.signal);Ta(e.operationContext,i.signal);const d=await qg(s,o,c,e.operationContext,i.signal);Ta(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function qg(e,t,r,n,i){try{return await W(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?g("REQUEST_CANCELLED","media.pick 已取消"):Pg(o)}}function Wg(e){if(!e.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Xr=4294967296;function $g(e){const t=new Kg;return t.write(e),t.finish()}class Kg{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<Xr?(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=Zg(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<Xr)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/Xr),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Xr)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Zg(e){const t=new Uint8Array(Jg(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 Jg(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 ou(e){jo(e);const t=$g(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 jo(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)jo(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");jo(s,t+1,r)}r.delete(e)}const Xg=["pc","console","mobile"],ep=["game","wiki"];function ai(e){throw{code:"INVALID_PARAMS",message:e}}function tp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function it(e,t){return typeof e!="string"||!e.trim()?ai(t):e.trim()}function ba(e,t,r){return typeof e!="string"||!t.includes(e)?ai(r):e}function rp(e){const t={target:"game_detail",appId:it(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:ba(e.gameType,Xg,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=ba(e.page,ep,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=it(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=it(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function np(e){return{target:"user_detail",userId:it(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function ip(e){const t={target:"post_detail",linkId:it(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=it(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=it(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function op(e){const t={target:"mini_program",miniProgramId:it(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function sp(e){return tp(e)?e.target==="game_detail"?rp(e):e.target==="user_detail"?np(e):e.target==="post_detail"?ip(e):e.target==="mini_program"?op(e):ai("navigation.openAppPage target 不支持"):ai("navigation.openAppPage options 必须是对象")}function ap(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 cp(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function dp(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 up(e){const t=e;return t.target==="game_detail"?ap(t):t.target==="user_detail"?cp(t):dp(t)}const lp="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",fp="data-hb-sdk-fullscreen-exit",hp=3e3,mp=2e3,Oa="var(--white-70a,rgba(255,255,255,.7))",va="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function gp(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(fp,""),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 ${Oa}`,`box-shadow:${va}`,"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=lp,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 m(M=mp){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")},M)}function h(){l(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Oa,t.style.boxShadow=va,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),m()}async function p(){if(!(s||a)){if(!o){h();return}a=!0,clearTimeout(c),l();try{await e()}catch{}finally{a=!1,s||h()}}}return t.addEventListener("click",p),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"})),m(hp),{dispose(){s=!0,clearTimeout(c),l(),t.removeEventListener("click",p),window.removeEventListener("resize",f),t.remove()}}}const su=1e4;function au(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()},su);return{signal:r.signal,async run(s){try{return await W(s,r.signal)}catch(a){throw n??a}},dispose(){clearTimeout(o),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function La(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 Wi(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function dr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function pp(e){let t=0,r=0,n,i,o={mode:"portrait",hideCapsule:!1},s={mode:"portrait",hideCapsule:!1},a;function c(){a?.dispose(),a=void 0}function d(h){if(!h.hideCapsule){c();return}a??=gp(()=>m.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",c,{once:!0});function u(h,p){if(n===h){if(n=void 0,clearTimeout(h.timer),e.operationContext.signal.removeEventListener("abort",f),"error"in p)h.controller.abort();else if(i={options:h.options,result:p.result},o=h.options,d(h.options),e.onApplied?.(h.options),p.result.supported&&!Wi(s,h.options)){s={...h.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:h.source})}catch{}}for(const M of h.subscribers)M.dispose(),"error"in p?M.reject(p.error):M.resolve(p.result);h.subscribers.clear()}}function f(){n&&u(n,{error:dr()})}function l(h,p){return new Promise((M,w)=>{const T=()=>{h.subscribers.delete(_),_.dispose(),w(dr()),h.subscribers.size===0&&u(h,{error:dr()})},_={resolve:M,reject:w,dispose:()=>p?.removeEventListener("abort",T)};h.subscribers.add(_),p?.addEventListener("abort",T,{once:!0}),p?.aborted&&T()})}const m={async runDisplayRequest(h,p,M){const w=++t,T=au(p,e.operationContext.signal);try{return await T.run(async()=>{if(await M(T.signal),T.signal.aborted)throw dr();if(La(h),w<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=w,m.apply(h,T.signal)})}finally{T.dispose()}},async apply(h,p,M="api"){if(X(e.operationContext.signal),p?.aborted)throw dr();const w=La(h),T=n?.options??o,_={mode:w.orientation??T.mode,hideCapsule:w.fullscreen??T.hideCapsule};_.mode==="landscape"&&(_.hideCapsule=!0);const P=e.presentation.applyOrientation;if(!P)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&Wi(n.options,_))return l(n,p);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&Wi(i.options,_))return i.result;i=void 0;const F={options:_,source:M,controller:new AbortController,subscribers:new Set};n=F;const U=l(F,p);return e.operationContext.signal.addEventListener("abort",f,{once:!0}),p||(F.timer=setTimeout(()=>{u(F,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},su)),W(()=>P.call(e.presentation,_,{...e.operationContext,signal:F.controller.signal}),F.controller.signal).then(O=>u(F,{result:O??{supported:!0}}),O=>u(F,{error:O})),U},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return m}function cu(e){throw{code:"INVALID_PARAMS",message:e}}function Ca(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&cu(`${t} 不支持参数`)}function yp(e){return{[Jn]:async t=>{X(e.operationContext.signal),Ca(t,"navigation.close"),await W(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Xn]:async t=>{X(e.operationContext.signal),Ca(t,"navigation.reload"),await W(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[ei]:async(t,r)=>{const n=Ne(e.operationContext,r?.signal);X(n.signal);const i=sp(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=ou(i.extra)}catch{cu("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=au(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}X(n.signal),await W(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await W(()=>e.presentation.openAppPage(up(i),n),n.signal)}}}const Ra={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function Ep(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw _e("network.upload");const o=Ne(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw g("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(l){throw s(),Rr(l)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw g("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw g("FILE_TOO_LARGE","文件超过大小限制");let d=0,u=!1;const f=l=>{u||o.signal.aborted||!Number.isSafeInteger(l)||l<d||l>c.size||(d=l,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:l,...m}=e,h=await n.upload(a,{...m,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:f});if(u=!0,!Number.isSafeInteger(h.uploadedBytes)||h.uploadedBytes<d||h.uploadedBytes>c.size)throw g("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(h.status>=200&&h.status<300&&h.uploadedBytes!==c.size)throw g("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:h.uploadedBytes,total:c.size,lengthComputable:!0}),h}catch(l){u=!0;const m=ps(l);throw m&&Ra[m]?g(m,Ra[m]):o.signal.aborted?g("UPLOAD_CANCELLED","上传已取消"):m?.startsWith("FILE_")||m?.startsWith("DIRECTORY_")?Rr(l):g("UPLOAD_NETWORK_FAILED","上传网络失败")}}const As="withCredentials",wp=new Set(["url","method","params","data","headers","timeout",As]),Ip=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",As]),Ap=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Pa=3e4,zo=2*1024*1024,Mp=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,du=/[\u0000-\u0008\u000A-\u001F\u007F]/,Np=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Dp="network.request 不支持 multipart/form-data,请使用专用上传能力";function Sp(e){const t=_p(e.runtimePermissions),r=Hp(e.allowedHttpOrigins);return{[xn]:async(n,i)=>{const o=bp(n,{permission:t,allowedHttpOrigins:r}),s=await Ep(o,i,e),{uploadedBytes:a,...c}=s;return xa(c)},[kn]:async(n,i)=>{const o=Op(n,{permission:t,allowedHttpOrigins:r});return qd(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Pn]:async(n,i)=>{const o=Ne(e.operationContext,i?.signal);X(o.signal);const s=Tp(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await W(()=>e.network.request(s,o),o.signal)}catch(c){throw Vp(c)?c:Bp(c,"REQUEST_UNSUPPORTED")?q("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):q("REQUEST_FAILED","网络请求失败")}return xa(a)}}}function _p(e){const t=Re(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Tp(e,t){const r=Zt(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!wp.has(c));if(n.length>0)throw q("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);uu(r,"network.request");const i=Ms(r,t,"network.request"),o=Lp(r.method),s=r.data;s!==void 0&&Pp(s),xp(i.headers,s);const a=Up(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 bp(e,t){const r=Zt(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=Ms(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(!Wt(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=ka(r.fieldName),c=r.fields===void 0?void 0:Zt(r.fields,"fields 必须是字符串字典");for(const[u,f]of Object.entries(c??{}))if(ka(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"||du.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>zo)throw q("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:Es(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function ka(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw q("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function Op(e,t){const r=Zt(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!Ip.has(c));if(n.length>0)throw q("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);uu(r,"network.download");const i=Ms(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw q("INVALID_PARAMS","network.download timeout 必须是有限正数");Jm(i.headers);const o=Wt(r.to),s=ud(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=Es(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 Ms(e,t,r){const n=vp(e.url,t.allowedHttpOrigins,r),i=Hf(n);if(i&&!t.permission.useOfficialDomain)throw q("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(zf(n.pathname,i))throw q("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Zt(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Cp(e.headers,r),timeout:Rp(e.timeout,r)}}function vp(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 Lp(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(!Ap.has(t))throw q("INVALID_PARAMS","network.request method 不合法");return t}function Cp(e,t="network.request"){const r=Zt(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!Mp.test(s)||typeof o!="string"||du.test(o))throw q("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Ff(s))throw q("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function uu(e,t){const r=e[As];if(r!==void 0&&typeof r!="boolean")throw q("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Rp(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>Pa)throw q("INVALID_PARAMS",`${t} timeout 不能超过 ${Pa}ms`);return e}}function Pp(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(kp(e)>zo)throw q("INVALID_PARAMS",`network.request data 不能超过 ${zo} 字节`)}function kp(e){if(typeof e=="string")return $i(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return $i(e.toString());try{const t=JSON.stringify(e);return t?$i(t):0}catch{throw q("INVALID_PARAMS","network.request data 必须可序列化")}}function xp(e,t){const r=lu(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",Dp)}function Up(e,t,r){if(t===void 0)return;const n=lu(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)||zp(t))?"form":jp(t)?"json":void 0}function lu(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function jp(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function zp(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Hp(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&&Fp(n.hostname)&&t.add(n.origin)}catch{}return t}function Fp(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 xa(e){return Object.keys(e.headers).some(Ua)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Ua(t)))}:e}function Ua(e){const t=e.trim().toLowerCase();return Np.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Vp(e){return e instanceof Error&&e.name==="AbortError"}function Bp(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Zt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw q("INVALID_PARAMS",t);return e}function $i(e){return new TextEncoder().encode(e).length}function q(e,t){return{code:e,message:t}}function Gp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qp(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 Yp(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=Qp(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function qp(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 fu(e,t){if(e==null)return{};if(!Gp(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=Yp(e.topicIds),n=qp(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 Wp(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function $p(e){try{if(Wp(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function fe(e){throw{code:"INVALID_PARAMS",message:e}}function Gr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ho(e,t){return typeof e!="string"||!e.trim()?fe(t):e}function Kp(e,t){const r=Ho(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?fe(t):r}catch{return fe(t)}}function Zp(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function hu(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 Jp(e,t){if(!Gr(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&&!Zp(r))return fe("share.showShareMenu channel 不合法");const n=mu(e.extra,"share.showShareMenu");return{title:Ho(e.title,"share.showShareMenu title 必须是非空字符串"),description:Ho(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:hu(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:Kp(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function mu(e,t){if(e!==void 0)try{return ou(e)}catch{return fe(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function gu(e,t){return e.invalidMessage&&await W(()=>$p(t.environment),t.operationContext.signal)?fe(e.invalidMessage):e.post}function ja(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Xp(e){const t=e.getViewportMetrics();return{left:0,top:0,width:ja(t.windowWidth,0),height:ja(t.windowHeight,0)}}function Fo(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?fe(t):r}function za(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?fe(t):r}function ey(e){return Gr(e)?{left:Fo(e.left,"share.screenshot rect.left 必须是非负数字"),top:Fo(e.top,"share.screenshot rect.top 必须是非负数字"),width:za(e.width,"share.screenshot rect.width 必须是正数"),height:za(e.height,"share.screenshot rect.height 必须是正数")}:fe("share.screenshot rect 必须是对象")}function ty(e,t){if(e!=null&&!Gr(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?Xp(t):ey(r.rect),...r.delay===void 0?{}:{delay:Fo(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function ry(e,t){X(t.operationContext.signal);const r=Jp(e,t);let n=fu(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await gu(n,t);return W(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function ny(e,t){if(X(t.operationContext.signal),e!==void 0&&!Gr(e))return fe("share.copyLink 参数必须是对象");const r=mu(e?.extra,"share.copyLink"),n=hu(t,"share.copyLink",r);return await W(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function iy(e,t,r){X(t.operationContext.signal);const n=fu(Gr(e)?e.post:void 0,{method:"share.screenshot"}),i=await gu(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=oy(),{watermarkTheme:a,...c}=r;let d=!1,u,f;try{d=!0,await W(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),u=await t.prepareScreenshot?.(r.rect,t.operationContext.signal,a),f={status:"fulfilled",value:await W(()=>t.presentation.captureAndShare({...c,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(m){f={status:"rejected",error:m}}finally{u?.()}const l=d?await sy(t.presentation,s,t.operationContext.signal):void 0;if(f.status==="rejected")throw f.error;if(l)throw l;return f.value}function oy(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function sy(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await W(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function ay(e){let t=Promise.resolve();return{[On]:(r,n)=>ny(r,e),[vn]:(r,n)=>ry(r,e),[Ln]:async(r,n)=>{const i=Ne(e.operationContext,n.signal);X(i.signal);const o=ty(r,e.presentation),s=t.then(()=>iy(r,{...e,operationContext:i},o));return t=s.then(()=>{},()=>{}),W(()=>s,i.signal)}}}const Ha=new WeakMap;function pu(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return yf(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Ad(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function yu(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=Ha.get(t);f||(f=new Map,Ha.set(t,f));const l=f.get(u)??Promise.resolve(),m=async()=>(X(c.signal,{preserveReason:!0}),d(u)),h=l.catch(()=>{}).then(()=>e.lock?e.lock(u,m):m());f.set(u,h);try{return await h}finally{f.get(u)===h&&f.delete(u)}},o=async(c,d,u=!1)=>{const f=Ot(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(h=>h.key.startsWith(f)&&h.value!=="").map(h=>h.key.slice(f.length)))];const l=await e.storage.getRaw(Wr(c),d);if((l===void 0||l==="")&&!u)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let m;try{m=l?JSON.parse(l):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(m)||m.length>zs||m.some(h=>typeof h!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(h)))throw new Error("本地数据索引异常");return[...new Set(m)]},s=async(c,d)=>{if(e.diagnostics){const l=Ot(c,"");return(await e.diagnostics.listRaw(d)).filter(m=>m.key.startsWith(l)&&m.value!=="").map(m=>({...m,key:m.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 m=await Promise.all(f.slice(l,l+16).map(async h=>{const p=await e.storage.getRaw(Ot(c,h),d);return p!==void 0&&p!==""?{area:"local",key:h,value:p}:void 0}));for(const h of m)h&&u.push(h)}return u},a=c=>{if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw Object.assign(new Error("storage key 不合法"),{code:"INVALID_REQUEST"})};return{get(c,d){return a(c),i(d,u=>e.storage.getRaw(Ot(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>=zs)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const m=[...new Set([...l,c])];await e.storage.setRaw(Wr(f),JSON.stringify(m),u)}X(u.signal,{preserveReason:!0}),await e.storage.setRaw(Ot(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(Wr(d),JSON.stringify(u),c);for(let f=0;f<u.length;f+=16){X(c.signal,{preserveReason:!0});const m=(await Promise.allSettled(u.slice(f,f+16).map(h=>e.storage.setRaw(Ot(d,h),"",c)))).find(h=>h.status==="rejected");if(m)throw m.reason}X(c.signal,{preserveReason:!0}),await e.storage.setRaw(Wr(d),"[]",c)})}}}function cy(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 dy=128,uy=/^[A-Za-z0-9_-]+$/;function ly(e){const t=e.scopedStorage??yu({storage:e.storage,resolveScope:()=>pu({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[Dr]:async n=>{X(e.operationContext.signal);const i=Fa(n,Dr,e.storageLimits?.maxKeyLength),o=await W(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:Va(o)}},[Sr]:async n=>{X(e.operationContext.signal);const i=Eu(n,"storage.setStorage 参数必须是对象"),o=Fa(i,Sr,e.storageLimits?.maxKeyLength),s=fy(i.data,e.storageLimits?.maxValueBytes);await W(()=>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 W(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?yt("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:Va(o),serializedValue:o,bytes:wu(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function Fa(e,t,r=dy){const i=Eu(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw yt("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!uy.test(i))throw yt("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function fy(e,t){let r;try{r=JSON.stringify(e)}catch{throw yt("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw yt("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&wu(r)>t)throw yt("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Va(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Eu(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw yt("INVALID_PARAMS",t);return e}function wu(e){return new TextEncoder().encode(e).length}function yt(e,t){return{code:e,message:t}}const Ba=120;function et(e){throw{code:"INVALID_PARAMS",message:e}}function Ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Iu(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&et(`${r} 不支持字段: ${n.join(", ")}`)}function hy(e){if(!Ns(e))return et("ui.showToast 参数必须是对象");if(Iu(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return et("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Ba)return et(`ui.showToast message 不能超过 ${Ba} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return et("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function my(e){return e===void 0?{dismissible:!1}:Ns(e)?(Iu(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?et("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):et("ui.showLoading 参数必须是对象")}function gy(e){e!==void 0&&(!Ns(e)||Object.keys(e).length)&&et("ui.hideLoading 不支持参数")}function py(e){return{[Yn]:async t=>{X(e.operationContext.signal),await W(()=>e.presentation.showToast(hy(t),e.operationContext),e.operationContext.signal)},[qn]:async t=>{X(e.operationContext.signal),await W(()=>e.presentation.showLoading(my(t),e.operationContext),e.operationContext.signal)},[Wn]:async t=>{X(e.operationContext.signal),gy(t),await W(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const yy={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ae(e,"当前用户首页资料接口响应异常")}},Ey=3e4;function wy(e,t,r={}){const n=r.ttlMs??Ey,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 _i(e,yy,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(l){throw t.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):l instanceof le?g("REQUEST_UNSUPPORTED",l.message):l instanceof Vr?g("INVALID_RESPONSE","user home_v2 响应不合法"):l instanceof Kt?g("REQUEST_FAILED","user home_v2 请求失败"):l instanceof Fr?i&&(l.status===403||l.status===429)?g("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:l.status,...l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs}}):g("REQUEST_FAILED",l.message):Ay(l)?l:g("REQUEST_FAILED","user home_v2 请求失败")}return Iy(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 m=s,h=d().then(p=>(s===m&&(a={userId:f,value:p,expiresAt:Date.now()+n}),p)).finally(()=>{c?.promise===h&&(c=void 0)});return c={userId:f,generation:m,promise:h},h}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function Iy(e,t){if(!Q(e))throw g("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw g(n,r)}if(!Q(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Ay(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}const My={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,"关注用户接口响应异常")}},Ny={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 接口响应异常")}},Dy={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 接口响应异常")}},Sy={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 _y(e,t=bo){const r=Gf({version:"2",validate:by}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):bo,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 Ga(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 Ty(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 by(e){if(!Q(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Qa(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Ft();for(const t of e.gameList){if(!Q(t)||!Vo(t.appid)||!Vo(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Ft();for(const r of["image","portraitImage","icon"])Oy(t,r);for(const r of["playtimeForever","playtime2Weeks"])Qa(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Ft()}return e}function Vo(e){return typeof e=="number"&&Number.isFinite(e)}function Qa(e,t){if(e[t]!==void 0&&!Vo(e[t]))throw Ft()}function Oy(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Ft()}function Ft(){return g("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Au=20,vy=100,Ly=128,Mu=0,Nu="weeks",Cy=100,Ry=new Set(["weeks","all","achieved"]);function Py(){return{nickname:"",avatar:""}}function ky(e){const t=wy(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??Dd(),i=_y(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(D,R){const b=JSON.stringify([D,R]);return(!o||o.key!==b)&&(o={key:b,scope:n.createScope(R,n.createScope(D))}),o.scope}function d(){const D=o;o=void 0,D&&n.invalidateScope(D.scope).catch(()=>{}),s.clear()}const u=kd({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??Rd))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let l,m,h=0,p=!1;const M=e.account.onChange(()=>{h+=1,t.clear(),u.invalidate(),d()}),w=e.authorization.onEvent((D,R)=>{D==="user_info_authorization_change"&&Object.values(R).some(b=>b==="denied")&&(h+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(p)return;const b=await e.account.getCurrentUserId(e.operationContext);typeof b=="string"&&b.trim()&&await n.invalidateScope(c(_(),b.trim()))}).catch(()=>{}))});function T(){if(p||e.operationContext.signal.aborted)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function _(){const D=e.identity.get()?.miniProgramId?.trim();if(!D)throw g("INVALID_STATE","用户能力缺少 canonical 小程序身份");return D}async function P(){T(),await a,T();let D;try{D=await e.account.getCurrentUserId(e.operationContext)}catch(R){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):ur(R)?R:g("REQUEST_FAILED","读取小黑盒账号失败")}return typeof D=="string"&&D.trim()?D.trim():void 0}async function F(D,R){const b=await P();if(h!==R||b!==D)throw g("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function U(D,R,b=e.operationContext.signal){try{return await _i(e.network,D,R,{...e.operationContext,signal:b,credentials:"heybox-session",...f?{gate:f}:{}})}catch(A){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):A instanceof le?g("REQUEST_UNSUPPORTED",A.message):A instanceof Vr?g("INVALID_RESPONSE","用户接口响应不合法"):A instanceof Kt?g("REQUEST_FAILED","用户请求失败"):A instanceof Fr?r&&(A.status===403||A.status===429)?g("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:A.status,...A.retryAfterMs===void 0?{}:{retryAfterMs:A.retryAfterMs}}):g("REQUEST_FAILED",A.message):ur(A)?A:g("REQUEST_FAILED","用户请求失败")}}async function O(D,R){if(!e.authorizationContext)return{mini_program_id:D};let b;try{b=await W(()=>e.authorizationContext.get({...e.operationContext,signal:R}),R)}catch(A){if(ur(A))throw A;const I=g("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(I,"cause",{configurable:!0,value:A}),I}if(!b.token?.trim())throw g("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:D,runtime_auth_context_token:b.token}}async function E(){T();const D=_(),R=h,b=await P();if(!b){if(h!==R)throw g("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const A=await O(D,e.operationContext.signal);await F(b,R);const I=await U(Ny,A);if(await F(b,R),_()!==D)throw g("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Wa(qa(I))}function S(D,R){if(!D)return Promise.reject(g("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(R?.aborted)return Promise.reject(g("REQUEST_CANCELLED","关注操作已取消"));if(l)return Promise.reject(g("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(g("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const b=v(R).finally(()=>{l===b&&(l=void 0)});return l=b,b}async function v(D){T();const R=_(),b=new AbortController;m=b;const A=()=>b.abort();e.operationContext.signal.addEventListener("abort",A,{once:!0}),D?.addEventListener("abort",A,{once:!0});let I=()=>{},L=!1;try{try{await W(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:b.signal}),b.signal)}catch(ne){throw ur(ne)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(ne.code)?g("FOLLOW_CANCELLED","已取消小黑盒登录"):ne}T();const k=h;I=e.account.onChange(()=>{L=!0,A()});const x=await W(P,b.signal);if(!x)throw g("FOLLOW_CANCELLED","未完成小黑盒登录");const z=async()=>{if(await W(()=>F(x,k),b.signal),T(),_()!==R)throw g("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await z();const H=await O(R,b.signal);await z();const V=Gy(),G=await W(()=>U(Dy,{...H,request_id:V},b.signal),b.signal);await z();const J=qa(G);if(J.status!=="notFollowing")return Wa(J);if(J.rateLimited)throw g("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const K=await W(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:R,signal:b.signal}),b.signal);if(await z(),K!=="confirmed")throw g("FOLLOW_CANCELLED","已取消关注作者");const Z=J.authorId,Y=await W(()=>U(My,{body:{following_id:Z}},b.signal),b.signal);if(await z(),Y.status!=="ok"){const ne=["login","relogin","lack_token"].includes(Y.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw g(ne,typeof Y.msg=="string"&&Y.msg.trim()?Y.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(k){throw T(),L?g("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):D?.aborted?g("REQUEST_CANCELLED","关注操作已取消"):ur(k)?k:g("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{I(),e.operationContext.signal.removeEventListener("abort",A),D?.removeEventListener("abort",A),m===b&&(m=void 0)}}async function C(){_();const D=h,R=await P();if(!R)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[b,A]=await Promise.all([e.authorization.getOrCreateLocalIdentity(R),y(R).catch(()=>Py())]);return await F(R,D),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:b.appUserId,profile:A,...b.steamId?{steam_id:b.steamId}:{}}}}function y(D){return u.read(D,()=>U(Pd,void 0).then(R=>{const b=Bo(R,"账号基础信息");if(b.display_username!==void 0&&typeof b.display_username!="string")throw g("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(b.display_avatar!==void 0&&typeof b.display_avatar!="string")throw g("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:b.display_username??"",avatar:b.display_avatar??""}}))}async function N(D){const R=xy(D),b=_(),A=h,I=await P();if(!I)return d(),{isLogin:!1,isBound:!1,data:null};const L=await t.get(I);await F(I,A);const k=Du(L.steam_id_info);if(Object.keys(k).length===0)return await n.invalidateScope(c(b,I)).catch(()=>{}),await F(I,A),s.delete(JSON.stringify([b,I])),{isLogin:!0,isBound:!1,data:null};const x=JSON.stringify([b,I]),z=c(b,I),H=Ga({...R,steamId:void 0},k),V=Su(k.personal_infomation_open??k.personal_information_open),G=JSON.stringify([H??null,V??null]),J=s.get(x);J&&J.identity!==G&&(await n.invalidateScope(z).catch(()=>{}),await F(I,A));const K={identity:G,scope:n.createScope(G,z)};s.set(x,K);const Z=Ga(R,k),Y=Z?i.persistent:i.unresolved,ne=n.createScope(Z??"unresolved",K.scope),ve=async()=>{if(await F(I,A),_()!==b||s.get(x)?.identity!==G)throw g("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},Qe=await Y.read({scope:ne,key:Ty({miniProgramId:b,userId:I,effectiveSteamId:Z,personalInformationOpen:V,query:R}),signal:e.operationContext.signal,load:async ye=>{const Le=await U(Sy,{userId:I,...R,personalInformationOpen:V},ye);return await ve(),Fy(Bo(Le,"Steam 游戏库"),R)}}).catch(async ye=>{throw await ve(),ye});return await ve(),{isLogin:!0,isBound:!0,data:Qe}}return{getFollowStatus:E,requestFollowAuthor:S,getInfo:C,getSteamGameList:N,async invalidateSteamGameListCache(){const D=_(),R=h,b=await P();if(!b)return;const A=c(D,b);await Promise.all([i.persistent.invalidateScope(A),i.unresolved.invalidateScope(A)]),t.clear(),s.delete(JSON.stringify([D,b])),await F(b,R)},dispose(){p||(p=!0,m?.abort(),h+=1,M(),w(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function xy(e){if(e==null)return{limit:Au,offset:Mu,sort:Nu,includeHidden:!1};if(!Q(e))throw tt("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw tt(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Uy(e.limit),offset:jy(e.offset),sort:zy(e.sort),includeHidden:Hy(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>Ly)throw tt("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw tt("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Cy))}return r}function Uy(e){if(e===void 0)return Au;if(!Number.isInteger(e)||Number(e)<1)throw tt("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),vy)}function jy(e){if(e===void 0)return Mu;if(!Number.isInteger(e)||Number(e)<0)throw tt("user.getSteamGameList offset 必须是非负整数");return Number(e)}function zy(e){if(e===void 0)return Nu;if(typeof e!="string"||!Ry.has(e))throw tt("user.getSteamGameList sort 不支持");return e}function Hy(e){if(e===void 0)return!1;if(typeof e!="boolean")throw tt("user.getSteamGameList includeHidden 必须是 boolean");return e}function Fy(e,t){if(!Array.isArray(e.game_list))throw g("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(Vy).filter(a=>a!==void 0),n=ci(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=Su(e.is_me);return s!==void 0&&(o.isMe=s),o}function Vy(e){const t=Du(e),r=ci(t.appid),n=ci(t.steam_appid)??r,i=Ds(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};Ki(o,"image",t.image),typeof t.vertical_head_image=="string"&&Ki(o,"portraitImage",t.vertical_head_image),Ki(o,"icon",t.appicon??t.icon),Ya(o,"playtimeForever",t.playtime_forever),Ya(o,"playtime2Weeks",t.playtime_2weeks);const s=By(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function Bo(e,t){if(!Q(e))throw g("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw g(n,r)}if(!Q(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Du(e){return Q(e)?e:{}}function Ds(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function By(e){return Array.isArray(e)?e.map(Ds).filter(Boolean):[]}function ci(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function Su(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function Ki(e,t,r){const n=Ds(r);n&&Object.assign(e,{[t]:n})}function Ya(e,t,r){const n=ci(r);n!==void 0&&Object.assign(e,{[t]:n})}function tt(e){return g("INVALID_PARAMS",e)}function ur(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}function qa(e){const t=Bo(e,"关注状态");if(![0,1,2].includes(t.follow_status)||typeof t.author_id!="string"||!/^[1-9]\d*$/.test(t.author_id)||typeof t.rate_limited!="boolean")throw g("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Wa(e){return e.status}function Gy(){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 Qy(e){return{[Dn]:async t=>(en(t,"user.getFollowStatus"),e.user.getFollowStatus()),[Sn]:async(t,r)=>(en(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[_n]:async t=>(en(t,"user.getInfo"),e.user.getInfo()),[Tn]:async(t,r)=>{en(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[bn]:async t=>e.user.getSteamGameList(t)}}function en(e,t){if(e!==void 0)throw g("INVALID_PARAMS",`${t} 不接收入参`)}function $a(e){throw{code:"INVALID_PARAMS",message:e}}function lr(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function _u(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function tn(e,t,r){return Math.min(_u(e,t),r)}async function Yy(e){try{return _u(await e.getNavigationBarHeight(),0)}catch{return 0}}function qy(e,t,r,n){const i=tn(e.safeArea?.left,0,t),o=Math.max(i,tn(e.safeArea?.right,t,t)),s=tn(e.safeArea?.top,n,r),a=Math.max(s,tn(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Ka(e){const t=e.getViewportMetrics(),r=lr(t.windowWidth,0),n=lr(t.windowHeight,0),i=await Yy(e);return{pixelRatio:lr(t.pixelRatio,1),screenWidth:lr(t.screenWidth,r),screenHeight:lr(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:qy(t,r,n,i),screenTop:i}}function Wy(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;Ka(r.presentation).then(l=>{if(n||r.operationContext.signal.aborted||f!==i)return;const m=JSON.stringify(l);m!==o&&(o=m,r.onViewportChange?.(l))}).catch(()=>{})},c=pp({...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:{[wt]:async(f,l)=>c.apply(f,l?.signal),[Cn]:async()=>(X(r.operationContext.signal),Ka(r.presentation)),[Rn]:async f=>{if(X(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return $a("viewport.setNavigationBarStyle 参数必须是对象");const l=f.foregroundStyle;if(l!=="light"&&l!=="dark")return $a("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await W(()=>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 $y=new Map(nt.map(e=>[e.method,e]));function ln(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function Ky(e){const t=of(e);return r=>t(r.requirement,r.method)}function Zy(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 Jy(e){const t=Ky(e.runtimePermissions),r=Re(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??Xy,c=e.onTrace?a():0,d=e.onTrace?`cap_${++n}`:"";try{if(e.terminalSignal.aborted)throw ln("RUNTIME_DESTROYED","小程序 Runtime 已终止");If(i,e.effectiveCapabilities);const u=$y.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,m=!f.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,o)===!0;if(!f.allowed&&!l&&!m)throw ln(f.code,f.message,f.data);const h=e.handlers[i];if(!h)throw new Error(`Capability method ${i} 缺少 handler`);const p=async T=>{for(const _ of e.policies??[]){const P=await _.evaluate({method:i,payload:o,capability:u});if(e.terminalSignal.aborted||T.aborted)throw Xa();if(!P.allowed)throw ln(P.code,P.message,P.data)}if(e.terminalSignal.aborted||T.aborted)throw Xa()},w=await Zy(async()=>{if(i===wt){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,p)}return await p(e.terminalSignal),h(o,s)},void 0,s,e.terminalSignal);return Za(e.onTrace,Ja(d,i,o,c,w),a),w}catch(u){throw Za(e.onTrace,Ja(d,i,o,c,{status:"error",error:u}),a),u}}}}function Xy(){return typeof performance>"u"?Date.now():performance.now()}function Za(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 Ja(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:eE(i.error)}:{},...tE(t,r,i)}}function eE(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function tE(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"&&Tu(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 Tu(e){return typeof e=="object"&&e!==null}function Xa(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function rE(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=sh(e.requestPolicy);let n;if(e.files)try{n=Kf(e.files,t)}catch{}const i=Dd({store:n}),o=e.onRequestPolicyReport??(r.debugReport?nE:void 0),s=r.enabled?rh({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new ys(e.files,e.miniProgramDetail),c=Dg({registry:a,picker:e.picker,operationContext:t}),d=Ch({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,m,h,p=()=>{},M=()=>{};try{u=Wy({operationContext:t,presentation:e.hostPresentation,onDisplayChange:E=>e.eventSink.postEvent("display_change",E),onViewportChange:E=>e.eventSink.postEvent("viewport_change",E)}),l=ky({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}),p=d.onEvent((E,S)=>e.eventSink.postEvent(E,S)),M=e.hostCompanion?.onSessionEvent?.(E=>{const S=Eg(E);!e.terminalSignal.aborted&&S&&e.eventSink.postEvent(S.type,S.payload)})??(()=>{}),m=hm({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled}),h=ng({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 w=ly({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});f=Yg({registry:a,media:e.media,operationContext:t});const T=[{name:"gameSaves",handlers:h.handlers},{name:"auth",handlers:Hh({authorization:d})},{name:"user",handlers:{...Qy({user:l,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...Bf({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:ay({prepareScreenshot:e.prepareScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:u.handlers},{name:"storage",handlers:w.handlers},{name:"network",handlers:Sp({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[An]:async()=>{throw ln("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:py({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Mg({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:yp({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:E=>u.applyOrientation({mode:"portrait",hideCapsule:!1},E)}:{}})},{name:"cloud",handlers:m.handlers},{name:"companion",handlers:hg({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],_=iE(T);let P=!1;const F=()=>{P||(P=!0,e.terminalSignal.removeEventListener("abort",F),u?.dispose(),f?.dispose(),m?.dispose(),h?.dispose(),p(),M(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?F():e.terminalSignal.addEventListener("abort",F,{once:!0});const U=new Set(["file.readText","file.readBytes","file.stat"]),O=(E,S)=>U.has(E)&&Tu(S)&&a.isCompanionAttachmentRef(S.target);return{modules:T,handlers:_,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:O,allowsGameSaveAccess:h.allowsRead,gameSaveDiagnostics:h.diagnostics,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...w.diagnostics?{storageDiagnostics:w.diagnostics}:{},dispose:F}}catch(w){throw u?.dispose(),f?.dispose(),m?.dispose(),h?.dispose(),p(),M(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),w}}function nE(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function iE(e){const t=new Map(nt.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=nt.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==nt.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const oE="heybox-mini-dev:";function ec(e){try{return sE(new URL(e))}catch{return!1}}function sE(e){return e.protocol===oE}function aE(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||cE(e)}function cE(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 dE=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function uE(e,t){const r=[],n=lE(e.environmentInfo,r),i=fn(n?.appVersion,"host.appVersion",r),o=hE(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:fE(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:fn(t.miniProgramId),version:fn(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function lE(e,t){if(e!=null){if(bu(e))return e;t.push("environmentInfo")}}function fE(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function hE(e,t){if(e==null)return{name:"unknown",version:null};if(!bu(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=dE.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:fn(e.version,"operatingSystem.version",t)}}function fn(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function bu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const mE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",gE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",pE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",yE="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function EE(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?pE:mE,l.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const m=e.createElement("div");m.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${c};border-radius:11px;padding:0 7px 0 6px;`;const h=e.createElement("img");h.src=a?yE:gE,h.style.cssText="width:12px;height:12px;flex-shrink:0;";const p=e.createElement("span");p.textContent=t?.trim()||"小程序工坊",p.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const M=e.createElement("div");M.textContent="小黑盒工坊小程序",M.style.cssText=`margin-top:6px;color:${a?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,m.append(h,p),f.append(l,m),u.append(f,M),s.append(u),e.body.append(s);const w=()=>{s.remove(),n.removeEventListener("abort",w)};n.addEventListener("abort",w,{once:!0});try{return await W(()=>Promise.all([l.decode(),h.decode()]),n),await W(()=>new Promise(T=>{let _=o.requestAnimationFrame(()=>{_=o.requestAnimationFrame(()=>{n.removeEventListener("abort",P),T()})});const P=()=>o.cancelAnimationFrame(_);n.addEventListener("abort",P,{once:!0})}),n),w}catch(T){throw w(),T}}const wE=1,Ou="allow-scripts allow-same-origin",IE="",AE="no-referrer";function ME(e=Ou){return!e.split(/\s+/).includes("allow-same-origin")}function tc(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const NE=new Set(["javascript:","data:","blob:","file:"]),rc="xiaoheihe.cn";function DE(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(NE.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!OE(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function SE(e,t){const r=new URL(e);return r.searchParams.set(Pl,t),r.toString()}function _E(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=TE(r)??bE(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function TE(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function bE(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function nc(e){const t=new URL(e);return Ss(t)?"loopback":_s(t)?"lan":"production"}function OE(e,t,r){return vE(e)||Ss(e)||_s(e)&&CE(t,r)}function vE(e){return e.protocol==="https:"&&kE(e.hostname)}function Ss(e){return e.protocol==="http:"&&LE(e.hostname)}function LE(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function _s(e){return e.protocol==="http:"&&RE(e.hostname)}function CE(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Ss(r)||_s(r)}catch{return!1}}function RE(e){const t=PE(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function PE(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 kE(e){return e===rc||e.endsWith(`.${rc}`)}const xE=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"]),UE=new Set(["url","inline","eval","unknown"]),jE=/^\/(?:\:segment(?:\/\:segment)*)?$/,zE=/^[a-f0-9]{64}$/,HE=255,FE=160,VE=256;function BE(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!xE.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>VE||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!UE.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=GE(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>FE||!jE.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!zE.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 GE(e){if(e!==void 0&&!(typeof e!="string"||e.length>HE))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const QE=/^(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 YE(e){if(!e?.minimumSdkVersion)throw ee("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=mt(e.minimumSdkVersion),r=e.sdkVersion?mt(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=mt("0.6.0");if(!r){if(hn(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(hn(r,t)<0)throw ee("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:hn(r,mt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function qE(e,t){if(typeof t!="string"||!mt(t))throw ee("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw ee("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function vu(e,t){const r=mt(e),n=mt(t);if(!(!r||!n))return hn(r,n)}function mt(e){const t=QE.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 hn(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 bi=["android","ios","ohos","windows","macos","linux"],WE="0.9.0",$E=Object.freeze(["android","ios","ohos","windows","macos"]),Lu="该小程序暂不支持当前平台",KE="PLATFORM_UNSUPPORTED";function ZE(e){return typeof e=="string"&&bi.includes(e)}function JE(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 XE(e){const t=e.manifest;if(!iw(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=oc(e.sdkVersion)??oc(t.sdkVersion);return rw(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:tw()}const r=Cu(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function ew(e){const t=JE(e.operatingSystemName);if(!t)return jt("host_operating_system_unknown");const r=e.platformAccess;if(!r)return jt("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:bi,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=XE({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?jt("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):ic(t,s)}if(r.effectivePlatforms===void 0)return jt("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=Cu(r.effectivePlatforms);if("reason"in n)return jt("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=nw(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return ic(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function ic(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:jt("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function jt(e,t={}){return{status:"denied",reason:e,message:Lu,...t}}function tw(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:$E,platformsDeclared:!1,policy:"legacy_mobile_default"}}function Cu(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(!ZE(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(bi.filter(r=>t.has(r)))}}function rw(e){if(typeof e!="string"||!e.trim())return!1;const t=vu(e.trim(),WE);return t!==void 0&&t>=0}function oc(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function nw(e){return e==="explicit"||e==="legacy_mobile_default"}function iw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const ow=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 sw(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:aw(i.pathname),sanitizedPathnameHash:cw(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function aw(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function cw(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 M=0;M<16;M+=1)o[M]=s.getUint32(a+M*4,!1);for(let M=16;M<64;M+=1){const w=o[M-15],T=o[M-2],_=je(w,7)^je(w,18)^w>>>3,P=je(T,17)^je(T,19)^T>>>10;o[M]=o[M-16]+_+o[M-7]+P>>>0}let[c,d,u,f,l,m,h,p]=i;for(let M=0;M<64;M+=1){const w=p+(je(l,6)^je(l,11)^je(l,25))+(l&m^~l&h)+ow[M]+o[M]>>>0,T=(je(c,2)^je(c,13)^je(c,22))+(c&d^c&u^d&u);p=h,h=m,m=l,l=f+w>>>0,f=u,u=d,d=c,c=w+T>>>0}[c,d,u,f,l,m,h,p].forEach((M,w)=>{i[w]=i[w]+M>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function je(e,t){return e>>>t|e<<32-t}const dw=1e4,uw=1e4,Zi=2e3,lw=2,fw="open-with-native-credential-policy",Ru="安全提示",Pu="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class hw{nonce=tc();runtimeId=tc();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=Nd(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??dw,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics,r=this.capabilityGraph?.gameSaveDiagnostics;return{...t?{storage:t}:{},...r?{gameSaves:r}:{}}}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:(Mw(),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=sf(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=YE(t.sdkVersionPolicy);const n=uE(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=ew({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw Sw(this.platformGateDecision);if(this.miniProgramDetail=_w(t),this.effectiveCapabilities=Md(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),yw(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(ww(i)),this.launchUrl=i,this.miniProgramSrc=SE(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=ls(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:wt,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,$e(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[wt])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=rE({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||(vu(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):EE(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=Jy({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}:{}};$e(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new ff({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 pw(t)?t:ku(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 DE(t,r,{allowPrivateNetwork:ec(r)||sc(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??Aw)({message:Pu,title:Ru,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(nc(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!ec(r)&&!sc(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{ac(),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(()=>ac())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",IE),this.iframe.setAttribute("referrerpolicy",AE),this.iframe.setAttribute("sandbox",Ou)}removeIframeListeners(){this.iframe.removeEventListener("error",this.iframeErrorListener),this.iframe.removeEventListener("load",this.iframeLoadListener)}installSubscriptions(){if(this.options.lifecycle&&!this.lifecycleDisposer){const t=this.options.lifecycle.subscribe({show:this.show.bind(this),hide:this.hide.bind(this)});this.lifecycleDisposer=typeof t=="function"?t:null}}clearLifecycleDisposer(){const t=[this.lifecycleDisposer];this.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(),$e(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(),$e(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{qE(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>=lw)){this.failRuntime(ee("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Yr,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},Zi),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Yr})}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(Yr,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Yr})}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?uw:Zi))}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()},Zi))}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===xl){this.handleCspViolation(t.payload);return}if(t.method!==kl)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"||!_E(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=BE(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){$e(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=sw(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:wE,launchUrlType:nc(t),networkPolicy:fw})}failRuntime(t){const r=mw(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),$e(this.options.onError,gw(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,$e(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){$e(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 mw(e){const t=ls(e);return di(e)&&"cause"in e&&ku(t,e.cause),t}function ku(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function gw(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function pw(e){return di(e)&&typeof e.code=="string"&&typeof e.message=="string"}function di(e){return!!e&&typeof e=="object"}function $e(e,t){try{e?.(t)}catch{}}function yw(e,t,r){try{e?.(t,r)}catch{}}function sc(e){try{const t=new URL(e);return t.protocol==="http:"&&aE(t.hostname)}catch{return!1}}function Ew(e){try{return new URL(e).origin}catch{return}}function ww(e){return ME()?"*":Ew(e)}function Iw(e){return`${Ru}
2
+
3
+ ${Pu}
4
+
5
+ URL: ${e}`}function Aw(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(Iw(e.url))}function ac(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function Mw(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,r=typeof window>"u"?void 0:window,n=Object.freeze({protocolVersion:sd,knownMethodCount:nt.length,supportsFileCreate:nt.some(i=>i.method===_r),system:Nw(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:xt(e?.hardwareConcurrency),maxTouchPoints:xt(e?.maxTouchPoints),screen:{width:xt(t?.width),height:xt(t?.height)},viewport:{width:xt(r?.innerWidth),height:xt(r?.innerHeight),devicePixelRatio:Dw(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function Nw(e="",t=""){const r=`${t} ${e}`.toLowerCase();return/iphone|ipad|ipod/.test(r)?"ios":r.includes("android")?"android":/win32|win64|windows/.test(r)?"windows":/darwin|macintosh|macintel|mac os/.test(r)?"macos":/linux|x11/.test(r)?"linux":"unknown"}function xt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function Dw(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function Sw(e){return ee(KE,Lu,{reason:e.reason,...e.platform===void 0?{}:{platform:e.platform},...e.invalidReason===void 0?{}:{invalidReason:e.invalidReason},...e.effectivePlatforms===void 0?{}:{effectivePlatforms:e.effectivePlatforms}})}function _w(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(!t)return;const r=e.canonicalIdentity?.miniProgramVersion?.trim(),n=e.miniProgramPresentation?.name?.trim(),i=e.miniProgramPresentation?.avatarUrl?.trim(),o=e.miniProgramPresentation?.author?.trim();return Object.freeze({miniProgramId:t,...r?{version:r}:{},...n?{name:n}:{},...i?{iconUrl:i}:{},...o?{author:o}:{},...e.sdkVersionPolicy.releaseChannel===void 0?{}:{releaseChannel:e.sdkVersionPolicy.releaseChannel}})}function Tw(e){if(!di(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!di(e.environment)||typeof e.environment.getCurrentHref!="function"||typeof e.environment.isDevRuntime!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 environment");if(typeof e.resolveLaunchConfiguration!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 resolveLaunchConfiguration");return new hw(e)}function bw(e={}){return async(t,r,n)=>{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");const i=e.indexedDB??globalThis.indexedDB,o=e.crypto??globalThis.crypto;if(!i||!o?.getRandomValues)throw new Error("Host 缺少持久化账号标识能力");const s=await new Promise((a,c)=>{const d=i.open("heybox-mini-program-private-account-v1",1);let u=!1;const f=()=>n.signal.removeEventListener("abort",m),l=h=>{u||(u=!0,f(),c(h))},m=()=>l(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{u?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>l(d.error),d.onblocked=()=>l(new Error("账号存储被阻塞")),d.onsuccess=()=>{u?d.result.close():(u=!0,f(),a(d.result))},n.signal.addEventListener("abort",m,{once:!0}),n.signal.aborted&&m()});try{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");return await new Promise((a,c)=>{const d=s.transaction("accounts","readwrite"),u=d.objectStore("accounts"),f=JSON.stringify([t,r]);let l;const m=()=>{try{d.abort()}catch{}h(),c(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",m,{once:!0});const h=()=>n.signal.removeEventListener("abort",m);d.oncomplete=()=>{h(),a(l)},d.onabort=d.onerror=()=>{h(),c(d.error??new Error("账号存储事务失败"))};const p=u.get(f);p.onsuccess=()=>{try{if(typeof p.result=="string"&&/^ak_[0-9a-f]{64}$/.test(p.result))l=p.result;else{const M=o.getRandomValues(new Uint8Array(32));l=`ak_${Array.from(M,w=>w.toString(16).padStart(2,"0")).join("")}`,u.put(l,f)}}catch{d.abort()}}})}finally{s.close()}}}const Ow=/^(?:authentication-info|authorization|cookie|cookie2|proxy-authenticate|proxy-authentication-info|proxy-authorization|set-cookie|set-cookie2|www-authenticate|pkey|x-pkey|x-access-token|x-auth-token)$/i,vw=new Set(["origin","referer","user-agent"]);function Lw(e,t){return Nf({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=Cw(r),a=await e.authenticatedRequest(s,o);return kw(a)})}).network}function Cw(e){const t=Rw(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function Rw(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!Pw(t)))}function Pw(e){const t=e.trim().toLowerCase();return vw.has(t)}function kw(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:xw(e.headers)??{}}}function xw(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!Uw(t)))}function Uw(e){const t=e.trim().toLowerCase();return Ow.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function jw(e,t,r){const n=Bw(e.presentation,t);return{account:Fw(e,t,r),network:Lw(e,t),...e.storage===void 0?{}:{storage:Vw(e,t)},...e.storage===void 0?{}:zw(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function zw(e,t){const r=e.storage;return typeof r.storage.key!="function"||typeof r.storage.length!="number"?{}:{storageDiagnostics:{listRaw:n=>t.run(n.signal,()=>{const i=[];for(let o=0;o<r.storage.length;o+=1){const s=r.storage.key(o);if(s===null)continue;const a=r.storage.getItem(s);a!==null&&i.push({area:r.area,key:s,value:a})}return i})}}}function Hw(e,t){return{getCurrentHref:()=>(t.assertActive(),e.environment.getCurrentHref()),isDevRuntime:()=>t.run(void 0,()=>e.environment.isDevRuntime()),...e.environment.setDocumentTitle===void 0?{}:{setDocumentTitle:r=>{t.assertActive(),e.environment.setDocumentTitle?.(r)}}}}function Fw(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??bw();return{getAccountKey:(i,o,s)=>t.run(s.signal,a=>n(i,o,{...s,signal:a})),getCurrentUserId:i=>t.run(i.signal,o=>e.account.getCurrentUserId({signal:o})),ensureAuthenticated:i=>t.run(i.signal,o=>e.account.ensureAuthenticated({trustedUserGesture:i.trustedUserGesture,reason:i.reason,signal:o})),onChange:i=>{t.assertActive();const o=e.account.onChange(s=>{t.signal.aborted||i(s)});return r(o)}}}function Vw(e,t){const r=e.storage.storage;return{getRaw:(n,i)=>t.run(i.signal,()=>{const o=r.getItem(n);return o===null?void 0:o}),setRaw:(n,i,o)=>t.run(o.signal,()=>{r.setItem(n,i)})}}function Bw(e,t){if(!e)return;const r={};return e.close&&(r.close=n=>t.run(n.signal,i=>e.close({signal:i}))),e.reload&&(r.reload=n=>t.run(n.signal,i=>e.reload({signal:i}))),e.openAppPage&&(r.openAppPage=(n,i)=>t.run(i.signal,o=>e.openAppPage(n,{signal:o}))),e.openWindow&&(r.openWindow=(n,i)=>t.run(i.signal,o=>e.openWindow(n,{signal:o}))),e.applyOrientation&&(r.applyOrientation=(n,i)=>t.run(i.signal,o=>e.applyOrientation(n,{...i,signal:o}))),e.onViewportChange&&(r.onViewportChange=n=>{t.assertActive();const i=e.onViewportChange(()=>{t.signal.aborted||n()});let o=!1;const s=()=>{o||(o=!0,t.signal.removeEventListener("abort",s),i())};return t.signal.addEventListener("abort",s,{once:!0}),s}),e.getViewportMetrics&&(r.getViewportMetrics=()=>(t.assertActive(),e.getViewportMetrics())),e.getNavigationBarHeight&&(r.getNavigationBarHeight=()=>(t.assertActive(),e.getNavigationBarHeight())),e.setNavigationBarStyle&&(r.setNavigationBarStyle=(n,i)=>t.run(i.signal,o=>e.setNavigationBarStyle(n,{signal:o}))),e.showShareMenu&&(r.showShareMenu=(n,i)=>t.run(i.signal,o=>e.showShareMenu(n,{signal:o}))),e.setScreenshotChromeHidden&&(r.setScreenshotChromeHidden=(n,i)=>gf(i)?e.setScreenshotChromeHidden(n,i):t.run(i.signal,o=>e.setScreenshotChromeHidden(n,{signal:o}))),e.captureAndShare&&(r.captureAndShare=(n,i)=>t.run(i.signal,o=>e.captureAndShare(n,{signal:o}))),e.showToast&&(r.showToast=(n,i)=>t.run(i.signal,o=>e.showToast(n,{signal:o}))),e.showLoading&&(r.showLoading=(n,i)=>t.run(i.signal,o=>e.showLoading(n,{signal:o}))),e.hideLoading&&(r.hideLoading=n=>t.run(n.signal,i=>e.hideLoading({signal:i}))),e.vibrate&&(r.vibrate=(n,i)=>t.run(i.signal,o=>e.vibrate(n,{signal:o}))),e.setClipboard&&(r.setClipboard=(n,i)=>t.run(i.signal,o=>e.setClipboard(n,{signal:o}))),Object.keys(r).length===0?void 0:r}function Gw(){const e=new AbortController;return{signal:e.signal,abort:t=>{e.signal.aborted||e.abort(t)},assertActive:t=>{const r=[e.signal,t].find(n=>n?.aborted);if(r)throw rn(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(u=>u.aborted);if(i)throw rn(i.reason);const o=new AbortController;let s;const a=new Promise((u,f)=>{s=f}),c=n.map(u=>{const f=()=>{o.signal.aborted||o.abort(u.reason),s(rn(u.reason))};return u.addEventListener("abort",f,{once:!0}),{listener:f,source:u}});let d;try{d=Promise.resolve(r(o.signal))}catch(u){d=Promise.reject(u)}try{const u=await Promise.race([d,a]),f=n.find(l=>l.aborted);if(f)throw rn(f.reason);return u}finally{for(const{listener:u,source:f}of c)f.removeEventListener("abort",u)}}}}function rn(e){return new DOMException("Web Host operation aborted","AbortError")}async function Qw(e){const t=Gw(),r=new Set;let n=!1;const i=l=>{if(n||t.signal.aborted)return Ji(l),()=>{};let m=!0;const h=()=>{m&&(m=!1,r.delete(h),Ji(l))};return r.add(h),h},o=()=>s(e.signal.reason),s=l=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(l);for(const m of[...r])m();e.onDispose&&Ji(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=jw(e,t,i);a.storage?.getRaw&&a.storage.setRaw&&(a.scopedStorage=yu({storage:a.storage,diagnostics:a.storageDiagnostics,coordinationKey:e.storage.storage,lock:cy,resolveScope:async()=>pu((await f()).configuration)}));const c=Nd(a,{hostCapabilities:e.hostCapabilities}),d=Hw(e,t);let u;const f=()=>u??=t.run(void 0,l=>e.resolveLaunch(l));return{platform:"web",ports:a,environment:d,resolveLaunch:f,...e.authPresentation===void 0?{}:{authPresentation:Yw(e.authPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function Ji(e){try{e()}catch{}}function Yw(e,t){return{...e.confirmFollowAuthor?{confirmFollowAuthor:r=>t.run(r.signal,n=>e.confirmFollowAuthor({...r,signal:n}))}:{},confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var Ut={},Xi,cc;function qw(){return cc||(cc=1,Xi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Xi}var eo={},Ke={},dc;function St(){if(dc)return Ke;dc=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ke.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},Ke.getSymbolTotalCodewords=function(n){return t[n]},Ke.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Ke.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Ke.isKanjiModeEnabled=function(){return typeof e<"u"},Ke.toSJIS=function(n){return e(n)},Ke}var to={},uc;function Ts(){return uc||(uc=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,i){if(e.isValid(n))return n;try{return t(n)}catch{return i}}})(to)),to}var ro,lc;function Ww(){if(lc)return ro;lc=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},ro=e,ro}var no,fc;function $w(){if(fc)return no;fc=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,i){const o=t*this.size+r;this.data[o]=n,i&&(this.reservedBit[o]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},no=e,no}var io={},hc;function Kw(){return hc||(hc=1,(function(e){const t=St().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const i=Math.floor(n/7)+2,o=t(n),s=o===145?26:Math.ceil((o-13)/(2*i-2))*2,a=[o-7];for(let c=1;c<i-1;c++)a[c]=a[c-1]-s;return a.push(6),a.reverse()},e.getPositions=function(n){const i=[],o=e.getRowColCoords(n),s=o.length;for(let a=0;a<s;a++)for(let c=0;c<s;c++)a===0&&c===0||a===0&&c===s-1||a===s-1&&c===0||i.push([o[a],o[c]]);return i}})(io)),io}var oo={},mc;function Zw(){if(mc)return oo;mc=1;const e=St().getSymbolSize,t=7;return oo.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},oo}var so={},gc;function Jw(){return gc||(gc=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,d=null,u=null;for(let f=0;f<o;f++){a=c=0,d=u=null;for(let l=0;l<o;l++){let m=i.get(f,l);m===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=m,a=1),m=i.get(l,f),m===u?c++:(c>=5&&(s+=t.N1+(c-5)),u=m,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const d=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(d===4||d===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let d=0;d<o;d++){a=c=0;for(let u=0;u<o;u++)a=a<<1&2047|i.get(d,u),u>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(u,d),u>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let d=0;d<s;d++){o(d),e.applyMask(d,i);const u=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(d,i),u<c&&(c=u,a=d)}return a}})(so)),so}var nn={},pc;function xu(){if(pc)return nn;pc=1;const e=Ts(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return nn.getBlocksCount=function(i,o){switch(o){case e.L:return t[(i-1)*4+0];case e.M:return t[(i-1)*4+1];case e.Q:return t[(i-1)*4+2];case e.H:return t[(i-1)*4+3];default:return}},nn.getTotalCodewordsCount=function(i,o){switch(o){case e.L:return r[(i-1)*4+0];case e.M:return r[(i-1)*4+1];case e.Q:return r[(i-1)*4+2];case e.H:return r[(i-1)*4+3];default:return}},nn}var ao={},fr={},yc;function Xw(){if(yc)return fr;yc=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let i=0;i<255;i++)e[i]=n,t[n]=i,n<<=1,n&256&&(n^=285);for(let i=255;i<512;i++)e[i]=e[i-255]})(),fr.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},fr.exp=function(n){return e[n]},fr.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},fr}var Ec;function eI(){return Ec||(Ec=1,(function(e){const t=Xw();e.mul=function(n,i){const o=new Uint8Array(n.length+i.length-1);for(let s=0;s<n.length;s++)for(let a=0;a<i.length;a++)o[s+a]^=t.mul(n[s],i[a]);return o},e.mod=function(n,i){let o=new Uint8Array(n);for(;o.length-i.length>=0;){const s=o[0];for(let c=0;c<i.length;c++)o[c]^=t.mul(i[c],s);let a=0;for(;a<o.length&&o[a]===0;)a++;o=o.slice(a)}return o},e.generateECPolynomial=function(n){let i=new Uint8Array([1]);for(let o=0;o<n;o++)i=e.mul(i,new Uint8Array([1,t.exp(o)]));return i}})(ao)),ao}var co,wc;function tI(){if(wc)return co;wc=1;const e=eI();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(n.length+this.degree);i.set(n);const o=e.mod(i,this.genPoly),s=this.degree-o.length;if(s>0){const a=new Uint8Array(this.degree);return a.set(o,s),a}return o},co=t,co}var uo={},lo={},fo={},Ic;function Uu(){return Ic||(Ic=1,fo.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),fo}var ze={},Ac;function ju(){if(Ac)return ze;Ac=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
6
+ ]))+`;ze.KANJI=new RegExp(r,"g"),ze.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),ze.BYTE=new RegExp(n,"g"),ze.NUMERIC=new RegExp(e,"g"),ze.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return ze.testKanji=function(c){return i.test(c)},ze.testNumeric=function(c){return o.test(c)},ze.testAlphanumeric=function(c){return s.test(c)},ze}var Mc;function _t(){return Mc||(Mc=1,(function(e){const t=Uu(),r=ju();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(o,s){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!t.isValid(s))throw new Error("Invalid version: "+s);return s>=1&&s<10?o.ccBits[0]:s<27?o.ccBits[1]:o.ccBits[2]},e.getBestModeForData=function(o){return r.testNumeric(o)?e.NUMERIC:r.testAlphanumeric(o)?e.ALPHANUMERIC:r.testKanji(o)?e.KANJI:e.BYTE},e.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},e.isValid=function(o){return o&&o.bit&&o.ccBits};function n(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+i)}}e.from=function(o,s){if(e.isValid(o))return o;try{return n(o)}catch{return s}}})(lo)),lo}var Nc;function rI(){return Nc||(Nc=1,(function(e){const t=St(),r=xu(),n=Ts(),i=_t(),o=Uu(),s=7973,a=t.getBCHDigit(s);function c(l,m,h){for(let p=1;p<=40;p++)if(m<=e.getCapacity(p,h,l))return p}function d(l,m){return i.getCharCountIndicator(l,m)+4}function u(l,m){let h=0;return l.forEach(function(p){const M=d(p.mode,m);h+=M+p.getBitsLength()}),h}function f(l,m){for(let h=1;h<=40;h++)if(u(l,h)<=e.getCapacity(h,m,i.MIXED))return h}e.from=function(m,h){return o.isValid(m)?parseInt(m,10):h},e.getCapacity=function(m,h,p){if(!o.isValid(m))throw new Error("Invalid QR Code version");typeof p>"u"&&(p=i.BYTE);const M=t.getSymbolTotalCodewords(m),w=r.getTotalCodewordsCount(m,h),T=(M-w)*8;if(p===i.MIXED)return T;const _=T-d(p,m);switch(p){case i.NUMERIC:return Math.floor(_/10*3);case i.ALPHANUMERIC:return Math.floor(_/11*2);case i.KANJI:return Math.floor(_/13);case i.BYTE:default:return Math.floor(_/8)}},e.getBestVersionForData=function(m,h){let p;const M=n.from(h,n.M);if(Array.isArray(m)){if(m.length>1)return f(m,M);if(m.length===0)return 1;p=m[0]}else p=m;return c(p.mode,p.getLength(),M)},e.getEncodedBits=function(m){if(!o.isValid(m)||m<7)throw new Error("Invalid QR Code version");let h=m<<12;for(;t.getBCHDigit(h)-a>=0;)h^=s<<t.getBCHDigit(h)-a;return m<<12|h}})(uo)),uo}var ho={},Dc;function nI(){if(Dc)return ho;Dc=1;const e=St(),t=1335,r=21522,n=e.getBCHDigit(t);return ho.getEncodedBits=function(o,s){const a=o.bit<<3|s;let c=a<<10;for(;e.getBCHDigit(c)-n>=0;)c^=t<<e.getBCHDigit(c)-n;return(a<<10|c)^r},ho}var mo={},go,Sc;function iI(){if(Sc)return go;Sc=1;const e=_t();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let i,o,s;for(i=0;i+3<=this.data.length;i+=3)o=this.data.substr(i,3),s=parseInt(o,10),n.put(s,10);const a=this.data.length-i;a>0&&(o=this.data.substr(i),s=parseInt(o,10),n.put(s,a*3+1))},go=t,go}var po,_c;function oI(){if(_c)return po;_c=1;const e=_t(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(i){let o;for(o=0;o+2<=this.data.length;o+=2){let s=t.indexOf(this.data[o])*45;s+=t.indexOf(this.data[o+1]),i.put(s,11)}this.data.length%2&&i.put(t.indexOf(this.data[o]),6)},po=r,po}var yo,Tc;function sI(){if(Tc)return yo;Tc=1;const e=_t();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,i=this.data.length;n<i;n++)r.put(this.data[n],8)},yo=t,yo}var Eo,bc;function aI(){if(bc)return Eo;bc=1;const e=_t(),t=St();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(i){return i*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let i;for(i=0;i<this.data.length;i++){let o=t.toSJIS(this.data[i]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+`
7
+ Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},Eo=r,Eo}var wo={exports:{}},Oc;function cI(){return Oc||(Oc=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,d,u,f,l,m,h,p,M;!a.empty();){c=a.pop(),d=c.value,f=c.cost,l=r[d]||{};for(u in l)l.hasOwnProperty(u)&&(m=l[u],h=f+m,p=s[u],M=typeof s[u]>"u",(M||p>h)&&(s[u]=h,a.push(u,h),o[u]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var w=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(w)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var i=[],o=n;o;)i.push(o),r[o],o=r[o];return i.reverse(),i},find_path:function(r,n,i){var o=t.single_source_shortest_paths(r,n,i);return t.extract_shortest_path_from_predecessor_list(o,i)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,i={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);return i.queue=[],i.sorter=r.sorter||n.default_sorter,i},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var i={value:r,cost:n};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(wo)),wo.exports}var vc;function dI(){return vc||(vc=1,(function(e){const t=_t(),r=iI(),n=oI(),i=sI(),o=aI(),s=ju(),a=St(),c=cI();function d(w){return unescape(encodeURIComponent(w)).length}function u(w,T,_){const P=[];let F;for(;(F=w.exec(_))!==null;)P.push({data:F[0],index:F.index,mode:T,length:F[0].length});return P}function f(w){const T=u(s.NUMERIC,t.NUMERIC,w),_=u(s.ALPHANUMERIC,t.ALPHANUMERIC,w);let P,F;return a.isKanjiModeEnabled()?(P=u(s.BYTE,t.BYTE,w),F=u(s.KANJI,t.KANJI,w)):(P=u(s.BYTE_KANJI,t.BYTE,w),F=[]),T.concat(_,P,F).sort(function(O,E){return O.index-E.index}).map(function(O){return{data:O.data,mode:O.mode,length:O.length}})}function l(w,T){switch(T){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return o.getBitsLength(w);case t.BYTE:return i.getBitsLength(w)}}function m(w){return w.reduce(function(T,_){const P=T.length-1>=0?T[T.length-1]:null;return P&&P.mode===_.mode?(T[T.length-1].data+=_.data,T):(T.push(_),T)},[])}function h(w){const T=[];for(let _=0;_<w.length;_++){const P=w[_];switch(P.mode){case t.NUMERIC:T.push([P,{data:P.data,mode:t.ALPHANUMERIC,length:P.length},{data:P.data,mode:t.BYTE,length:P.length}]);break;case t.ALPHANUMERIC:T.push([P,{data:P.data,mode:t.BYTE,length:P.length}]);break;case t.KANJI:T.push([P,{data:P.data,mode:t.BYTE,length:d(P.data)}]);break;case t.BYTE:T.push([{data:P.data,mode:t.BYTE,length:d(P.data)}])}}return T}function p(w,T){const _={},P={start:{}};let F=["start"];for(let U=0;U<w.length;U++){const O=w[U],E=[];for(let S=0;S<O.length;S++){const v=O[S],C=""+U+S;E.push(C),_[C]={node:v,lastCount:0},P[C]={};for(let y=0;y<F.length;y++){const N=F[y];_[N]&&_[N].node.mode===v.mode?(P[N][C]=l(_[N].lastCount+v.length,v.mode)-l(_[N].lastCount,v.mode),_[N].lastCount+=v.length):(_[N]&&(_[N].lastCount=v.length),P[N][C]=l(v.length,v.mode)+4+t.getCharCountIndicator(v.mode,T))}}F=E}for(let U=0;U<F.length;U++)P[F[U]].end=0;return{map:P,table:_}}function M(w,T){let _;const P=t.getBestModeForData(w);if(_=t.from(T,P),_!==t.BYTE&&_.bit<P.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(_)+`.
8
+ Suggested mode is: `+t.toString(P));switch(_===t.KANJI&&!a.isKanjiModeEnabled()&&(_=t.BYTE),_){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new o(w);case t.BYTE:return new i(w)}}e.fromArray=function(T){return T.reduce(function(_,P){return typeof P=="string"?_.push(M(P,null)):P.data&&_.push(M(P.data,P.mode)),_},[])},e.fromString=function(T,_){const P=f(T,a.isKanjiModeEnabled()),F=h(P),U=p(F,_),O=c.find_path(U.map,"start","end"),E=[];for(let S=1;S<O.length-1;S++)E.push(U.table[O[S]].node);return e.fromArray(m(E))},e.rawSplit=function(T){return e.fromArray(f(T,a.isKanjiModeEnabled()))}})(mo)),mo}var Lc;function uI(){if(Lc)return eo;Lc=1;const e=St(),t=Ts(),r=Ww(),n=$w(),i=Kw(),o=Zw(),s=Jw(),a=xu(),c=tI(),d=rI(),u=nI(),f=_t(),l=dI();function m(U,O){const E=U.size,S=o.getPositions(O);for(let v=0;v<S.length;v++){const C=S[v][0],y=S[v][1];for(let N=-1;N<=7;N++)if(!(C+N<=-1||E<=C+N))for(let D=-1;D<=7;D++)y+D<=-1||E<=y+D||(N>=0&&N<=6&&(D===0||D===6)||D>=0&&D<=6&&(N===0||N===6)||N>=2&&N<=4&&D>=2&&D<=4?U.set(C+N,y+D,!0,!0):U.set(C+N,y+D,!1,!0))}}function h(U){const O=U.size;for(let E=8;E<O-8;E++){const S=E%2===0;U.set(E,6,S,!0),U.set(6,E,S,!0)}}function p(U,O){const E=i.getPositions(O);for(let S=0;S<E.length;S++){const v=E[S][0],C=E[S][1];for(let y=-2;y<=2;y++)for(let N=-2;N<=2;N++)y===-2||y===2||N===-2||N===2||y===0&&N===0?U.set(v+y,C+N,!0,!0):U.set(v+y,C+N,!1,!0)}}function M(U,O){const E=U.size,S=d.getEncodedBits(O);let v,C,y;for(let N=0;N<18;N++)v=Math.floor(N/3),C=N%3+E-8-3,y=(S>>N&1)===1,U.set(v,C,y,!0),U.set(C,v,y,!0)}function w(U,O,E){const S=U.size,v=u.getEncodedBits(O,E);let C,y;for(C=0;C<15;C++)y=(v>>C&1)===1,C<6?U.set(C,8,y,!0):C<8?U.set(C+1,8,y,!0):U.set(S-15+C,8,y,!0),C<8?U.set(8,S-C-1,y,!0):C<9?U.set(8,15-C-1+1,y,!0):U.set(8,15-C-1,y,!0);U.set(S-8,8,1,!0)}function T(U,O){const E=U.size;let S=-1,v=E-1,C=7,y=0;for(let N=E-1;N>0;N-=2)for(N===6&&N--;;){for(let D=0;D<2;D++)if(!U.isReserved(v,N-D)){let R=!1;y<O.length&&(R=(O[y]>>>C&1)===1),U.set(v,N-D,R),C--,C===-1&&(y++,C=7)}if(v+=S,v<0||E<=v){v-=S,S=-S;break}}}function _(U,O,E){const S=new r;E.forEach(function(D){S.put(D.mode.bit,4),S.put(D.getLength(),f.getCharCountIndicator(D.mode,U)),D.write(S)});const v=e.getSymbolTotalCodewords(U),C=a.getTotalCodewordsCount(U,O),y=(v-C)*8;for(S.getLengthInBits()+4<=y&&S.put(0,4);S.getLengthInBits()%8!==0;)S.putBit(0);const N=(y-S.getLengthInBits())/8;for(let D=0;D<N;D++)S.put(D%2?17:236,8);return P(S,U,O)}function P(U,O,E){const S=e.getSymbolTotalCodewords(O),v=a.getTotalCodewordsCount(O,E),C=S-v,y=a.getBlocksCount(O,E),N=S%y,D=y-N,R=Math.floor(S/y),b=Math.floor(C/y),A=b+1,I=R-b,L=new c(I);let k=0;const x=new Array(y),z=new Array(y);let H=0;const V=new Uint8Array(U.buffer);for(let Y=0;Y<y;Y++){const ne=Y<D?b:A;x[Y]=V.slice(k,k+ne),z[Y]=L.encode(x[Y]),k+=ne,H=Math.max(H,ne)}const G=new Uint8Array(S);let J=0,K,Z;for(K=0;K<H;K++)for(Z=0;Z<y;Z++)K<x[Z].length&&(G[J++]=x[Z][K]);for(K=0;K<I;K++)for(Z=0;Z<y;Z++)G[J++]=z[Z][K];return G}function F(U,O,E,S){let v;if(Array.isArray(U))v=l.fromArray(U);else if(typeof U=="string"){let R=O;if(!R){const b=l.rawSplit(U);R=d.getBestVersionForData(b,E)}v=l.fromString(U,R||40)}else throw new Error("Invalid data");const C=d.getBestVersionForData(v,E);if(!C)throw new Error("The amount of data is too big to be stored in a QR Code");if(!O)O=C;else if(O<C)throw new Error(`
9
+ The chosen QR Code version cannot contain this amount of data.
10
+ Minimum version required to store current data is: `+C+`.
11
+ `);const y=_(O,E,v),N=e.getSymbolSize(O),D=new n(N);return m(D,O),h(D),p(D,O),w(D,E,0),O>=7&&M(D,O),T(D,y),isNaN(S)&&(S=s.getBestMask(D,w.bind(null,D,E))),s.applyMask(S,D),w(D,E,S),{modules:D,version:O,errorCorrectionLevel:E,maskPattern:S,segments:v}}return eo.create=function(O,E){if(typeof O>"u"||O==="")throw new Error("No input text");let S=t.M,v,C;return typeof E<"u"&&(S=t.from(E.errorCorrectionLevel,t.M),v=d.from(E.version),C=s.from(E.maskPattern),E.toSJISFunc&&e.setToSJISFunction(E.toSJISFunc)),F(O,v,S,C)},eo}var Io={},Ao={},Cc;function zu(){return Cc||(Cc=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),d=Math.floor((s+o.margin*2)*c),u=o.margin*c,f=[o.color.light,o.color.dark];for(let l=0;l<d;l++)for(let m=0;m<d;m++){let h=(l*d+m)*4,p=o.color.light;if(l>=u&&m>=u&&l<d-u&&m<d-u){const M=Math.floor((l-u)/c),w=Math.floor((m-u)/c);p=f[a[M*s+w]?1:0]}n[h++]=p.r,n[h++]=p.g,n[h++]=p.b,n[h]=p.a}}})(Ao)),Ao}var Rc;function lI(){return Rc||(Rc=1,(function(e){const t=zu();function r(i,o,s){i.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=s,o.width=s,o.style.height=s+"px",o.style.width=s+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(o,s,a){let c=a,d=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(d=n()),c=t.getOptions(c);const u=t.getImageWidth(o.modules.size,c),f=d.getContext("2d"),l=f.createImageData(u,u);return t.qrToImageData(l.data,o,c),r(f,d,u),f.putImageData(l,0,0),d},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const d=e.render(o,s,c),u=c.type||"image/png",f=c.rendererOpts||{};return d.toDataURL(u,f.quality)}})(Io)),Io}var Mo={},Pc;function fI(){if(Pc)return Mo;Pc=1;const e=zu();function t(i,o){const s=i.a/255,a=o+'="'+i.hex+'"';return s<1?a+" "+o+'-opacity="'+s.toFixed(2).slice(1)+'"':a}function r(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function n(i,o,s){let a="",c=0,d=!1,u=0;for(let f=0;f<i.length;f++){const l=Math.floor(f%o),m=Math.floor(f/o);!l&&!d&&(d=!0),i[f]?(u++,f>0&&l>0&&i[f-1]||(a+=d?r("M",l+s,.5+m+s):r("m",c,0),c=0,d=!1),l+1<o&&i[f+1]||(a+=r("h",u),u=0)):c++}return a}return Mo.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,u=o.modules.data,f=d+c.margin*2,l=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",m="<path "+t(c.color.dark,"stroke")+' d="'+n(u,d,c.margin)+'"/>',h='viewBox="0 0 '+f+" "+f+'"',M='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+h+' shape-rendering="crispEdges">'+l+m+`</svg>
12
+ `;return typeof a=="function"&&a(null,M),M},Mo}var kc;function hI(){if(kc)return Ut;kc=1;const e=qw(),t=uI(),r=lI(),n=fI();function i(o,s,a,c,d){const u=[].slice.call(arguments,1),f=u.length,l=typeof u[f-1]=="function";if(!l&&!e())throw new Error("Callback required as last argument");if(l){if(f<2)throw new Error("Too few arguments provided");f===2?(d=a,a=s,s=c=void 0):f===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=s,s=c=void 0):f===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(m,h){try{const p=t.create(a,c);m(o(p,s,c))}catch(p){h(p)}})}try{const m=t.create(a,c);d(null,o(m,s,c))}catch(m){d(m)}}return Ut.create=t.create,Ut.toCanvas=i.bind(null,r.render),Ut.toDataURL=i.bind(null,r.renderToDataURL),Ut.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),Ut}var mI=hI();function gI(e){const t=`hb-game-saves-${crypto.randomUUID()}`,r=c=>`hb-sdk:game-save-cache:${c}`;let n,i;const o=new Promise((c,d)=>{n=c,i=d});let s;const a=new Promise(c=>{s=c});return e.signal.addEventListener("abort",s,{once:!0}),e.signal.aborted&&s(),e.locks.request(r(t),async()=>{let c;try{c=await e.getRoot();const d=await e.locks.request("hb-sdk:game-save-cache:gc",async()=>{e.signal.throwIfAborted();for await(const[u,f]of c)f.kind!=="directory"||!/^hb-game-saves-[a-f0-9-]{36}$/.test(u)||await e.locks.request(r(u),{ifAvailable:!0},async l=>{l&&await xc(c,u)});return e.signal.throwIfAborted(),c.getDirectoryHandle(t,{create:!0})});e.signal.throwIfAborted(),n(d),await a}catch(d){i(d)}finally{e.signal.removeEventListener("abort",s),c&&await xc(c,t).catch(()=>{})}}).catch(i),o.catch(()=>{}),o}async function xc(e,t){for(let r=0;;r++)try{await e.removeEntry(t,{recursive:!0});return}catch(n){if(n instanceof DOMException&&n.name==="NotFoundError")return;if(!(n instanceof DOMException)||n.name!=="NoModificationAllowedError"||r>=4)throw n;await new Promise(i=>setTimeout(i,25*(r+1)))}}const No=8*1024*1024,pI=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),yI="/__hb_sdk__/game-save-download",me=(e,t)=>({code:e,message:t});function EI(e){const t=e.getRoot??(navigator.storage?.getDirectory?()=>navigator.storage.getDirectory():void 0),r=e.locks??navigator.locks,n=e.supportsWritable??(typeof FileSystemFileHandle<"u"&&typeof FileSystemFileHandle.prototype.createWritable=="function");if(!t||!r||!n)return;const i=gI({getRoot:t,locks:r,signal:e.signal}),o=new WeakMap,s=new WeakSet,a=h=>{h.signal.throwIfAborted(),h.lifecycle!=="cleanup"&&e.signal.throwIfAborted()},c=()=>i;function d(h){if(!/^\.hb-game-saves\/[a-zA-Z0-9_-]+\.zip$/.test(h))throw me("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存");return h.slice(15)}async function u(h,p){a(p);const M=d(h);try{return await(await c()).getFileHandle(M)}catch(w){throw w instanceof DOMException&&w.name==="NotFoundError"?me("FILE_NOT_FOUND","存档缓存不存在"):w}}function f(h){const p={kind:"file",mode:"readwrite",name:h.split("/").at(-1),async create(M,w){a(w);const T=d(h),_=await c();if(M.exclusive)try{throw await _.getFileHandle(T),me("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(P){if(!(P instanceof DOMException&&P.name==="NotFoundError"))throw P}a(w),await _.getFileHandle(T,{create:!0}),a(w)},async remove(M){a(M);const w=d(h);if(i)try{await(await i).removeEntry(w)}catch(T){if(!(T instanceof DOMException&&T.name==="NotFoundError"))throw T}},async read(M){const w=await(await u(h,M)).getFile();if(w.size>No)throw me("FILE_TOO_LARGE","存档文件超过 8 MiB");const T=new Uint8Array(await w.arrayBuffer());try{return a(M),T}catch(_){throw T.fill(0),_}},async write(){throw me("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(M){const w=await(await u(h,M)).getFile();return a(M),{kind:"file",size:w.size,modifiedAt:w.lastModified}}};return o.set(p,h),p}const l=async()=>{throw me("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},m={kind:"directory",mode:"readwrite",name:"",file:f,directory(h){return{...m,name:h,async create(p,M){if(a(M),h!==".hb-game-saves")return l();await c(),a(M)}}},create:l,stat:l,list:l};return{files:{sandbox:m},transfer:{network:{async open(h,p){if(a(p),!wd(h))throw me("METHOD_FORBIDDEN","仅支持受控存档下载");const M=await(e.fetch??fetch)(yI,{method:"POST",credentials:"same-origin",redirect:"error",headers:{"content-type":"application/json","x-hb-sdk-csrf":e.csrfToken()},body:JSON.stringify(h),signal:AbortSignal.any([p.signal,e.signal,AbortSignal.timeout(6e4)])});if(!M.ok){const w=await M.json().catch(()=>({}));throw me(w.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return s.add(M),{status:M.status,headers:Object.fromEntries(Array.from(M.headers).filter(([w])=>pI.has(w)).map(([w,T])=>[w,[T]])),body:M}},async release(h){s.delete(h),await h.body?.cancel()}},files:{async writeResource(h,p,M,w){let T,_;try{a(w);const P=o.get(h);if(!P||!s.delete(p))throw me("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(M.mode!=="replace-existing")throw me("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(T=await(await u(P,w)).createWritable(),!p.body)throw me("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");_=p.body.getReader();let U=0;for(;;){a(w);const O=await _.read().catch(E=>{throw a(w),me(E instanceof DOMException&&E.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(a(w),O.done)break;if(U+=O.value.byteLength,U>Math.min(M.maxBytes??No,No))throw me("FILE_TOO_LARGE","存档文件超过 8 MiB");await T.write(new Uint8Array(O.value)),w.onProgress(U)}if(M.expectedBytes!==void 0&&U!==M.expectedBytes)throw me("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return a(w),await T.close(),T=void 0,{committedBytes:U}}catch(P){throw P instanceof DOMException&&P.name==="QuotaExceededError"?me("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):P}finally{await _?.cancel().catch(()=>{}),_||await p.body?.cancel().catch(()=>{}),await T?.abort().catch(()=>{}),s.delete(p)}}}}}}function He(e,t){throw{code:e,message:t}}function wI(e){const t=e.now??Date.now;let r;const n=new Map,i=()=>{r=void 0};e.signal.addEventListener("abort",i,{once:!0});function o(){if(e.signal.aborted)throw new DOMException("调试会话已结束","AbortError");const a=e.readState();a.userId||(i(),He("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:c,browser:d}=a,u=nf(c.developmentSnapshot);(c.source!=="remote"||!c.miniProgramId||!c.localDevLaunchToken||!c.expiresAt||c.expiresAt<=t()||!u||!c.developmentSnapshotDigest||!/^[a-f0-9]{64}$/.test(c.developmentSnapshotDigest))&&(i(),He("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态")),(d.source!=="remote"||d.miniProgramId!==c.miniProgramId||d.devSessionId!==u.session_id||d.contextRevision!==u.revision||c.devSessionId!==u.session_id||c.contextRevision!==u.revision)&&(i(),He("AUTHORIZATION_CONTEXT_CHANGED","开发快照正在更新,请稍后重试"));const f={mini_program_id:c.miniProgramId,launch_kind:"remote-dev",version_identity:`dev:${u.session_id}:${u.revision}`,sdk_version:u.sdk_version,local_dev_launch_token:c.localDevLaunchToken,dev_snapshot_digest:c.developmentSnapshotDigest,dev_network_enabled:a.networkEnabled};return{body:f,key:JSON.stringify([a.userId,a.accountRevision,f]),expiresAt:c.expiresAt}}async function s(a,c){const d=c.signal;let u;try{u=await e.request({source:"runtime-private",credentials:"heybox-session",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:"heybox.user_miniprogram.runtime.auth.context.post",path:"/user_miniprogram/runtime/auth/context",channel:"api"},method:"POST",bodyEncoding:"form",data:a.body,timeout:1e4},c)}catch(p){d.throwIfAborted();const M=p&&typeof p=="object"&&"code"in p?String(p.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(M)&&He("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(M)||p instanceof DOMException&&["AbortError","TimeoutError"].includes(p.name))throw p;He("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted(),o().key!==a.key&&He("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const f=u.data;(u.status===401||f?.status==="login"||f?.status==="relogin")&&He("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(u.status!==200||f?.status!=="ok")&&He("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const l=f.result,m=Number(l?.expires_at)*1e3;(typeof l?.token!="string"||!l.token.trim()||!Number.isSafeInteger(l?.expires_at)||!Number.isSafeInteger(m)||m<=t()||!["legacy","local","server"].includes(String(l.user_data_mode)))&&He("INVALID_RESPONSE","开发运行授权响应无效");const h={token:l.token,expiresAt:Math.min(m,a.expiresAt),steamAccount:l.steam_account===!0,userDataMode:l.user_data_mode};return r={key:a.key,value:h},h}return{async get(a){const c=AbortSignal.any([a.signal,e.signal]);c.throwIfAborted(),await e.refreshAccount(c),c.throwIfAborted();const d=o();if(r?.key===d.key&&r.value.expiresAt>t()+3e4)return r.value;i();let u=n.get(d.key);if(!u||u.controller.signal.aborted){const l=new AbortController,m=s(d,{...a,signal:AbortSignal.any([l.signal,e.signal])});u={promise:m,controller:l,users:0},n.set(d.key,u);const h=u;m.finally(()=>{n.get(d.key)===h&&n.delete(d.key)}).catch(()=>{})}u.users++;let f;try{const l=await Promise.race([u.promise,new Promise((m,h)=>{f=()=>h(c.reason),c.addEventListener("abort",f,{once:!0}),c.aborted&&f()})]);return c.throwIfAborted(),o().key!==d.key&&He("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),l}finally{c.removeEventListener("abort",f),--u.users===0&&u.controller.abort()}}}}const II="/__hb_sdk__/dev-context";function Uc(e,t){return xr(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId:void 0,developmentSnapshot:typeof e.developmentSnapshot=="string"?e.developmentSnapshot:void 0,developmentSnapshotDigest:typeof e.developmentSnapshotDigest=="string"?e.developmentSnapshotDigest:void 0,localDevLaunchToken:typeof e.localDevLaunchToken=="string"?e.localDevLaunchToken:void 0,runtimePermissions:e.runtimePermissions,publishedRuntimePermissions:e.publishedRuntimePermissions,warning:typeof e.warning=="string"?e.warning:void 0,declaredPermissions:xr(e.declaredPermissions)?e.declaredPermissions:void 0,platforms:Array.isArray(e.platforms)?e.platforms.filter(r=>["android","ios","ohos","windows","macos","linux"].includes(String(r))):void 0,localDevGrant:e.localDevGrant,contextRevision:typeof e.contextRevision=="number"?e.contextRevision:void 0,devSessionId:typeof e.devSessionId=="string"?e.devSessionId:void 0,expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0,companionManifestSha256:typeof e.companionManifestSha256=="string"?e.companionManifestSha256:void 0}:{source:"anonymous",runtimePermissions:t}}function wr(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=gd(e.localDevGrant);return!r.valid||!e.devSessionId?.trim()||!Number.isSafeInteger(e.contextRevision)||e.contextRevision!==r.grant.revision||!e.expiresAt||!Number.isFinite(e.expiresAt)||e.source!=="remote"&&e.expiresAt<=t?{...e,localDevGrant:void 0,warning:"本地临时授权无效或已过期,已降权"}:{...e,...e.expiresAt<=t?{source:"anonymous",localDevLaunchToken:void 0,expiresAt:t+3e4}:{},localDevGrant:ef({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,revision:r.grant.revision,eligiblePermissionKeys:e.platforms?.some(n=>["windows","macos","linux"].includes(n))?["network","companion","appProtocol"]:["network","appProtocol"]})}}function AI(e){if(!xr(e)||!jc(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!xr(t)||!jc(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const MI={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Oi(e){const t=Re(e.localDevGrant?us({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}).runtimePermissions:e.runtimePermissions),r=t.permissions.network;return t.valid&&r?{networkRequest:{status:r.status,useOfficialDomain:r.config.useOfficialDomain===!0}}:SI()}function NI(e,t,r){return r?.localDevGrant?us({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:Hu(e,t,t.networkRequest.useOfficialDomain)}function DI(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=Oi({...e,localDevGrant:void 0});return Hu(e.runtimePermissions,t,!1)}function SI(){return{networkRequest:{...MI.networkRequest}}}function Hu(e,t,r){const n=Re(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of Mt){const a=n.permissions[s];a&&i.push(s==="network"?{key:s,status:t.networkRequest.status,config:{useOfficialDomain:r}}:{key:s,status:a.status,config:{}})}const o=xr(e)&&typeof e.revision=="number"&&Number.isInteger(e.revision)&&e.revision>=0?e.revision:void 0;return{schema_version:1,...o===void 0?{}:{revision:o},entries:i}}function xr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function jc(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function _I(e){let t,r=!1,n=!1,i;return{invalidate(a){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(a,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=o().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function o(){let a={ok:!0};for(;r&&!n;){r=!1;const c=new AbortController;t=c;let d;try{d=await e.fetch(c.signal)}catch(f){a={ok:!1},!n&&!c.signal.aborted&&s(f);continue}finally{t===c&&(t=void 0)}if(n)return{ok:!1};let u;try{u=e.apply(d)}catch(f){a={ok:!1},n||s(f);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(u))try{await e.onChanged(u)}catch(f){a={ok:!1},n||s(f)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function TI(e){return _I({apply:e.applyStatus,fetch:e.fetchStatus,hasChanged:t=>t.changed,onChanged:t=>e.reconcile(t.status),onError:e.onError,shouldSkip:t=>t!==void 0&&t<=e.getCanonicalRevision()})}function bI(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,o;return{schedule:s,reset(){n=t,a()},dispose(){i||(i=!0,a())}};function s(){i||e.isDisposed()||(a(),o=e.timers.setTimeout(async()=>{o=void 0;let c;try{c=await e.invalidate()}catch{c={ok:!1}}if(!(i||e.isDisposed())){if(c.ok){n=t,e.connectEvents();return}n=Math.min(n*2,r),s()}},n))}function a(){o!==void 0&&e.timers.clearTimeout(o),o=void 0}}const zc="hb-sdk-action-dialog-style";async function vi(e){await Fu(e)}async function OI(e){return await Fu({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,confirmation:!0})?"confirmed":"cancelled"}function Fu(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}PI();const n=document.activeElement,i=document.createElement("div");i.className="hb-sdk-action-dialog",i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-label",e.title),i.innerHTML=`
13
+ <div class="hb-sdk-action-dialog__panel">
14
+ <h2>${Hc(e.title)}</h2>
15
+ <pre class="hb-sdk-action-dialog__detail">${Hc(e.detail)}</pre>
16
+ <div class="hb-sdk-action-dialog__actions">
17
+ ${e.confirmation?'<button type="button" data-action="cancel">取消</button>':""}
18
+ <button type="button" class="primary" data-action="confirm">${e.confirmation?"关注":"确定"}</button>
19
+ </div>
20
+ </div>
21
+ `;const o=()=>{e.signal?.removeEventListener("abort",a),document.removeEventListener("keydown",c),i.remove(),n instanceof HTMLElement&&n.focus()},s=d=>{o(),t(d)},a=()=>{o(),r(e.signal?.reason)},c=d=>{if(d.key==="Escape"&&e.confirmation&&(d.preventDefault(),s(!1)),d.key==="Tab"){const u=Array.from(i.querySelectorAll("button")),f=u[0],l=u.at(-1);d.shiftKey&&document.activeElement===f?(d.preventDefault(),l?.focus()):!d.shiftKey&&document.activeElement===l&&(d.preventDefault(),f?.focus())}};i.querySelector('[data-action="confirm"]')?.addEventListener("click",()=>s(!0)),i.querySelector('[data-action="cancel"]')?.addEventListener("click",()=>s(!1)),i.addEventListener("click",d=>{e.confirmation&&d.target===i&&s(!1)}),e.signal?.addEventListener("abort",a,{once:!0}),document.addEventListener("keydown",c),(document.querySelector("#host-overlay-layer")??document.body).appendChild(i),i.querySelector("button")?.focus()})}async function vI(e,t){await vi({title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+Jt(e.params)].join(`
22
+ `),signal:t.signal})}async function LI(e,t){await vi({title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+Jt(e.extra)].join(`
23
+ `),signal:t.signal})}async function CI(e,t){await vi({title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+Jt(e.channel),"post: "+Jt(e.post)].join(`
24
+ `),signal:t.signal})}async function RI(e,t){await vi({title:"截图分享",detail:["rect: "+Jt(e.rect),"post: "+Jt(e.post)].join(`
25
+ `),signal:t.signal})}function Jt(e){return JSON.stringify(e,null,2)}function Hc(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}function PI(){if(document.getElementById(zc))return;const e=document.createElement("style");e.id=zc,e.textContent=`
26
+ .hb-sdk-action-dialog {
27
+ position: absolute;
28
+ inset: 0;
29
+ z-index: 40;
30
+ display: grid;
31
+ place-items: center;
32
+ padding: 24px;
33
+ background: rgba(15, 23, 42, 0.45);
34
+ }
35
+
36
+ .hb-sdk-action-dialog__panel {
37
+ width: min(420px, 100%);
38
+ border-radius: 12px;
39
+ padding: 20px;
40
+ background: #fff;
41
+ box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
42
+ }
43
+
44
+ .hb-sdk-action-dialog__panel h2 {
45
+ margin: 0 0 8px;
46
+ font-size: 18px;
47
+ }
48
+
49
+ .hb-sdk-action-dialog__detail {
50
+ margin: 0 0 16px;
51
+ max-height: 40vh;
52
+ overflow: auto;
53
+ color: #1f2933;
54
+ font-family: inherit;
55
+ font-size: 12px;
56
+ line-height: 1.6;
57
+ white-space: pre-wrap;
58
+ overflow-wrap: anywhere;
59
+ word-break: break-word;
60
+ }
61
+
62
+ .hb-sdk-action-dialog__actions {
63
+ display: flex;
64
+ justify-content: flex-end;
65
+ gap: 8px;
66
+ }
67
+
68
+ .hb-sdk-action-dialog__actions button {
69
+ min-height: 36px;
70
+ border: 1px solid #cad5e2;
71
+ border-radius: 6px;
72
+ padding: 0 12px;
73
+ background: #fff;
74
+ cursor: pointer;
75
+ }
76
+
77
+ .hb-sdk-action-dialog__actions .primary {
78
+ border-color: #2563eb;
79
+ color: #fff;
80
+ background: #2563eb;
81
+ }
82
+ `,document.head.appendChild(e)}const kI={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};function xI(e){return new Promise((t,r)=>{if(e.signal.aborted){r(e.signal.reason);return}const n=document.createElement("div");n.className="hb-sdk-auth-dialog",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.innerHTML=`
83
+ <div class="hb-sdk-auth-dialog__panel">
84
+ <h2>授权请求</h2>
85
+ <p class="hb-sdk-auth-dialog__app">${Do(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
86
+ <ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(a=>`<li>${Do(kI[a]||a)}</li>`).join("")}</ul>
87
+ ${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${Do(e.userProfile.nickname)}</p>`:""}
88
+ <div class="hb-sdk-auth-dialog__actions">
89
+ <button type="button" data-action="deny">拒绝</button>
90
+ <button type="button" class="primary" data-action="allow">允许</button>
91
+ </div>
92
+ </div>
93
+ `;const i=a=>{s(),t(a)},o=()=>{s(),r(e.signal.reason)},s=()=>{e.signal.removeEventListener("abort",o),n.remove()};n.querySelector('[data-action="allow"]')?.addEventListener("click",()=>{i({status:"granted",grantedScopes:[...e.scopes]})}),n.querySelector('[data-action="deny"]')?.addEventListener("click",()=>{i({status:"cancelled"})}),e.signal.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n)})}function Do(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}function UI(e){return{launchUrl:e.launchUrl,sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:xs,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:bi},sdkVersion:xs},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const jI=44;function zI(e){const t=()=>e.isCapsuleHidden?.()?0:jI,r=()=>{const n=e.getDeviceMetrics?.();return n?{windowWidth:n.screenWidth,windowHeight:n.screenHeight,screenWidth:n.screenWidth,screenHeight:n.screenHeight,pixelRatio:n.pixelRatio,safeArea:{top:n.safeAreaInsets.top+t(),right:n.screenWidth-n.safeAreaInsets.right,bottom:n.screenHeight-n.safeAreaInsets.bottom,left:n.safeAreaInsets.left}}:{windowWidth:window.innerWidth,windowHeight:window.innerHeight,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}};return{...e.applyDisplay?{applyOrientation:async(n,i)=>(await e.applyDisplay(n,i.signal),{supported:!0})}:{},...e.onViewportChange?{onViewportChange:e.onViewportChange}:{},close:async()=>{await e.close()},reload:async()=>{await e.reload()},getViewportMetrics:()=>e.getViewportMetrics?.()??r(),getNavigationBarHeight:()=>{if(e.getNavigationBarHeight)return e.getNavigationBarHeight();const n=e.getDeviceMetrics?.().statusBarHeight;return n===void 0?0:n+t()},setNavigationBarStyle:n=>{document.documentElement.dataset.navigationBarStyle=n,e.onNavigationBarStyleChange?.(n)},setClipboard:async({text:n})=>{await navigator.clipboard.writeText(n)},showToast:async({message:n,status:i})=>{e.pushLog("host.message",{message:n,status:i}),await gl({message:n,status:i})},showLoading:ml,hideLoading:hl,vibrate:fl,openAppPage:vI,openWindow:LI,showShareMenu:CI,captureAndShare:RI,setScreenshotChromeHidden:ll}}const Fc=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],on=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Vc={"launch-only":[],stdio:["stdio"],full:["stdio","attachments","notifications"],"prepare-fail":[],"prepare-cancel":[],"launch-cancel":[],"os-blocked":[],"normal-exit":["stdio"],crash:["stdio"],"output-limit":["stdio"]};class HI{port;presentation;now;schedule;clearSchedule;onDiagnostic;preparations=new Map;sessions=new Map;eventSink;sessionEventListeners=new Set;nextSessionId=0;constructor(t={}){this.now=t.now??Date.now,this.schedule=t.schedule??((r,n)=>setTimeout(r,n)),this.clearSchedule=t.clearSchedule??(r=>clearTimeout(r)),this.onDiagnostic=t.onDiagnostic??(()=>{}),this.port={getInfo:async r=>this.getInfo(r),getPreparationStatus:async r=>this.getPreparationStatus(r),prepare:(r,n)=>this.prepare(r,n),cancelPreparation:async r=>this.cancelPreparation(r),getActiveSession:async r=>this.getActiveSession(r),launch:async r=>this.launch(r),write:async r=>this.write(r),closeStdin:async r=>this.closeStdin(r),terminate:async r=>this.terminate(r),ackOutput:async r=>this.ackOutput(r),openAttachment:async r=>this.openAttachment(r),showNotification:async r=>this.showNotification(r),onSessionEvent:r=>(this.sessionEventListeners.add(r),()=>this.sessionEventListeners.delete(r))},this.presentation={confirmCompanionOperation:async({action:r,companion:n})=>{const i=n.alias===`${r}-cancel`;return this.diagnostic(`authorization.${i?"cancelled":"granted"}`,n.alias,{action:r}),i?{status:"cancelled"}:{status:"granted"}}}}bindEventSink(t){this.eventSink=t,this.diagnostic(t?"runtime.connected":"runtime.disconnected")}reset(t){const r=t?[t]:[...Fc];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(he("COMPANION_PREPARATION_CANCELLED","固定 Fake 已重置")),this.preparations.delete(n),this.sessions.delete(n)}this.diagnostic("reset",t)}getInfo(t){const r=this.readAlias(t);return{alias:r,displayName:`Browser Fake: ${r}`,target:r==="os-blocked"?"macos-arm64":"windows-x64",capabilities:Vc[r],archiveBytes:12,signatureStatus:"unsigned"}}getPreparationStatus(t){const r=this.readAlias(t);return this.preparations.get(r)?.status??{state:"not-prepared"}}prepare(t,r){const n=this.readAlias(t),i=this.preparations.get(n);if(i?.status.state==="ready")return Promise.resolve(this.getInfo(n));if(i?.operation)return i.operation.listeners.add(r.onProgress),this.diagnostic("prepare.joined",n),r.onProgress(i.status.state==="preparing"?i.status.progress:on[0]),i.operation.promise;let o,s;const a=new Promise((d,u)=>{o=d,s=u}),c={cancelled:!1,listeners:new Set([r.onProgress]),promise:a,reject:s,resolve:o,timers:new Set};{const d={status:{state:"preparing",progress:on[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),on.forEach((u,f)=>{const l=this.schedule(()=>{if(c.timers.delete(l),!c.cancelled){d.status={state:"preparing",progress:u};try{c.listeners.forEach(m=>m(u))}catch(m){c.cancelled=!0;for(const h of c.timers)this.clearSchedule(h);d.operation=void 0,d.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",n,{message:m instanceof Error?m.message:String(m)}),c.reject(m);return}if(this.diagnostic("prepare.progress",n,{phase:u.phase}),f===on.length-1){if(d.operation=void 0,n==="prepare-fail"){d.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},c.reject(he("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",n,{code:"COMPANION_INTEGRITY_FAILED"});return}d.status={state:"ready",preparedAt:this.now()},c.resolve(this.getInfo(n)),this.diagnostic("prepare.ready",n)}}},f+1);c.timers.add(l)})}return a}cancelPreparation(t){const r=this.readAlias(t),n=this.preparations.get(r);if(n?.operation){n.operation.cancelled=!0;for(const i of n.operation.timers)this.clearSchedule(i);n.operation.reject(he("COMPANION_PREPARATION_CANCELLED","准备已取消")),n.operation=void 0,n.status={state:"not-prepared"},this.diagnostic("prepare.cancelled",r)}}getActiveSession(t){const r=this.readAlias(t),n=this.sessions.get(r);if(!n||n.exited)return;const i=n.snapshot.controllerGeneration;return n.snapshot={...n.snapshot,controllerGeneration:i+1},this.emit(zl,{sessionId:n.snapshot.id,controllerGeneration:i}),n.waitingOutput&&(n.queuedOutput.unshift(n.waitingOutput),n.waitingOutput=void 0,this.flushOutput(n)),this.diagnostic("session.controller-transferred",r,{controllerGeneration:n.snapshot.controllerGeneration}),{...n.snapshot,capabilities:[...n.snapshot.capabilities]}}launch(t){const r=this.readAlias(t);if(this.getPreparationStatus(r).state!=="ready")throw he("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw he("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw he("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:Vc[r],state:"running",controllerGeneration:1},o={snapshot:i,stdinClosed:!1,exited:!1,queuedOutput:[]};return this.sessions.set(r,o),this.diagnostic("session.launched",r,{capabilities:[...i.capabilities],sessionId:i.id}),i.capabilities.includes("stdio")&&this.schedule(()=>{this.queueOutput(o,"stdout",1,`fake:ready
94
+ `),this.queueOutput(o,"stderr",1,`fake:diagnostic
95
+ `)},20),r==="normal-exit"&&this.schedule(()=>this.requestExit(o,{reason:"exited",exitCode:0}),40),r==="crash"&&this.schedule(()=>this.requestExit(o,{reason:"crashed",exitCode:1}),40),r==="output-limit"&&this.schedule(()=>this.requestExit(o,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("stdio"))throw he("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw he("COMPANION_PIPE_CLOSED","stdin 已关闭");const n=Math.max(1,...r.queuedOutput.map(i=>i.sequence),r.waitingOutput?.sequence??0)+1;this.queueOutput(r,"stdout",n,new Uint8Array(t.data)),this.diagnostic("stdio.write",r.snapshot.alias,{bytes:t.data.byteLength})}closeStdin(t){const r=this.readController(t);r.stdinClosed=!0,this.diagnostic("stdio.closed",r.snapshot.alias)}terminate(t){const r=this.readController(t);this.exit(r,{reason:"terminated"})}ackOutput(t){const r=this.readController(t),n=r.waitingOutput;!n||n.stream!==t.stream||n.sequence!==t.sequence||(r.waitingOutput=void 0,this.diagnostic("stdio.ack",r.snapshot.alias,{sequence:t.sequence,stream:t.stream}),this.flushOutput(r))}openAttachment(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("attachments"))throw he("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw he("COMPANION_ATTACHMENT_NOT_FOUND","固定 Fake Attachment 不存在");this.diagnostic("attachment.opened",r.snapshot.alias,{id:t.id});const n=new TextEncoder().encode(`Browser Fake Companion report
96
+ `);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw he("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw he("FILE_ACCESS_DENIED","Attachment 只读")},stat:async()=>({kind:"file",size:n.byteLength})}}showNotification(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("notifications"))throw he("COMPANION_NOTIFICATION_UNAVAILABLE","notifications 未启用");this.diagnostic("notification.shown",r.snapshot.alias,{category:t.category})}queueOutput(t,r,n,i){t.queuedOutput.push({stream:r,sequence:n,data:typeof i=="string"?new TextEncoder().encode(i):i}),this.flushOutput(t)}flushOutput(t){if(t.exited||t.waitingOutput||!this.eventSink&&this.sessionEventListeners.size===0)return;const r=t.queuedOutput.shift();if(!r){t.pendingExit&&this.exit(t,t.pendingExit);return}t.waitingOutput=r,this.emit(Ul,{sessionId:t.snapshot.id,controllerGeneration:t.snapshot.controllerGeneration,...r}),this.diagnostic("stdio.chunk",t.snapshot.alias,{bytes:r.data.byteLength,sequence:r.sequence,stream:r.stream})}requestExit(t,r){t.pendingExit=r,!t.waitingOutput&&t.queuedOutput.length===0&&this.exit(t,r)}exit(t,r){t.exited||(t.exited=!0,t.pendingExit=void 0,t.waitingOutput=void 0,t.queuedOutput.length=0,this.emit(jl,{sessionId:t.snapshot.id,exit:r}),this.diagnostic("session.exit",t.snapshot.alias,{...r}))}readController(t){const r=[...this.sessions.values()].find(n=>n.snapshot.id===t.sessionId);if(!r||r.exited)throw he("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw he("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!Fc.includes(t))throw he("COMPANION_NOT_DECLARED","未知固定 Companion Fake 场景");return t}emit(t,r){this.eventSink?.(t,r),this.sessionEventListeners.forEach(n=>n({type:t,payload:r}))}diagnostic(t,r,n){this.onDiagnostic({action:t,...r?{alias:r}:{},...n?{detail:n}:{}})}}const FI=Object.freeze({[mi]:!0,[gi]:!0,[pi]:!0,[yi]:!0,[Ei]:!0,[wi]:!0,[Ii]:!0,[Ai]:!0,[Mi]:!0,[Ni]:!0,[Di]:!0,[Si]:!0,[Or]:!0,[br]:!0,[vr]:!0});function VI(e){return new HI(e)}function he(e,t){return Object.assign(new Error(t),{code:e})}const BI=/^[A-Za-z0-9_-]{22}$/,GI="https://api.xiaoheihe.cn/open_inapp/";function QI(e){const t=typeof e.port=="number"?e.port:Number(e.port);if(!Number.isInteger(t)||t<=0||t>65535)throw new TypeError("Mobile launch redirect port is invalid");if(!BI.test(e.token))throw new TypeError("Mobile launch redirect token is invalid");const r=new URL(`http://${e.host}:${t}/l/${e.token}`);if(r.protocol!=="http:"||r.hostname!==e.host||r.port!==String(t)||r.username||r.password||r.search||r.hash)throw new TypeError("Mobile launch redirect host is invalid");return r.href}function YI(e){const t=new URL(e);if(t.protocol!=="http:"||t.username||t.password)throw new TypeError("Mobile launch redirect URL must be an HTTP URL without credentials");const r=`heybox://${encodeURIComponent(JSON.stringify({protocol_type:"openWindow",full_screen:!0,navigation_bar:{title:""},webview:{url:t.href,pull:!1,refresh:!1}}))}`;return`${GI}#${r}`}function qI(e){const t=Re(e.runtimePermissions),r=us({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=Re(e.publishedRuntimePermissions),o=Re(r.runtimePermissions);for(const s of md){const a=s.key,c={network:"Network",companion:"Companion",appProtocol:"AppProtocol"}[a]??s.name;if(!e.declaredPermissions?.[a]?.enabled)continue;const d=t.valid&&t.permissions[a]?.status==="enabled",u=r.temporaryPermissionKeys.some(f=>f===a);n.push({key:a,label:c,state:s.access==="declaration"?"declared":d?"approved":u?"temporary":"unavailable",facts:{platformApproval:s.access==="declaration"?null:d,temporary:u,effective:o.permissions[a]?.status==="enabled",online:i.valid?i.permissions[a]?.status??"missing":"unknown"},...u?{releaseDifference:"本次使用临时授权,发布后仍需平台批准。"}:i.valid&&!i.permissions[a]?{releaseDifference:"线上快照尚未包含该权限,需发布包含声明的新版本。"}:{},...a==="appProtocol"?{highestRisk:!0}:{},...s.access!=="declaration"&&!d&&!u?{reason:a==="appProtocol"?"最高危险权限:可执行任意协议并绕过其他 SDK 能力权限;当前没有有效临时授权,线上未批准":"没有有效的本地临时授权,线上未批准"}:{}})}if(e.declaredPermissions?.network?.useOfficialDomain){const s=t.valid&&t.permissions.network?.status==="enabled"&&t.permissions.network.config.useOfficialDomain===!0;n.push({key:"network.useOfficialDomain",label:"官方域名",state:s?"approved":"unavailable",...s?{}:{reason:"不支持本地临时授权,获得线上批准后才能使用"}})}return n}function gt(e){return JSON.stringify({source:e.source,miniProgramId:e.miniProgramId,devSessionId:e.devSessionId,contextRevision:e.contextRevision,declaredPermissions:e.declaredPermissions,runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant,companionManifestSha256:e.companionManifestSha256})}const WI="__hb_sdk_mini_dev__",$I="hb-sdk:mini-dev-console",KI="__hb_sdk_mini_dev_console_installed__",Bc=KI;function ZI(e,t=console){XI(t,e,t)}const JI=["log","debug","info","warn","error"];function XI(e,t,r){if(!r||r[Bc]===!0)return!1;let n=!1;for(const i of JI){const o=e[i];if(typeof o!="function")continue;const s=function(...a){try{t(i,a)}catch{}return o.apply(this,a)};try{e[i]=s,n=!0}catch{return n}}return n&&(r[Bc]=!0),n}const Go=1,Gc=64*1024,eA=64,tA=/^[A-Za-z0-9_-]{22}$/;class Ae extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function rA(e,t=!1){const r=iA(e,t);switch(Qo(r,"Server message"),oA(r),r.type){case"grant":return Ir(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),Ar(r.connectionEpoch,"connectionEpoch"),pt(r.nextClientSequence,"nextClientSequence"),pt(r.nextServerSequence,"nextServerSequence"),Qc(r.snapshot),r;case"event":return Ir(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),Ar(r.connectionEpoch,"connectionEpoch"),pt(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&ct("event must be account.changed or status.changed"),Qc(r.snapshot),r;case"heartbeat":return Ir(r,["version","type","connectionEpoch","sequence"],"heartbeat"),Ar(r.connectionEpoch,"connectionEpoch"),pt(r.sequence,"sequence"),r;default:return ct("Unknown server message type")}}function nA(e){const t=e.connectionEpoch;Ar(t,"connectionEpoch"),pt(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(Ar(n.connectionEpoch,"connectionEpoch"),pt(n.sequence,"sequence"),n.connectionEpoch!==t)throw new Ae("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new Ae("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new Ae("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function iA(e,t){if(t)throw new Ae("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new Ae("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Gc)throw new Ae("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Gc)throw new Ae("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return sA(e),JSON.parse(e)}catch(r){throw r instanceof Ae?r:new Ae("INVALID_JSON","Channel frame must contain strict JSON")}}function Qc(e){Qo(e,"snapshot"),Ir(e,["account","permissions"],"snapshot"),Qo(e.account,"snapshot.account"),Ir(e.account,["revision"],"snapshot.account"),pt(e.account.revision,"snapshot.account.revision"),AI(e.permissions)||ct("snapshot.permissions is invalid")}function oA(e){e.version!==Go&&ct("version must be 1")}function Qo(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&ct(`${t} must be a plain JSON object`)}function Ir(e,t,r,n=[]){const i=Object.keys(e);(t.some(o=>!Object.hasOwn(e,o))||i.some(o=>!t.includes(o)&&!n.includes(o)))&&ct(`${r} fields are invalid`)}function pt(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&ct(`${t} must be a non-negative safe integer`)}function Ar(e,t){(typeof e!="string"||!tA.test(e))&&ct(`${t} must be a 22-character base64url value`)}function ct(e){throw new Ae("INVALID_MESSAGE",e)}function sA(e){new aA(e).scan()}class aA{constructor(t){this.source=t}position=0;scan(){if(this.skipWhitespace(),this.scanValue(),this.skipWhitespace(),this.position!==this.source.length)throw new SyntaxError("Unexpected trailing JSON data")}scanValue(t=0){const r=this.source[this.position];if(r==="{"||r==="["){if(t>=eA)throw new Ae("INVALID_JSON","Channel JSON exceeds maximum nesting depth");return r==="{"?this.scanObject(t):this.scanArray(t)}if(r==='"'){this.scanString();return}this.scanPrimitive()}scanObject(t){this.position+=1,this.skipWhitespace();const r=new Set;if(!this.consume("}"))for(;;){if(this.source[this.position]!=='"')throw new SyntaxError("JSON object key must be a string");const n=this.scanString(),i=JSON.parse(n);if(typeof i!="string")throw new SyntaxError("JSON object key must be a string");if(r.has(i))throw new Ae("INVALID_JSON","Channel JSON contains a duplicate key");if(r.add(i),this.skipWhitespace(),!this.consume(":"))throw new SyntaxError("Missing JSON object colon");if(this.skipWhitespace(),this.scanValue(t+1),this.skipWhitespace(),this.consume("}"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON object comma");this.skipWhitespace()}}scanArray(t){if(this.position+=1,this.skipWhitespace(),!this.consume("]"))for(;;){if(this.scanValue(t+1),this.skipWhitespace(),this.consume("]"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON array comma");this.skipWhitespace()}}scanString(){const t=this.position;for(this.position+=1;this.position<this.source.length;){const r=this.source[this.position];if(r==='"')return this.position+=1,this.source.slice(t,this.position);r==="\\"?this.position+=2:this.position+=1}throw new SyntaxError("Unterminated JSON string")}scanPrimitive(){const t=this.position;for(;this.position<this.source.length&&!/[\s,\]}]/.test(this.source[this.position]??"");)this.position+=1;if(t===this.position)throw new SyntaxError("Missing JSON value")}skipWhitespace(){for(;/[\t\n\r ]/.test(this.source[this.position]??"");)this.position+=1}consume(t){return this.source[this.position]!==t?!1:(this.position+=1,!0)}}const Yc=[1e3,2e3,4e3,8e3,15e3];function cA(e){const t=new Set,r=e.webSocketFactory??(v=>new WebSocket(v)),n=e.randomValues??(v=>crypto.getRandomValues(v)),i=e.timers??{clearTimeout:v=>window.clearTimeout(v),setTimeout:(v,C)=>window.setTimeout(v,C)},o=e.onlineTarget??(typeof window>"u"?void 0:window),s=e.visibilityTarget??(typeof document>"u"?void 0:document),a=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let c,d,u,f=!1,l=0,m,h=!1,p=!1;const M=new Set,w=(v,C)=>{if(!(!e.onDiagnostic||M.has(v))){M.add(v);try{e.onDiagnostic({phase:v,...C?{code:C}:{}})}catch{}}},T=(v,C,y=!1)=>{if(u&&v.account.revision<u.account.revision)return;const N=u&&JSON.stringify(v)===JSON.stringify(u);if(u=v,!(N&&!y))for(const D of t)D(v,C)},_=()=>{if(f||m!==void 0||c)return;const v=Yc[Math.min(l,Yc.length-1)];l+=1,m=i.setTimeout(()=>{m=void 0,S()},v)},P=()=>{f||!h||c||(m!==void 0&&(i.clearTimeout(m),m=void 0),S())},F=()=>{a()&&P()},U=()=>{s&&!s.hidden&&P()},O=()=>{p||(p=!0,o?.addEventListener("online",F),s?.addEventListener("visibilitychange",U))},E=()=>{p&&(p=!1,o?.removeEventListener("online",F),s?.removeEventListener("visibilitychange",U))},S=()=>{if(f||c)return;h=!0,O(),m!==void 0&&(i.clearTimeout(m),m=void 0);let v,C;try{v=r(e.url)}catch{w("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),_();return}try{C=uA(n)}catch{w("entropy","NONCE_GENERATION_FAILED");try{v?.close(1011,"channel initialization failed")}catch{}_();return}c=v;let y,N,D;const R=()=>{v.removeEventListener("open",A),v.removeEventListener("message",I),v.removeEventListener("close",L),v.removeEventListener("error",k),d===R&&(d=void 0)},b=()=>{if(c===v){c=void 0,R();try{v.close(1008,"invalid channel state")}catch{}_()}},A=()=>{if(!(f||c!==v))try{v.send(JSON.stringify({version:Go,type:"hello",csrfToken:e.csrfToken,clientNonce:C}))}catch{w("send","HELLO_SEND_FAILED"),b()}},I=x=>{if(f||c!==v)return;if(typeof x.data!="string"){w("parse","TEXT_FRAME_REQUIRED"),b();return}let z;try{z=rA(x.data)}catch(H){w("parse",H instanceof Ae?H.code:"INVALID_MESSAGE"),b();return}if(z.type==="grant"){if(D){w("sequence","DUPLICATE_GRANT"),b();return}y=z.connectionEpoch,N=z.nextClientSequence,D=nA({connectionEpoch:y,nextSequence:z.nextServerSequence}),l=0,M.clear(),T(z.snapshot,{type:"grant"});return}if(!D||!y||N===void 0){w("sequence","MESSAGE_BEFORE_GRANT"),b();return}try{D.accept(z)}catch{w("sequence","INVALID_SEQUENCE"),b();return}if(z.type==="heartbeat"){try{v.send(JSON.stringify({version:Go,type:"heartbeat.ack",connectionEpoch:y,sequence:N}))}catch{w("send","HEARTBEAT_ACK_SEND_FAILED"),b()}N=N===Number.MAX_SAFE_INTEGER?void 0:N+1;return}T(z.snapshot,{type:"event",event:z.event},!0)},L=()=>{c===v&&(w("close","SOCKET_CLOSED"),c=void 0,R(),_())},k=()=>{w("open","SOCKET_ERROR"),b()};v.addEventListener("open",A),v.addEventListener("message",I),v.addEventListener("close",L),v.addEventListener("error",k),d=R};return{connect:S,subscribeUpdates(v){return t.add(v),()=>t.delete(v)},dispose(){if(f)return;f=!0,h=!1,E(),m!==void 0&&i.clearTimeout(m),m=void 0;const v=c;c=void 0,d?.(),v?.close(1e3,"client disposed"),t.clear()}}}function dA(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,o=e[n+1],s=e[n+2];r+=t[i>>2],r+=t[(i&3)<<4|(o??0)>>4],o!==void 0&&(r+=t[(o&15)<<2|(s??0)>>6]),s!==void 0&&(r+=t[s&63])}return r}function uA(e){const t=e(new Uint8Array(16));if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("Channel nonce source must fill 16 bytes");const r=dA(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}try{ZI((e,t)=>{zr(`console.${e}`,{source:"host",message:t.map(r=>qu(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const lA="/__hb_sdk_bootstrap__",fA="/__hb_sdk__/mobile-launch-redirect",hA="/__hb_sdk__/network",mA="/session/status",gA="/session/request",pA="/session/events",yA=320,EA=1e3,wA=1e3,IA=15e3,qc="dark",AA=["windows","macos","linux","unknown"],Vu=new URL(location.href).searchParams,Bu=Vu.get("mini_url"),Tt=Vu.get("ui_preview")==="1",se={get device(){return hr("#device")},get mobileLanSelect(){return hr("#mobile-lan-select")},get mobileQrImage(){return hr("#mobile-qr-image")},get mobileQrStatus(){return hr("#mobile-qr-status")},storageSnapshot:hr("#storage-snapshot")};if(!Bu&&!Tt)throw se.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Gu=Bu??"about:blank",oe=await Ls();$.openPlatformBaseUrl=oe.openPlatformBaseUrl;$.devReadiness=oe.devReadiness;$.miniProgramSupportsDesktop=oe.miniProgramSupportsDesktop;$.desktopLaunch.workspaceCardsEnabled=oe.workspaceCardsEnabled;Kc(oe.hostPlatform);Zc(oe.windowForm);let Ze=oe.lanAddresses,mn=oe.defaultLanAddressId,zt=oe.mobileLaunchRedirect,bs=oe.nativeAppLaunchUnavailableReason,Mr=oe.devSessionId,Yo=oe.miniProgramManifestAccessToken,gn=oe.workspaceCardsEnabled,pn=oe,Os=Ri(oe),Se=oe.devContext,Vt=oe.browserDevContext,pe=wr(Vt);hi();let Nt=Oi(pe),re=!1,Li=0;const Ci=new AbortController;let Me=0,Bt,Ur,yn=0,ot,vs,qo,Wo,ui,Je=0,st=!1,En,$o,So=!1;const Et=Dl({apply:Sl,waitForLayout:async e=>{await td(),await _l(e),await Tl(e)}});let Ko,Zo,Jo,Xo,es,ts,Wc=Date.now(),pr=!1,$c=Promise.resolve(),Gt=-1,jr=!1,at,rs,ns,wn,ht;const li=new Set,is=VI({onDiagnostic:({action:e,alias:t,detail:r})=>Te(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Xt=TI({applyStatus:e=>Xu(e,!0),fetchStatus:e=>Ju(sl(Ci.signal,e)),getCanonicalRevision:()=>Gt,onError:KA,reconcile:()=>PA(Li)}),os=bI({connectEvents:el,invalidate:()=>Xt.invalidate(),isDisposed:()=>re,maxDelayMs:IA,minDelayMs:wA,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let _o=0,yr="",To=!1,ss;await fi(!1);nl();ol(il(oe));Tt&&SA();Pi();Tt||await Yu();await bt("initial");Tt||(el(),CA());MA();zA();function Qu(){!Tt&&!re&&(ss=window.setTimeout(()=>{Yu().finally(Qu)},1e3))}Qu();async function Yu(){if(!(To||re)){To=!0;try{const e=await fetch(`/__hb_sdk__/device-logs?after=${_o}&limit=500`,{signal:AbortSignal.any([Ci.signal,AbortSignal.timeout(5e3)])});if(!e.ok)return;const t=await e.json();if(re)return;if(yr&&t.epoch!==yr){_o=0,yr=t.epoch;return}yr=t.epoch,$.logDevices=t.devices,t.gap&&zr("console.warn",{message:"部分设备日志已超出服务器缓冲,存在日志缺口"});for(const r of t.items){const n=pl(r.method||`console.${r.level}`,{...r,source:"app"},r.timestamp,r.level==="debug"?"log":r.level);n.source=r.source,n.summary=r.message,n.detail=r,n.deviceSessionId=r.deviceSessionId,n.deviceName=t.devices.find(i=>i.id===r.deviceSessionId)?.name,n.dedupeKey=void 0,Jc(n)}_o=t.nextCursor}catch{}finally{To=!1}}}function MA(){window.addEventListener("beforeunload",ZA),window.addEventListener("hb-sdk:restart-runtime",$u),window.addEventListener("hb-sdk:refresh-storage",Pi),window.addEventListener("hb-sdk:qr-open-change",Wu),window.addEventListener("message",NA),Ko=yl(()=>document.querySelector("#host-fullscreen-exit-mount")),Zo=ir(()=>$.devicePresetId,()=>Et.notifyViewportChange(),{flush:"post"}),Jo=ir(()=>$.previewMode,()=>{Et.reset(),Xc(!1),El(!1),er("preview mode changed")}),Xo=ir(()=>ed.value,()=>Et.notifyViewportChange(),{flush:"post"}),es=ir(()=>$.desktopWindow.closed,(e,t)=>{if(as()){if(e){Dt("desktop window closed"),$.runtimeStatus="closed";return}t&&$.runtimeStatus==="closed"&&bt("desktop window reopened")}}),ts=ir(()=>$.desktopWindow.minimized,e=>{e||!as()||(ot?TA():bA())},{flush:"post"})}function NA(e){const t=e.data;if(e.source===null||!we(t)||t.type!==$I||!we(t.detail))return;const r=t.detail;r.level!=="log"&&r.level!=="debug"&&r.level!=="info"&&r.level!=="warn"&&r.level!=="error"||!Array.isArray(r.args)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||zr(`console.${r.level}`,{source:"app",message:r.args.map(n=>qu(n)).join(" ")},r.timestamp,r.level==="log"||r.level==="debug"?"log":r.level)}function qu(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
97
+ `).slice(0,4).join(`
98
+ `):"")||`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}return String(e)}function Wu(e){const t=e.detail?.open===!0;t!==st&&(st=t,Je+=1,ki(),t&&(se.mobileLanSelect.addEventListener("change",DA),tl(),Qr()))}function DA(){st&&Qr()}function $u(){er("manual restart")}function er(e){re||Bt!==void 0||(Te("runtime.restart",{boundary:Me+1}),Bt=window.setTimeout(()=>{Bt=void 0,re||bt(e)},0))}async function bt(e){if(pr)return;const t=++Me;if(Ur=void 0,ui=void 0,Dt(e),Ku(),dl(Nt),await td(),re||t!==Me)return;const r=ks("#device");if(!r){ui=e,$.runtimeStatus="closed";return}if(r.replaceChildren(),$.runtimeStatus="loading",Tt){r.innerHTML=`
99
+ <div class="browser-mock-preview">
100
+ <span class="browser-mock-preview__icon">UI</span>
101
+ <strong>Browser Mock</strong>
102
+ <small>mp_preview</small>
103
+ </div>`,$.runtimeStatus="idle";return}const n=document.createElement("iframe");n.dataset.testid="device-iframe",n.title="小程序预览",n.allow="clipboard-read; clipboard-write",n.name=WI,r.appendChild(n),vs=n;const i=new AbortController;qo=i;let o=!1;try{const s=await Qw(_A(i.signal,t));if(re||t!==Me){s.dispose();return}Wo=s.dispose,s.ports.companion=is.port,s.ports.media=wl({getMode:()=>$.mediaSimulation,signal:i.signal});const a=EI({signal:i.signal,csrfToken:()=>oe.csrfToken??""}),c=Tw({iframe:n,authorizationContext:wI({signal:i.signal,refreshAccount:d=>fi(!0,d),request:Zu,readState:()=>({signed:Se,browser:pe,userId:at,accountRevision:Gt,networkEnabled:Nt.networkRequest.status==="enabled"})}),ports:{...s.ports,...a},environment:s.environment,hostCapabilities:{...s.hostCapabilities,"media.pick":!0,...a?{"gameSaves.getFile":!0,"file.readBytes":!0,"file.readText":!0,"file.stat":!0,"file.exists":!0}:{},...FI},authPresentation:s.authPresentation,companionPresentation:is.presentation,resolveLaunchConfiguration:async()=>(await s.resolveLaunch()).configuration,dispose:s.dispose,onReady:()=>{re||t!==Me||i.signal.aborted||(rd.value=a?c.diagnostics.gameSaves:void 0,$.runtimeStatus="ready",Te("runtime.ready",{generation:t}))},onTrace:d=>LA(t,d),onError:()=>{o=!0,$.runtimeStatus="error"},onCapabilityTrace:d=>{yr||Te(d.method,d),d.method==="storage.setStorage"&&d.outcome==="success"&&Pi()}});ot=c,await c.start()}catch(s){if(re||t!==Me||i.signal.aborted)return;$.runtimeStatus="error",o||Te("runtime.start.failed",Il(s))}}function SA(){Te("runtime.ready",{generation:1}),zr("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info"),Te("user.getInfo",{durationMs:34,outcome:"success"}),Te("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function _A(e,t){const r=pe,n=Mr,i=NI(r.runtimePermissions,Nt,r),o=as();return{signal:e,account:{async getCurrentUserId(){return(await fi(!1,e)).user_id},async ensureAuthenticated({signal:s}){await fi(!1,s)},onChange(s){return li.add(s),()=>li.delete(s)}},authenticatedRequest:Zu,storage:{area:"local",storage:localStorage},presentation:zI({close:async()=>{id(),!(re||t!==Me)&&(Dt("presentation closed"),Et.reset(),Ku(),$.runtimeStatus="closed",o&&Xc(!0))},reload:()=>{!re&&t===Me&&(Ur=t)},onNavigationBarStyleChange:nd,pushLog:Te,...o?{getViewportMetrics:()=>{const s=ed.value;return{windowWidth:s.width,windowHeight:s.height,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio,safeArea:{left:0,right:s.width,top:0,bottom:s.height}}},getNavigationBarHeight:()=>bl}:{getDeviceMetrics:()=>Ol.value,applyDisplay:(s,a)=>Et.applyDisplay(s,a),isCapsuleHidden:()=>$.display.capsuleHidden},onViewportChange:s=>Et.onViewportChange(s)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:s=>{document.title=s}},resolveLaunch:async()=>({configuration:UI({launchUrl:Gu,runtimePermissions:i,...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:o?$.hostPlatform:Al.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:s=>xI(s),confirmFollowAuthor:s=>OI(s)},protocol:OA()}}function as(){return $.previewMode==="desktop"}function TA(){const e=vs;if(!e||e.isConnected)return!1;const t=ks("#device");return t?(t.replaceChildren(),t.appendChild(e),!0):!1}function bA(){const e=ui;ui=void 0,e&&bt(e)}function OA(){return{async invoke(e){Te("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:vA(e)})}}}function vA(e){if(typeof e!="string")return typeof e.protocol_type=="string"?e.protocol_type:void 0;const t=/^heybox:\/\/(.+)$/i.exec(e.trim());if(t)try{const r=JSON.parse(decodeURIComponent(t[1]));return we(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function Ku(){document.documentElement.dataset.navigationBarStyle=qc,nd(qc)}function LA(e,t){const r=Ml(t,e);r&&Jc(r),!(t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||Ur!==e||e!==Me)&&(Ur=void 0,er("navigation.reload"))}async function Zu(e,t){if(e.redirectPolicy!=="error")throw new Error("Browser Dev Host network 只允许 no-follow redirect policy");const n=e.target.kind==="absolute-url"&&e.source==="public-sdk"&&e.target.kind==="absolute-url"?{url:e.target.url,method:e.method,params:e.params,data:e.data,bodyEncoding:e.bodyEncoding,headers:e.headers,timeout:e.timeout}:void 0;if(!n&&e.source!=="runtime-private")throw new Error("Browser Dev Host 的公开请求只支持 absolute URL");const i=await Cs(n?hA:gA,{method:"POST",body:JSON.stringify(n??{target:e.target,method:e.method,params:e.params,data:e.data,headers:e.headers,credentials:e.source==="runtime-private"?e.credentials:void 0,bodyEncoding:e.bodyEncoding,timeout:e.timeout}),signal:t.signal});!n&&i.status===401&&Xt.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function fi(e,t){const r=Li,n=await Ju(sl(Ci.signal,t));return al(r)?Xu(n,e).status:cs()}async function Ju(e){return await(await fetch(mA,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Xu(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Gt)return{changed:!1,status:cs()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?ue(e.nickname):void 0,i=e.authenticated?ue(e.avatar):void 0,o=e.revision!==Gt||e.authenticated!==jr||r!==at||n!==rs||i!==ns;return Gt=e.revision,jr=e.authenticated,at=r,rs=n,ns=i,nl(),t&&o&&li.forEach(s=>s(at)),{changed:o,status:cs()}}function cs(){return{authenticated:jr,revision:Gt,...jr&&at?{user_id:at}:{}}}function CA(){if(!(!oe.csrfToken||re))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",ht=cA({csrfToken:oe.csrfToken,onDiagnostic:t=>Te("channel.diagnostic",t),url:e.toString()}),ht.subscribeUpdates((t,r)=>RA(t,r)),ht.connect()}catch{ht?.dispose(),ht=void 0}}function RA(e,t){Xt.invalidate(e.account.revision),eM(Nt,e.permissions)?t.type==="event"&&t.event==="status.changed"&&bt("status changed"):(Nt=dl(e.permissions),kA())}function el(){if(wn?.close(),wn=void 0,!at||re)return;const e=new EventSource(pA);wn=e,e.addEventListener("account-invalidated",()=>{Xt.invalidate()}),e.addEventListener("account-revision",()=>{Xt.invalidate()}),e.onopen=()=>{os.reset()},e.onerror=()=>{e.close(),os.schedule()}}async function PA(e){al(e)&&await bt("account revision changed")}function Dt(e){rd.value=void 0,yn+=1,id(),ot&&is.reset(),ot?.destroy(),ot=void 0,vs=void 0,qo?.abort(new DOMException(e,"AbortError")),qo=void 0,Wo?.(),Wo=void 0,Et.reset()}async function kA(){re||(await bt("permission changed"),!re&&await Qr())}async function Ls(){const e=await fetch(lA,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error("Browser Dev Host bootstrap request failed");const t=await e.json();if(!we(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=cl(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new tr;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:jA(t.devReadiness),csrfToken:typeof t.csrfToken=="string"?t.csrfToken:void 0,defaultLanAddressId:typeof t.defaultLanAddressId=="string"?t.defaultLanAddressId:void 0,devSessionId:typeof t.devSessionId=="string"&&/^[a-f0-9]{32}$/.test(t.devSessionId)?t.devSessionId:void 0,devContext:Uc(t.devContext,t.runtimePermissions),browserDevContext:Uc(t.browserDevContext??t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(XA):[],loginAvailable:t.loginAvailable===!0,miniProgram:WA(t.miniProgram),miniProgramSupportsDesktop:t.miniProgramSupportsDesktop===!0,workspaceCardsEnabled:t.workspaceCardsEnabled===!0,mobileLaunchRedirect:r,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof t.miniProgramManifestAccessToken=="string"?t.miniProgramManifestAccessToken:void 0,windowForm:UA(t.windowForm),hostPlatform:xA(t.hostPlatform)}}function xA(e){return AA.includes(e)?e:"unknown"}function UA(e){if(!we(e))return;const t=s=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:void 0,r=t(e.defaultWidth),n=t(e.defaultHeight),i=t(e.minWidth),o=t(e.minHeight);return{...r===void 0?{}:{defaultWidth:r},...n===void 0?{}:{defaultHeight:n},...i===void 0?{}:{minWidth:i},...o===void 0?{}:{minHeight:o},...typeof e.resizable=="boolean"?{resizable:e.resizable}:{}}}function jA(e){if(!we(e))return;const t=s=>{if(!(!we(s)||!["ready","pending","blocked","not-configured"].includes(String(s.state))))return{state:s.state,...typeof s.reason=="string"?{reason:s.reason.slice(0,240)}:{}}},r=t(e.browser),n=t(e.mobile),i=t(e.companion);if(!r||!n||!i||!we(e.companion))return;const o=e.companion;return{browser:r,mobile:n,companion:{...i,...typeof o.digest=="string"&&/^[a-f0-9]{64}$/.test(o.digest)?{digest:o.digest}:{},artifacts:Array.isArray(o.artifacts)?o.artifacts.filter(s=>we(s)&&typeof s.alias=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(s.alias)&&["windows-x64","macos-arm64"].includes(String(s.target))).map(({alias:s,target:a})=>({alias:s,target:a})):[]}}}async function Cs(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),oe.csrfToken&&r.set("x-hb-sdk-csrf",oe.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function zA(){Rs(),Tt||($o=window.setInterval(()=>{qA()},EA))}function tl(e=se.mobileLanSelect.options.length>0?se.mobileLanSelect.value:void 0){se.mobileLanSelect.replaceChildren();for(const t of Ze){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,se.mobileLanSelect.appendChild(r)}e&&Ze.some(({id:t})=>t===e)?se.mobileLanSelect.value=e:mn&&Ze.some(({id:t})=>t===mn)?se.mobileLanSelect.value=mn:Ze[0]&&(se.mobileLanSelect.value=Ze[0].id),se.mobileLanSelect.disabled=Ze.length===0}async function Qr(){if(re)return;const e=++Je;if(ki(),Se.source!=="remote"||!Se.localDevLaunchToken||Se.expiresAt!==void 0&&Se.expiresAt<=Date.now()){se.mobileQrImage.removeAttribute("src"),se.mobileQrStatus.textContent=bs||"需要有效的本地调试启动票";return}const t=JA();if(!t?.mobileAppQrPayload){se.mobileQrImage.removeAttribute("src"),se.mobileQrStatus.textContent="未发现可用的局域网地址";return}se.mobileQrStatus.textContent="正在生成二维码...";try{const r=await GA(t);if(e!==Je||re)return;const n=await HA(r.address,r.expiresAt);if(e!==Je||re)return;const i=await mI.toDataURL(n.payload,{width:yA,margin:1});if(e!==Je||re)return;se.mobileQrImage.src=i,se.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,YA(n.expiresAt,e)}catch(r){if(e!==Je||re)return;if(r instanceof tr){In();return}se.mobileQrImage.removeAttribute("src"),se.mobileQrStatus.textContent=Ps(r)}}async function HA(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await FA(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:YI(QI({host:e.address,port:location.port,token:n.token}))}}catch{throw new tr}}async function FA(e,t){if(zt?.addressId===e.id)return zt;if(!zt)return;const r=await Cs(fA,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:zt.token})});if(!r.ok)throw new tr;const n=await r.json(),i=we(n)?cl({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new tr;return zt=i,pn={...pn,mobileLaunchRedirect:i},Os=Ri(pn),i}async function VA(e){const t=await Ls(),r=BA(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return rl(t),{...r,mobileAppQrPayload:n}}function BA(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function rl(e){const t=gt(pe);$.devReadiness=e.devReadiness,$.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,Kc(e.hostPlatform),Zc(e.windowForm),gn=e.workspaceCardsEnabled,pn=e,Os=Ri(e),Se=e.devContext,Vt=e.browserDevContext,pe=wr(Vt),Nt=Oi(pe),hi(),Ze=e.lanAddresses,mn=e.defaultLanAddressId,zt=e.mobileLaunchRedirect,bs=e.nativeAppLaunchUnavailableReason,Mr=e.devSessionId,Yo=e.miniProgramManifestAccessToken,ol(il(e)),st&&tl(),Rs(),t!==gt(pe)&&(Me+=1,Dt("local permission context changed"),er("local permission context changed"))}function hi(){$.localPermissions=qI(pe),$.devContextWarning=pe.source==="anonymous"?"未连接线上上下文":pe.warning?"本地上下文受限,请检查 CLI 状态":""}function Rs(){let e;try{e=Nl(Gu)}catch{}const t=Se.miniProgramId?.trim().toLowerCase();let r=bs?.trim()??"";!r&&(Se.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!Se.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&gn&&!Mr&&(r="本地调试会话尚未就绪"),!r&&Se.expiresAt!==void 0&&Se.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),od({...e?{address:e}:{},...t?{miniProgramId:t}:{},...gn&&Mr?{devSessionId:Mr}:{},...Yo?{miniProgramManifestToken:Yo}:{},workspaceCardsEnabled:gn,ready:r==="",...r?{unavailableReason:r}:{}})}class tr extends Error{}async function GA(e){const t=$c.then(()=>QA(e));return $c=t.then(()=>{},()=>{}),t}async function QA(e){const t=new URL(e.appUrl),r=new URL(II,location.origin),n=await Cs(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:DI(Se)})}),i=await n.json();if(!n.ok||!we(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await VA(e.id),expiresAt:i.expires_at}}function YA(e,t){En=window.setTimeout(()=>{!re&&st&&t===Je&&Qr()},Math.max(1e3,e-Date.now()-3e4))}async function qA(){if(!(So||re)){So=!0;try{const e=await Ls();Wc=Date.now();const t=pr;pr=!1;const r=Ri(e);if(!t&&r===Os&&gt(wr(e.browserDevContext))===gt(pe)){Vt=e.browserDevContext,pe=wr(Vt),hi();return}rl(e),t&&er("CLI dev session reconnected"),st&&Qr()}catch(e){e instanceof tr&&In();const t=wr(Vt);gt(t)!==gt(pe)&&(pe=t,Nt=Oi(pe),hi(),Me+=1,Dt("local permission context expired"),er("local permission context expired"),Rs(),st&&In()),Date.now()-Wc>=3e4&&!pr&&(pr=!0,Me+=1,Dt("CLI dev session disconnected"),ks("#device")?.replaceChildren(),$.runtimeStatus="closed",$.localPermissions=[],$.devContextWarning="调试会话已断开",od({ready:!1,unavailableReason:"调试会话已断开"}),$.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},st&&In())}finally{So=!1}}}function In(){Je+=1,ki(),se.mobileQrImage.removeAttribute("src"),se.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Ri(e){return JSON.stringify({devReadiness:e.devReadiness,devSessionId:e.devSessionId,defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,devContext:{permissionContext:gt(e.devContext),expiresAt:e.devContext.expiresAt,localDevLaunchToken:e.devContext.localDevLaunchToken,miniProgramId:e.devContext.miniProgramId,source:e.devContext.source},nativeAppLaunchUnavailableReason:e.nativeAppLaunchUnavailableReason,miniProgramManifestAccessToken:e.miniProgramManifestAccessToken,miniProgramSupportsDesktop:e.miniProgramSupportsDesktop,workspaceCardsEnabled:e.workspaceCardsEnabled,hostPlatform:e.hostPlatform,windowForm:e.windowForm})}function nl(){if(!jr){$.account={authenticated:!1,avatar:"",nickname:"未登录"};return}$.account={authenticated:!0,avatar:ns??"",nickname:rs||at||"已登录"}}function il(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function ol(e){if(!!!e?.miniProgramId||!e){$.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}$.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function WA(e){if(e===null)return null;if(!we(e))return;const t=ue(e.miniProgramId)??ue(e.mini_program_id);if(t)return{miniProgramId:t,...ue(e.name)?{name:ue(e.name)}:{},...ue(e.iconUrl)??ue(e.icon_url)?{iconUrl:ue(e.iconUrl)??ue(e.icon_url)}:{},...ue(e.status)?{status:ue(e.status)}:{},...ue(e.version)?{version:ue(e.version)}:{},...ue(e.developerName)??ue(e.developer_name)?{developerName:ue(e.developerName)??ue(e.developer_name)}:{}}}function ue(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function Pi(){const e=++yn,t=ot,r=t?.diagnostics.storage;if(!r){$.storage=[],$.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(re||e!==yn||t!==ot)return;$.storage=n.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),$.storageError=""}catch(n){if(re||e!==yn||t!==ot)return;$.storage=[],$.storageError=Ps(n)}}function $A(e,t){Te("host.message",{message:e,status:t})}function KA(e){re||$A(Ps(e),"error")}function Te(e,t){zr(e,t)}function ZA(){ss!==void 0&&window.clearTimeout(ss),!re&&(re=!0,window.removeEventListener("hb-sdk:restart-runtime",$u),window.removeEventListener("hb-sdk:refresh-storage",Pi),window.removeEventListener("hb-sdk:qr-open-change",Wu),Li+=1,Ci.abort(new DOMException("Browser Dev Host disposed","AbortError")),Xt.dispose(),Me+=1,Dt("Browser Dev Host disposed"),wn?.close(),ht?.dispose(),ht=void 0,os.dispose(),Ur=void 0,Bt!==void 0&&window.clearTimeout(Bt),Bt=void 0,ki(),$o!==void 0&&window.clearInterval($o),li.clear(),Ko?.(),Ko=void 0,Zo?.(),Zo=void 0,Jo?.(),Jo=void 0,Xo?.(),Xo=void 0,es?.(),es=void 0,ts?.(),ts=void 0)}function ki(){En!==void 0&&window.clearTimeout(En),En=void 0}function sl(e,t){return t?AbortSignal.any([e,t]):e}function al(e){return!re&&e===Li}function JA(){return Ze.find(({id:e})=>e===se.mobileLanSelect.value)}function XA(e){return we(e)&&typeof e.address=="string"&&typeof e.appUrl=="string"&&typeof e.id=="string"&&typeof e.name=="string"&&(e.mobileAppQrPayload===void 0||typeof e.mobileAppQrPayload=="string")}function cl(e){if(!(!we(e)||typeof e.addressId!="string"||!e.addressId||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||typeof e.token!="string"||!/^[A-Za-z0-9_-]{22}$/.test(e.token)))return{addressId:e.addressId,expiresAt:e.expiresAt,token:e.token}}function dl(e){return{networkRequest:{...e.networkRequest}}}function eM(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function Ps(e){return e instanceof Error&&e.message?e.message:"操作失败"}function we(e){return Object.prototype.toString.call(e)==="[object Object]"}function hr(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function ks(e){return document.querySelector(e)??void 0}