@heybox/hb-sdk 0.9.4 → 0.9.5-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/cli-chunks/{artifact-DKBVVALl.cjs → artifact-CevKlc1g.cjs} +3 -3
  3. package/dist/cli-chunks/{build-ByqewdbU.cjs → build-CF1-28D8.cjs} +5 -5
  4. package/dist/cli-chunks/{create-RucKGsv0.cjs → create-Q50un0Bg.cjs} +1 -1
  5. package/dist/cli-chunks/{deploy-lock-IBHm1WFG.cjs → deploy-lock-CpdL3s9E.cjs} +1 -1
  6. package/dist/cli-chunks/{dev-D-_6vms0.cjs → dev-Bsa-tW7L.cjs} +8 -8
  7. package/dist/cli-chunks/{dev-context-B4ZtDxzm.cjs → dev-context-D007Z2-c.cjs} +2 -2
  8. package/dist/cli-chunks/{doctor-DQeX2AJX.cjs → doctor-CIWDaPfi.cjs} +1 -1
  9. package/dist/cli-chunks/{games-BMmrK7pj.cjs → games-CNjfXQjT.cjs} +2 -2
  10. package/dist/cli-chunks/{index-DOg8iLM6.cjs → index-CYTciTqL.cjs} +1 -1
  11. package/dist/cli-chunks/{index-Dx_O9N1P.cjs → index-xZw-b2po.cjs} +17 -17
  12. package/dist/cli-chunks/{index.esm-C_JZnx87.cjs → index.esm-hwkHnZhi.cjs} +6 -6
  13. package/dist/cli-chunks/{login-DzbMxAOa.cjs → login-ClnBJiRJ.cjs} +1 -1
  14. package/dist/cli-chunks/{project-vite-DXt33L_j.cjs → project-vite-CgMLPNS6.cjs} +1 -1
  15. package/dist/cli-chunks/{remote-CxGBKlIt.cjs → remote-D-N5Gj1e.cjs} +7 -7
  16. package/dist/cli-chunks/{runtime-permission-env-BAi5k5Hm.cjs → runtime-permission-env-BF-Jw5-T.cjs} +2 -2
  17. package/dist/cli-chunks/{skill-CtKW4NiU.cjs → skill-ba1VHnEN.cjs} +2 -2
  18. package/dist/cli-chunks/{version-CJsHJ4QU.cjs → version-CArGts-T.cjs} +1 -1
  19. package/dist/cli.cjs +1 -1
  20. package/dist/devtools/browser-dev-host/assets/{browser-dev-host-B9Gx2iIY.js → browser-dev-host-D9zSDJJ8.js} +9 -9
  21. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-BElRBLGR.js → desktop-app-launch-BXS6eaj9.js} +1 -1
  22. package/dist/devtools/browser-dev-host/assets/{index-zZH5iNv_.js → index-Bn6Xr40h.js} +3 -3
  23. package/dist/devtools/browser-dev-host/index.html +2 -2
  24. package/dist/index.cjs.js +1 -1
  25. package/dist/index.esm.js +1 -1
  26. package/dist/vite.cjs.js +1 -1
  27. package/dist/vite.esm.js +1 -1
  28. package/package.json +5 -5
  29. package/skill/SKILL.md +4 -0
  30. package/skill/skill.json +5 -5
@@ -1,15 +1,15 @@
1
- import{H as gs,aD as xu,b2 as ju,P as Uu,aN as zu,aO as Hu,ap as Rr,bc as Z,ag as Fu,aq as vc,aw as Vu,b6 as Bu,r as Gu,as as Qu,f as Yu,aK as Cc,ae as qu,az as Lc,u as $u,aF as Rc,q as Wu,aJ as Ku,ab as Ju,b4 as Zu,b3 as Xu,e as el}from"./desktop-app-launch-BElRBLGR.js";const mn="workspaceCards.requestRefresh",gn="auth.getAccountState",pn="auth.login",tl="gameSaves.list",rl="gameSaves.sync",nl="gameSaves.getFile",il="gameSaves.readParsedData",yn="user.getInfo",En="user.revokeAuthorization",wn="user.getSteamGameList",In="share.copyLink",An="share.showShareMenu",Mn="share.screenshot",ht="viewport.setDisplay",Nn="viewport.getWindowInfo",Dn="viewport.setNavigationBarStyle",gr="storage.getStorage",pr="storage.setStorage",Sn="network.request",Tn="network.download",_n="network.upload",bn="files.pickFiles",On="files.pickDirectory",vn="files.saveFile",yr="file.create",Er="file.remove",Cn="file.exists",wr="file.readText",Ln="file.writeText",Ir="file.readBytes",Rn="file.writeBytes",Ar="file.stat",Pn="directory.create",Mr="directory.remove",kn="directory.exists",xn="directory.list",Nr="media.pick",jn="ui.showToast",Un="ui.showLoading",zn="ui.hideLoading",Hn="device.vibrate",Fn="device.setClipboard",Vn="device.executeProtocol",Bn="navigation.close",Gn="navigation.reload",Qn="navigation.openAppPage",Be="cloud.leaderboard.submit",be="cloud.leaderboard.getList",Je="cloud.leaderboard.getCurrentUserEntry",mt="cloud.leaderboard.deleteCurrentUserEntry",Ue="cloud.leaderboard.getInfo",kt="cloud.storage.getStorage",xt="cloud.storage.setStorage",jt="cloud.storage.removeItem",gt="cloud.storage.getKeys",ri="companion.getInfo",ni="companion.getPreparationStatus",ii="companion.prepare",oi="companion.cancelPreparation",si="companion.getActiveSession",ai="companion.launch",ci="companion.session.write",di="companion.session.closeStdin",ui="companion.session.terminate",li="companion.session.ackOutput",fi="companion.openAttachment",hi="companion.showNotification",Ze=[...[tl,rl,nl,il].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),{method:mn,module:"workspaceCards",capability:mn,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:gn,module:"auth",capability:gn,requirement:{kind:"none"},risk:"low"},{method:pn,module:"auth",capability:pn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:yn,module:"user",capability:yn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:En,module:"user",capability:En,requirement:{kind:"none"},risk:"high"},{method:wn,module:"user",capability:wn,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:In,module:"share",capability:In,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:An,module:"share",capability:An,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Mn,module:"share",capability:Mn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Nn,module:"viewport",capability:Nn,requirement:{kind:"none"},risk:"low"},{method:Dn,module:"viewport",capability:Dn,requirement:{kind:"none"},risk:"low"},{method:ht,module:"viewport",capability:ht,requirement:{kind:"none"},risk:"low"},{method:gr,module:"storage",capability:gr,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:pr,module:"storage",capability:pr,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Sn,module:"network",capability:Sn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Tn,module:"network",capability:Tn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:_n,module:"network",capability:_n,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:bn,module:"files",capability:bn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:On,module:"files",capability:On,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:vn,module:"files",capability:vn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:yr,module:"file",capability:yr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Er,module:"file",capability:Er,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Cn,module:"file",capability:Cn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:wr,module:"file",capability:wr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ln,module:"file",capability:Ln,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ir,module:"file",capability:Ir,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Rn,module:"file",capability:Rn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ar,module:"file",capability:Ar,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Pn,module:"directory",capability:Pn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mr,module:"directory",capability:Mr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:kn,module:"directory",capability:kn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:xn,module:"directory",capability:xn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Nr,module:"media",capability:Nr,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:jn,module:"ui",capability:jn,requirement:{kind:"none"},risk:"low"},{method:Un,module:"ui",capability:Un,requirement:{kind:"none"},risk:"low"},{method:zn,module:"ui",capability:zn,requirement:{kind:"none"},risk:"low"},{method:Hn,module:"device",capability:Hn,requirement:{kind:"none"},risk:"low"},{method:Fn,module:"device",capability:Fn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Vn,module:"device",capability:Vn,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:Bn,module:"navigation",capability:Bn,requirement:{kind:"none"},risk:"medium"},{method:Gn,module:"navigation",capability:Gn,requirement:{kind:"none"},risk:"medium"},{method:Qn,module:"navigation",capability:Qn,requirement:{kind:"none"},risk:"medium"},{method:Be,module:"cloud",capability:Be,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:be,module:"cloud",capability:be,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Je,module:"cloud",capability:Je,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:mt,module:"cloud",capability:mt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ue,module:"cloud",capability:Ue,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:kt,module:"cloud",capability:kt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:xt,module:"cloud",capability:xt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:jt,module:"cloud",capability:jt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:gt,module:"cloud",capability:gt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[ri,ni,ii,oi,si,ai,ci,di,ui,li,fi,hi].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],ot="heybox:miniprogram",Pc=2,ol="hb_mini_bridge_nonce",kc="sdk.handshake",Hr="runtime.location.probe",sl="sdk.location.report",al="sdk.csp.violation",xc="operation.progress",cl="companion.session.output",dl="companion.session.exit",ul="companion.session.ownershipLost";function ll(e){return!Le(e)||e.namespace!==ot||e.version!==1&&e.version!==2||!oe(e.nonce)?!1:e.type==="handshake"?oe(e.id)&&e.method===kc&&e.error===void 0&&wl(e.payload):e.type==="request"?oe(e.id)&&oe(e.method)&&e.error===void 0:e.type==="response"?oe(e.id)&&(e.method===void 0||oe(e.method))&&(e.error===void 0||Il(e.error)):e.type==="event"?!oe(e.method)||e.error!==void 0?!1:e.method===xc?e.version===2&&oe(e.id)&&El(e.payload):e.id===void 0||oe(e.id):e.type==="cancel"?e.version===2&&oe(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Go(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function jc(e){return Le(e)?e.kind==="sandbox"?Se(e,["kind"]):e.kind==="directory"&&oe(e.handleId)&&Se(e,["kind","handleId"]):!1}function Ut(e){return!Le(e)||e.kind!=="file"?!1:oe(e.handleId)?Se(e,["kind","handleId"]):jc(e.root)&&Go(e.relativePath)&&Se(e,["kind","root","relativePath"])}function Uc(e){return!Le(e)||e.kind!=="directory"?!1:oe(e.handleId)?Se(e,["kind","handleId"]):jc(e.root)&&(e.relativePath==="."||Go(e.relativePath))&&Se(e,["kind","root","relativePath"])}function fl(e){return Le(e)&&e.kind==="file"&&oe(e.name)&&Al(e.mode)&&Ut(e.ref)&&Se(e,["kind","name","mode","ref"])}const zc=20,ps=["type","mimeType","size","width","height","previewUrl","file"];function hl(e){return e===void 0?!0:!(!Le(e)||!Se(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&&(!Ml(e.maxCount,1,zc)||e.source==="camera"&&e.maxCount!==1))}function Hc(e){if(!Le(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!Se(e,t?[...ps,"durationMs"]:ps)||!oe(e.mimeType)||!$e(e.size)||!ys(e.width)||!ys(e.height)||!oe(e.previewUrl)||!gl(e.file)?!1:t?$e(e.durationMs):!0}function ml(e){if(!Array.isArray(e)||e.length<1||e.length>zc)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!Hc(e[t]))return!1;return!0}function gl(e){return!fl(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&oe(e.ref.handleId)}function Fc(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function pl(e){return!Le(e)||!$e(e.loaded)||typeof e.lengthComputable!="boolean"||!Se(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?$e(e.total)&&e.loaded<=e.total:e.total===void 0}function yl(e){return Le(e)?e.phase==="downloading"?$e(e.loaded)&&(e.total===void 0||$e(e.total)&&e.loaded<=e.total)&&Se(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:$e(e.processed)&&$e(e.total)&&e.processed<=e.total&&Se(e,["phase","processed","total"]):!1}function El(e){return pl(e)||yl(e)}function wl(e){return Le(e)&&oe(e.href)&&typeof e.userAgent=="string"&&oe(e.sdkVersion)}function Il(e){return Le(e)&&oe(e.code)&&typeof e.message=="string"}function Al(e){return e==="read"||e==="readwrite"}function $e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ys(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Ml(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function oe(e){return typeof e=="string"&&e.length>0}function Se(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Le(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Dr=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards"],Vc=[{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(Dr);const Nl=new Set(Dr);function Dl(e){return Nl.has(e)}function Oe(e){if(!Fr(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(!Fr(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),!!Dl(o)){if(o==="network"){const s=n.config;if(!Fr(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&&(!Fr(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 Fr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Zr=["network","companion","appProtocol"];function Bc(e){if(!Wt(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>Zr.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Wt(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(!Wt(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(!Wt(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Wt(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>Zr.indexOf(n.key)-Zr.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Sl(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Oe(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of Zr)!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 Qo(e){const t=Oe(e.runtimePermissions),r=Bc(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of Dr)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:Vc.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=Gc(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:Dr.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function Gc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wt(e,t){return Gc(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const zt=["identity","profile","steam_account"],Tl=/^[a-z][a-z0-9-]{0,31}$/,Qc=["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"];Ze.map(e=>e.method);function _l(e){const t=Oe(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 bl(e){const t=Oe(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 Yo(e){return Ol(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?ee("RUNTIME_ERROR",e.message):ee("UNKNOWN_ERROR","小程序运行时异常",e)}function Ol(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function vl(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Cl=1e3;function Ll(e,t=vl()){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<=Cl}const Rl="runtime.gate.probe",Yc=new Set(Ze.map(e=>e.method));class Pl{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=Pc;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:ot,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:ot,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:ot,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:ot,version:2,nonce:this.nonce,type:"event",id:t,method:xc,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=Ll(this.iframe,{activeElement:document.activeElement,userActivation:navigator.userActivation,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{n=!1}this.handleRequest(r,n);return}if(r.type==="cancel"&&this.handshaken&&r.id){this.operations.get(r.id)?.abort();return}r.type==="event"&&this.handshaken&&this.onInternalEvent?.(r)}onUserInteraction(t){const r=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||r.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&ll(t.data)&&(!this.handshaken||t.data.version===this.bridgeVersion)&&((this.handshaken?this.bridgeVersion:t.data.version)===1||this.targetOrigin==="*"||t.origin===this.targetOrigin)&&t.data.nonce===this.nonce}handleHandshake(t,r){const n=t.payload,i=t.version,o=!this.handshaken;if(o){if(this.onHandshake?.(n)===!1)return;this.bridgeVersion=i,i===1&&this.targetOrigin!=="*"&&r&&r!=="null"&&(this.targetOrigin=r),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.environmentInfo&&t.id&&this.postMessage({namespace:ot,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:kc,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===Rl){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,ee("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Yc.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=Yo(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:ot,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!kl(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 kl(e){return typeof e=="string"&&Yc.has(e)}function xl(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 qc="METHOD_FORBIDDEN";function Ne(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=qc,t}class ue 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 jl=/^[A-Za-z0-9_-]{1,64}$/,Es=1e3;function $c(e){return jl.test(e)?e:zl(e)}function Ul(e){return`id_${$c(e.trim())}`}function It(e,t){return`hb_miniprogram_${e}_${t}`}function Vr(e){return`hb_miniprogram_keys_${e}`}function zl(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 ws={"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"],[mn]:["workspaceCards.requestRefresh"],[gn]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[pn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[yn]:["account.getCurrentUserId","account.onChange","network.request"],[En]:["account.getCurrentUserId","account.onChange","network.request"],[wn]:["account.getCurrentUserId","account.onChange","network.request"],[In]:["presentation.setClipboard"],[An]:["presentation.showShareMenu"],[Mn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ht]:["presentation.applyOrientation"],[Nn]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Dn]:["presentation.setNavigationBarStyle"],[gr]:["storage.getRaw"],[pr]:["storage.setRaw"],[Sn]:["network.request"],[Tn]:["network.stream","files.transfer","files.access"],[_n]:["network.upload","files.access"],[bn]:["files.external"],[On]:["files.external"],[vn]:["files.save"],[yr]:["files.access"],[Er]:["files.removeFile"],[Cn]:["files.access"],[wr]:["files.access"],[Ln]:["files.access"],[Ir]:["files.access"],[Rn]:["files.access"],[Ar]:["files.access"],[Pn]:["files.access"],[Mr]:["files.removeDirectory"],[kn]:["files.access"],[xn]:["files.access"],[Nr]:["media.pick"],[jn]:["presentation.showToast"],[Un]:["presentation.showLoading"],[zn]:["presentation.hideLoading"],[Hn]:["presentation.vibrate"],[Fn]:["presentation.setClipboard"],[Vn]:["protocol.invoke"],[Bn]:["presentation.close"],[Gn]:["presentation.reload"],[Qn]:["presentation.openAppPage"],[Be]:["account.getCurrentUserId","account.onChange","network.request"],[be]:["account.onChange","network.request"],[Je]:["account.getCurrentUserId","account.onChange","network.request"],[mt]:["account.getCurrentUserId","account.onChange","network.request"],[Ue]:["account.onChange","network.request"],[kt]:["account.getCurrentUserId","account.onChange","network.request"],[xt]:["account.getCurrentUserId","account.onChange","network.request"],[jt]:["account.getCurrentUserId","account.onChange","network.request"],[gt]:["account.getCurrentUserId","account.onChange","network.request"],[ri]:["companion.getInfo"],[ni]:["companion.getPreparationStatus"],[ii]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[oi]:["companion.cancelPreparation"],[si]:["companion.getActiveSession"],[ai]:["companion.getInfo","companion.launch"],[ci]:["companion.session.write"],[di]:["companion.session.closeStdin"],[ui]:["companion.session.terminate"],[li]:["companion.session.ackOutput"],[fi]:["companion.openAttachment"],[hi]:["companion.showNotification"]};function Hl(e,t){if(t[e]!==!0)throw Ne(e)}const Fl=32*1024*1024,Vl=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Bl(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:Fl},i);return Gl(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Gl(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:Ql(t,ql(e,"content-type"))}}function Ql(e,t){Yl(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new ue("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!Vl.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function Yl(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new ue(`Host network response 不支持 charset=${t}`)}function ql(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function j(e){return typeof e=="function"}function Is(e){return(...t)=>{throw Ne(e)}}function ae(e){return async(...t)=>{throw Ne(e)}}const $l=(e,t)=>{},Wl=()=>()=>{};function Kl(e){const t={request:j(e.network?.request)?e.network.request.bind(e.network):ae("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):ae("account.getCurrentUserId"),ensureAuthenticated:j(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):ae("account.ensureAuthenticated"),onChange:j(e.account?.onChange)?e.account.onChange.bind(e.account):Wl},n={getRaw:j(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):ae("storage.getRaw"),setRaw:j(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):ae("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):ae("presentation.close"),reload:j(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):ae("presentation.reload"),openAppPage:j(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):ae("presentation.openAppPage"),openWindow:j(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):ae("presentation.openWindow"),getViewportMetrics:j(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Is("presentation.getViewportMetrics"),getNavigationBarHeight:j(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Is("presentation.getNavigationBarHeight"),setNavigationBarStyle:j(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):ae("presentation.setNavigationBarStyle"),showShareMenu:j(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):ae("presentation.showShareMenu"),setScreenshotChromeHidden:j(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):$l,captureAndShare:j(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):ae("presentation.captureAndShare"),showToast:j(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):ae("presentation.showToast"),showLoading:j(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):ae("presentation.showLoading"),hideLoading:j(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):ae("presentation.hideLoading"),vibrate:j(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):ae("presentation.vibrate"),setClipboard:j(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):ae("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):ae(`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):ae("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 Jl(e){const t=Zl(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.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 Zl(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 As(e,t){return t?.[e]!==!1}function Xl(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function Wc(e,t={}){const r={};for(const n of Object.keys(ws)){const o=ws[n].every(a=>e[a]),s=!Xl(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=As(n,t.callerCapabilities)&&As(n,t.hostCapabilities)&&o&&s}return r}function Kc(e={},t={}){const r=Jl(e),n=Wc(r,t);return{ports:Kl(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function ve(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):ef(e.signal,t);return{...e,signal:r}}function ef(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 tf(e){if(!e||typeof e!="object"||e.lifecycle!=="cleanup")return!1;const t=e.signal;return!!t&&typeof t=="object"&&typeof t.aborted=="boolean"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"}const rf=4,nf=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],of=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),sf=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],af=["/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 cf(e,t){const r=lf(e);return r===null||Ms(r,sf)?!0:t&&Ms(r,af)}function df(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return nf.some(r=>t===r||t.endsWith(`.${r}`))}function uf(e){const t=e.trim().toLowerCase();return of.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function lf(e){let t=e;for(let r=0;r<rf;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Ns(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Ns(t)}function Ms(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Ns(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function At(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Ds(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function Jc(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(A,T){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:A,type:T})).catch(()=>{})}catch{}}function u(A){const T=r.get(A);if(!T)throw new Error("Unknown runtime cache scope");return T}function f(A,T){return A.flatMap((M,b)=>{const S=JSON.stringify(A.slice(0,b+1));return[JSON.stringify([S]),JSON.stringify([S,T])]})}function l(A,T){return JSON.stringify(f(A,T).map(M=>n.get(M)??0))}async function h(A,T){const M=u(A),b=JSON.stringify([JSON.stringify(M),...T?[T]:[]]),S=(n.get(b)??0)+1;n.set(b,S),i.add(b);for(const R of a)R(M,T);if(!e.store){i.delete(b),d(T??"*","invalidation");return}try{await e.store.invalidate(M,T)}catch(R){throw d(T??"*","storage_error"),R}n.get(b)===S&&i.delete(b),d(T??"*","invalidation")}function w(A){if(c)throw new Error("Runtime cache manager disposed");const T=o.get(A.namespace);if(T){if(T.sourceCodec!==A.codec||T.definition.codec.version!==A.codec.version||JSON.stringify(T.definition.policy)!==JSON.stringify(A.policy))throw new Error("Conflicting runtime cache namespace");return T.cache}if(!A.namespace||!A.codec.version)throw new Error("Invalid runtime cache definition");const M=Object.freeze({...A.policy}),b=Object.freeze({version:A.codec.version,encode:A.codec.encode.bind(A.codec),decode:A.codec.decode.bind(A.codec),validate:A.codec.validate.bind(A.codec),clone:A.codec.clone.bind(A.codec)}),S=A.namespace;for(const C of[M.ttlMs,M.memoryMaxEntries,M.diskMaxEntries,M.diskMaxBytes,M.maxEntryBytes])if(!Number.isFinite(C)||C<0)throw new Error("Invalid runtime cache policy");const R=new Map,B=new Map,U=new Map;let p=!1;function m(C,N,O){if(c||p||C.aborted||l(N,S)!==O)throw At()}function I(C){return M.ttlMs>0&&M.persistence==="memory-and-disk"&&!!e.store&&!f(C,S).some(N=>i.has(N))}function y(C,N,O){const L=t();return C.envelopeVersion===1&&JSON.stringify(C.address)===JSON.stringify(N)&&Ds(C.revisions,O)&&C.payload.byteLength<=M.maxEntryBytes&&Number.isFinite(C.cachedAt)&&Number.isFinite(C.expiresAt)&&C.cachedAt<=L&&C.cachedAt>=0&&C.expiresAt>C.cachedAt&&Math.min(C.expiresAt,C.cachedAt+M.ttlMs)>L}function _(C,N,O,L,P){if(!(M.ttlMs<=0||M.memoryMaxEntries<1)){for(const[z,H]of R)Math.min(H.entry.expiresAt,H.entry.cachedAt+M.ttlMs)<=t()&&R.delete(z);for(R.delete(C);R.size>=Math.floor(M.memoryMaxEntries);){const z=R.keys().next();if(z.done)break;R.delete(z.value)}R.set(C,{entry:N,value:O,epoch:L,persistent:P})}}async function g(C,N,O,L){const P={namespace:S,codecVersion:b.version,scopeIds:N,key:C.key},z=JSON.stringify(P);let H=[],F=I(N);if(F)try{H=await e.store.readRevisions(N,S)}catch{F=!1,d(S,"storage_error")}m(L.signal,N,O);async function Q(){if(!F)return!0;try{return Ds(H,await e.store.readRevisions(N,S))}catch{return F=!1,d(S,"storage_error"),!1}}const J=R.get(z);if(M.ttlMs>0&&J&&J.epoch===O&&y(J.entry,P,H)&&J.persistent===F&&await Q())return m(L.signal,N,O),d(S,"memory_hit"),J.value;if(R.delete(z),F){let q,ce;try{q=await e.store.read(P,M.maxEntryBytes),q&&y(q,P,H)?ce=b.decode(q.payload):q=void 0}catch{q=void 0,d(S,"storage_error")}if(m(L.signal,N,O),q&&await Q())return m(L.signal,N,O),_(z,q,ce,O,!0),d(S,"disk_hit"),ce}d(S,"miss");const $=b.validate(await C.load(L.signal));m(L.signal,N,O);const X=b.clone($);if(!await Q()&&F)throw At();if(m(L.signal,N,O),M.ttlMs>0){const q=t();let ce;try{ce=b.encode(X)}catch{return X}const wt={envelopeVersion:1,address:P,revisions:F?H:[],cachedAt:q,expiresAt:q+M.ttlMs,payload:ce};if(F&&ce.byteLength<=M.maxEntryBytes){let ye=!0,Ae=!1;try{ye=await e.store.publish(wt,M),Ae=ye}catch{d(S,"storage_error")}if(m(L.signal,N,O),!ye)throw At();Ae&&d(S,"published")}m(L.signal,N,O),_(z,wt,X,O,F)}return X}async function D(C){if(c||p||C.signal?.aborted)return Promise.reject(At());const N=u(C.scope),O=l(N,S);let L;if(I(N)){const F=new AbortController;U.set(F,N);const Q=()=>F.abort();C.signal?.addEventListener("abort",Q,{once:!0});let J=()=>{};try{L=await Promise.race([e.store.readRevisions(N,S),new Promise(($,X)=>{const q=()=>X(At());F.signal.addEventListener("abort",q,{once:!0}),J=()=>F.signal.removeEventListener("abort",q)})])}catch{F.signal.aborted||d(S,"storage_error")}finally{J(),U.delete(F),C.signal?.removeEventListener("abort",Q)}}m(C.signal??new AbortController().signal,N,O);const P=JSON.stringify([N,C.key,O,L]);let z=B.get(P);if(z?.controller.signal.aborted&&(z=void 0),!z){const F=new AbortController;z={ids:N,controller:F,waiters:0,promise:Promise.resolve(void 0)};const Q=z;Q.promise=g(C,N,O,F).finally(()=>{B.get(P)===Q&&B.delete(P)}),B.set(P,Q)}const H=z;return H.waiters+=1,new Promise((F,Q)=>{let J=!1;function $(q){J||(J=!0,C.signal?.removeEventListener("abort",X),H.controller.signal.removeEventListener("abort",X),H.waiters-=1,H.waiters===0&&H.controller.abort(),q())}function X(){$(()=>Q(At()))}C.signal?.addEventListener("abort",X,{once:!0}),H.controller.signal.addEventListener("abort",X,{once:!0}),H.promise.then(q=>$(()=>{try{m(C.signal??new AbortController().signal,N,O),F(b.clone(q))}catch(ce){Q(ce)}}),q=>$(()=>Q(q)))})}function v(C,N){if(N&&N!==S)return;const O=L=>C.every((P,z)=>L[z]===P);for(const[L,P]of R)O(P.entry.address.scopeIds)&&R.delete(L);for(const[L,P]of B)O(P.ids)&&(P.controller.abort(),B.delete(L));for(const[L,P]of U)O(P)&&L.abort()}function k(){if(!p){p=!0,R.clear();for(const C of U.keys())C.abort();U.clear();for(const C of B.values())C.controller.abort();B.clear(),s.delete(k),a.delete(v),o.get(S)?.cache===x&&o.delete(S)}}const x={read:D,invalidateScope:C=>h(C,S),dispose:k};return s.add(k),a.add(v),o.set(S,{definition:{namespace:S,codec:b,policy:M},sourceCodec:A.codec,cache:x}),x}return{createScope(A,T){if(c||!A)throw new Error("Invalid runtime cache scope");const M=Object.freeze({});return r.set(M,[...T?u(T):[],A]),M},register:w,invalidateScope:A=>h(A),dispose(){if(!c){c=!0;for(const A of[...s])A();o.clear(),n.clear(),i.clear()}}}}function ff(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 hf=".hb-runtime-cache-v1",mf=1e3,Di=64*1024,Mt=1e3,gf=2048,Kt=32*1024*1024,pf=1024,Xr=new TextEncoder,Ss=new TextDecoder("utf-8",{fatal:!0});function Jt(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Br(e){const t=await globalThis.crypto.subtle.digest("SHA-256",Xr.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Re(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ts(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function yf(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 Ef(e,t){const r=e.sandbox.directory(hf),n=r.directory("revisions"),i=r.directory("entries");for(const g of[r,n,i,i.directory("capability-check")])_s(g,["directory","file","create","stat","list","remove"]),_s(g.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(g){d=g,o.abort(),t.signal.removeEventListener("abort",s)}function f(g){if(yf(g))throw u(g),g}function l(){if(d)throw d;if(a.signal.aborted)throw Jt()}function h(g,D=a.signal){const v=c.then(()=>{if(D.aborted)throw d??Jt();return l(),g()},()=>{if(D.aborted)throw d??Jt();return l(),g()}).catch(N=>{throw f(N),N});if(c=v.catch(()=>{}),D.aborted)return Promise.reject(d??Jt());let k=()=>{};const x=new Promise((N,O)=>{const L=()=>O(d??Jt());D.addEventListener("abort",L,{once:!0}),k=()=>D.removeEventListener("abort",L)}),C=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},mf);return Promise.race([v,x]).finally(()=>{clearTimeout(C),k()})}async function w(){l(),await n.create({recursive:!0,exclusive:!1},a),l(),await i.create({recursive:!0,exclusive:!1},a),l()}async function A(g,D){const v=n.file(`${await Br([g,D??null])}.revision`);await M(v);let k=!1;try{await v.create({recursive:!1,exclusive:!0},a),k=!0}catch(N){f(N),l()}if(k){const N=Ts();return await v.write(Xr.encode(N),a),l(),N}const x=await v.stat(a);if(x.size<1||x.size>128)throw new Error("缓存 revision 文件损坏");const C=Ss.decode(await v.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(C))throw new Error("缓存 revision 文件损坏");return l(),C}async function T(g){const D=await g.list({limit:Mt},a);if(D.length>=Mt)throw new Error("缓存目录超过治理上限");return D}async function M(g){try{await g.stat(a);return}catch(v){if(!Gr(v))throw v}if((await T(n)).length>=Mt-1)throw new Error("缓存 metadata 超过治理上限")}async function b(g,D){await w();const v=[];for(let k=0;k<g.length;k+=1){const x=g.slice(0,k+1);v.push(await A(x),await A(x,D))}return v}async function S(g){return r.directory(`entries/${await Br([g.namespace,g.codecVersion,g.scopeIds])}`)}async function R(g){return(await S(g)).file(`${await Br(g.key)}.cache`)}async function B(g,D){const v=await g.stat(a);if(v.size<5||v.size>D+Di+4)throw new Error("缓存条目超过大小限制");const k=await g.read(a);if(l(),k.length!==v.size)throw new Error("缓存条目读取不完整");const x=new DataView(k.buffer,k.byteOffset,k.byteLength).getUint32(0);if(x<1||x>Di||x+4>k.length)throw new Error("缓存信封损坏");const C=JSON.parse(Ss.decode(k.subarray(4,x+4))),N=k.slice(x+4);if(C.envelopeVersion!==1||!C.address||!Array.isArray(C.address.scopeIds)||!C.address.scopeIds.every(O=>typeof O=="string")||typeof C.address.namespace!="string"||typeof C.address.codecVersion!="string"||typeof C.address.key!="string"||!Array.isArray(C.revisions)||C.revisions.length!==C.address.scopeIds.length*2||!C.revisions.every(O=>typeof O=="string"&&O.length>0)||!Number.isSafeInteger(C.cachedAt)||!Number.isSafeInteger(C.expiresAt)||C.cachedAt<0||C.expiresAt<=C.cachedAt||C.payloadBytes!==N.length||N.length>D)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:C.address,revisions:C.revisions,cachedAt:C.cachedAt,expiresAt:C.expiresAt,payload:N}}async function U(g){if(!g.remove)throw new Error("Host 不支持缓存文件删除");await g.remove(a)}async function p(g){try{if((await g.file.stat(a)).size!==g.size)return!1;const D=await B(g.file,Kt);return!Re(D.address,g.entry.address)||!Re(D.revisions,g.entry.revisions)||D.cachedAt!==g.entry.cachedAt||D.expiresAt!==g.entry.expiresAt||!Re(await m(D.payload),await m(g.entry.payload))?!1:(await U(g.file),!0)}catch(D){if(Gr(D))return!0;throw D}}async function m(g){const D=await globalThis.crypto.subtle.digest("SHA-256",g);return Array.from(new Uint8Array(D),v=>v.toString(16).padStart(2,"0")).join("")}async function I(){const g=await T(n);let D=0;for(const C of g)if(C.kind==="file"&&(D+=(await C.stat(a)).size,D>Kt))throw new Error("缓存扫描超过字节上限");const v=[];let k=0,x=D;for(const C of await T(i)){if(C.kind!=="directory")throw new Error("缓存目录结构损坏");for(const N of await T(C)){if(N.kind!=="file"||++k>gf)throw new Error("缓存文件超过治理上限");const O=(await N.stat(a)).size;if(x+=O,x>Kt)throw new Error("缓存扫描超过字节上限");try{const L=await B(N,Kt);v.push({file:N,entry:L,size:(await N.stat(a)).size,bucketName:C.name})}catch(L){f(L),l(),Gr(L)||await U(N)}}}return{entries:v,metadataBytes:D}}async function y(){for(const g of await T(i))if(g.kind==="directory"&&g.remove&&(await T(g)).length===0)try{await g.remove({recursive:!1},a)}catch(D){f(D),l()}}function _(g){const{payload:D,...v}=g,k=Xr.encode(JSON.stringify({...v,payloadBytes:D.length}));if(k.length>Di)throw new Error("缓存信封过大");const x=new Uint8Array(4+k.length+D.length);return new DataView(x.buffer).setUint32(0,k.length),x.set(k,4),x.set(D,k.length+4),x}return{readRevisions:(g,D)=>h(()=>b(g,D)),read:(g,D)=>h(async()=>{l();const v=await R(g);let k;try{k=await B(v,D)}catch(x){if(l(),Gr(x))return;throw x}if(!(!Re(k.address,g)||k.expiresAt<=Date.now())&&Re(k.revisions,await b(g.scopeIds,g.namespace)))return k}),publish:(g,D)=>h(async()=>{l();const{address:v}=g;if(!Re(g.revisions,await b(v.scopeIds,v.namespace)))return!1;const k=_(g);if(g.payload.length>D.maxEntryBytes||k.length>D.diskMaxBytes||D.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await w();const x=await S(v),C=await R(v),N=await I(),O=[],L=new Map;for(const H of N.entries){if(H.bucketName===x.name&&H.file.name===C.name)continue;const F=JSON.stringify([H.entry.address.scopeIds,H.entry.address.namespace]);let Q=L.get(F);if(Q||(Q=await b(H.entry.address.scopeIds,H.entry.address.namespace),L.set(F,Q)),H.entry.expiresAt<=Date.now()||!Re(H.entry.revisions,Q)){if(!await p(H))throw new Error("缓存治理期间条目已变化")}else O.push(H)}O.sort((H,F)=>H.entry.cachedAt-F.entry.cachedAt);function P(){const H=O.filter(F=>F.bucketName===x.name);return O.length+1>pf||k.length+N.metadataBytes+O.reduce((F,Q)=>F+Q.size,0)>Kt||H.length+1>Math.min(D.diskMaxEntries,Mt-1)||k.length+H.reduce((F,Q)=>F+Q.size,0)>D.diskMaxBytes}for(;P();){const H=O.filter(J=>J.bucketName===x.name),Q=H.length+1>Math.min(D.diskMaxEntries,Mt-1)||k.length+H.reduce((J,$)=>J+$.size,0)>D.diskMaxBytes?H[0]:O[0];if(!Q||!await p(Q))throw new Error("缓存容量不足或条目已变化");O.splice(O.indexOf(Q),1)}await y();const z=await T(i);if(!z.some(H=>H.name===x.name)&&z.length>=Mt-1)throw new Error("缓存目录超过治理上限");if(await x.create({recursive:!0,exclusive:!1},a),!Re(g.revisions,await b(v.scopeIds,v.namespace)))return!1;try{await C.create({recursive:!1,exclusive:!0},a)}catch(H){f(H),await C.stat(a)}return await C.write(k,a),l(),Re(g.revisions,await b(v.scopeIds,v.namespace))}),invalidate:(g,D)=>h(async()=>{await w();const v=n.file(`${await Br([g,D??null])}.revision`);await M(v);try{await v.create({recursive:!1,exclusive:!0},a)}catch(k){f(k),await v.stat(a)}await v.write(Xr.encode(Ts()),a),l();try{const{entries:k}=await I();for(const x of k){if(D!==void 0&&x.entry.address.namespace!==D||!g.every((N,O)=>x.entry.address.scopeIds[O]===N))continue;const C=await b(x.entry.address.scopeIds,x.entry.address.namespace);Re(x.entry.revisions,C)||await p(x)}await y()}catch(k){f(k),l()}})}}function Gr(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const wf="RATE_LIMITED_BY_RUNTIME",If="RATE_LIMITED",Zc=20,Xc=40,ed=150,td=20,rd=1e4,nd=45e3,id=1,Af=300*1e3,Mf=64;function Nt(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Nf(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Df(e={}){const t=e.now??Date.now,r=Nf(e.coalesceWindowMs,ed),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,Nt(e.budget?.ratePerSecond,Zc)),burst:Math.max(1,Math.floor(Nt(e.budget?.burst,Xc)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(Nt(e.loopDetection?.maxCalls,td))),windowMs:Math.max(1,Math.floor(Nt(e.loopDetection?.windowMs,rd)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(Nt(e.circuitBreaker?.failureThreshold,id))),openMs:Math.max(1,Math.floor(Nt(e.circuitBreaker?.openMs,nd)))},s=new Map,a=new Map,c=new Set,d=new Map,u=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},f={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let l=!1;function h(p){try{e.onReport?.(p)}catch{}}function w(p,m){if(!i)return{exceeded:!1,count:0};const I=a.get(p)??[],y=m-i.windowMs;let _=0;for(;_<I.length&&I[_]<=y;)_+=1;_>0&&I.splice(0,_);const g=I.length>=i.maxCalls;return g||(I.push(m),I.length>i.maxCalls+1&&I.splice(0,I.length-(i.maxCalls+1))),a.set(p,I),{exceeded:g,count:I.length}}function A(p){if(!n)return!0;const m=Math.max(0,p-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+m*n.ratePerSecond),u.updatedAt=p,u.tokens<1?!1:(u.tokens-=1,!0)}function T(p){if(!n)return 0;const m=Math.max(0,p-u.updatedAt)/1e3,I=Math.min(n.burst,u.tokens+m*n.ratePerSecond);return Math.max(0,Math.ceil((1-I)/n.ratePerSecond*1e3))}function M(p,m,I,y,_){if(!o)return;const g=d.get(m),D=(g?.open?0:g?.failures??0)+1;if(D<o.failureThreshold){d.set(m,{open:!1,openedAt:0,openMs:0,failures:D});return}const v=Math.min(Math.max(o.openMs,y),Af);d.set(m,{open:!0,openedAt:_,openMs:v,failures:D}),f.circuitOpened+=1,h({type:"circuit_opened",capability:p,endpointId:m,status:I,openMs:v,timestamp:_})}function b(p){const m=d.get(p);m&&!m.open&&d.delete(p)}function S(p){for(const[m,I]of s)!I.pending&&I.expiresAt<=p&&s.delete(m);for(;s.size>=Mf;){const m=[...s].find(([,I])=>!I.pending);if(!m)break;s.delete(m[0])}}function R(p,m){if(p===void 0)return;const I=s.get(p);I?.promise===m&&(I.pending=!1)}function B(p,m){if(p===void 0)return;s.get(p)?.promise===m&&s.delete(p)}async function U(p){if(l)return p.load();const m=t();if(o){const g=d.get(p.endpointId);if(g?.open){const D=g.openedAt+g.openMs-m;if(D>0)throw f.circuitRejected+=1,h({type:"circuit_rejected",capability:p.capability,endpointId:p.endpointId,retryAfterMs:D,timestamp:m}),_f("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:p.endpointId,retryAfterMs:D});d.delete(p.endpointId)}}const I=w(p.endpointId,m);I.exceeded&&i?c.has(p.endpointId)||(c.add(p.endpointId),h({type:"loop_detected",capability:p.capability,endpointId:p.endpointId,count:I.count,windowMs:i.windowMs,timestamp:m})):c.delete(p.endpointId);const y=r>0?p.coalesceKey:void 0;if(y!==void 0){const g=s.get(y);if(g&&(g.pending||g.expiresAt>m))return f.coalesced+=1,h({type:"coalesced",capability:p.capability,endpointId:p.endpointId,timestamp:m}),g.promise;g&&s.delete(y)}if(I.exceeded&&i)throw f.loopRejected+=1,bs("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:p.capability,endpointId:p.endpointId,count:I.count,windowMs:i.windowMs});if(!A(m)){f.budgetRejected+=1;const g=T(m);throw h({type:"budget_exhausted",capability:p.capability,endpointId:p.endpointId,retryAfterMs:g,timestamp:m}),bs("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:p.capability,endpointId:p.endpointId,retryAfterMs:g})}y!==void 0&&S(m);const _=p.load().then(g=>(R(y,_),b(p.endpointId),g),g=>{B(y,_);const D=Sf(g);throw D!==void 0&&M(p.capability,p.endpointId,D,Tf(g),m),g});return y!==void 0&&s.set(y,{endpointId:p.endpointId,promise:_,expiresAt:m+r,pending:!0}),_}return{execute:U,invalidateCoalescing(p){if(p===void 0){s.clear();return}for(const[m,I]of s)p.includes(I.endpointId)&&s.delete(m)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,p])=>p.open).map(([p])=>p)}},dispose(){l||(l=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function Sf(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 Tf(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 bs(e,t){return{code:wf,message:e,data:t}}function _f(e,t){return{code:If,message:e,data:t}}const od=3e4,sd=6e4,go=1440*60*1e3;function bf(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??od)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??sd)):0,steamGameListTtlMs:t?Of(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:Zc,burst:Xc},coalesceWindowMs:r?.coalesceWindowMs??ed,loopDetection:r?.loopDetection??{maxCalls:td,windowMs:rd},circuitBreaker:r?.circuitBreaker??{failureThreshold:id,openMs:nd}}}}function Of(e){return e===void 0||!Number.isFinite(e)?go:Math.max(0,Math.floor(e))}function E(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function G(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vf(e){return typeof e=="object"&&e!==null}function le(e,t){const r=e.data;if(!vf(r)||typeof r.status!="string")throw new Error(t);return r}const ad={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Cf={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 le(e,"工坊小程序详情加载失败")}};function Pr(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Lf(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Rf(e){const t=le(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=Lf(r.consent_challenge)),{...t,result:n}}const Pf={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=>({...Pr(e.runtimeContext),challenge:e.challenge}),parse:e=>le(e,"小程序授权取消接口响应异常")},kf={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=>Pr(e.runtimeContext),parse:e=>le(e,"小程序授权撤销接口响应异常")},xf={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=>Pr(e.runtimeContext),parse(e){const t=le(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}:{}}}}},jf={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=>({...Pr(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Rf(e)},Uf={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=>({...Pr(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=le(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},zf=64;function cd(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??zf)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(f){for(const[l,h]of i)h.expiresAt<=f&&i.delete(l)}function d(f,l,h){if(a||t<=0||h!==s)return;const w=n();for(c(w),i.delete(f);i.size>=r;){const A=i.keys().next();if(A.done)break;i.delete(A.value)}i.set(f,{expiresAt:w+t,value:l})}function u(f,l){if(a)return l();if(t>0){const T=i.get(f);if(T&&T.expiresAt>n())return Promise.resolve(T.value);T&&i.delete(f)}const h=o.get(f);if(h)return h;const w=s,A=l().then(T=>(d(f,T,w),T)).finally(()=>{o.get(f)===A&&o.delete(f)});return o.set(f,A),A}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 Hf(e,t){return t?e?"server":"local":"legacy"}function Ff(e,t){if(e==="local")throw E("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const Vf=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],Bf=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Gf=/authorization|cookie|pkey|password|secret|token/i,dd=/authorization|cookie|pkey|token|password|secret/i;function Pe(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Qf(e){for(const t of Object.keys(e))if(!Bf.has(t))throw new ue(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of Vf)if(Object.prototype.hasOwnProperty.call(e,t)&&Pe(e,t)!==void 0)throw new ue(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Pe(e,"bodyEncoding")!==void 0&&Pe(e,"bodyEncoding")!=="json"&&Pe(e,"bodyEncoding")!=="form")throw new ue("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Pe(e,"failurePresentation")!==void 0&&Pe(e,"failurePresentation")!=="none")throw new ue("endpoint failurePresentation 必须为 none");if(Pe(e,"auth")!==void 0&&Pe(e,"auth")!=="none"&&Pe(e,"auth")!=="optional"&&Pe(e,"auth")!=="required")throw new ue("endpoint auth 必须为 none、optional 或 required")}function cr(e){if(Array.isArray(e))return e.map(cr);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Gf.test(n)||(r[n]=cr(i));return r}function Os(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))dd.test(r)||(t[r]=n);return t}function Yf(e){if(!e)return;const t=Object.keys(e).find(r=>dd.test(r));if(t)throw new ue(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Ht 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,t.retryAfterMs!==void 0&&(this.retryAfterMs=t.retryAfterMs),Object.setPrototypeOf(this,new.target.prototype)}}const vs=1440*60*1e3,qf=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function $f(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,vs):void 0}if(!qf.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,vs):void 0}function Wf(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 Ft 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 kr 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 Kf(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:cr(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Os(o),method:e.method,metadata:{endpointId:e.id},query:cr(n),timeout:e.timeout,url:r},data:cr(a.data),headers:Os(a.headers)||{},status:a.status,statusText:a.statusText}}async function mi(e,t,r,n){if(!n||!n.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(n.credentials!=="heybox-session"&&n.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(Qf(t),typeof t.id!="string"||!t.id)throw new ue("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new ue("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new ue("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;Yf(a);const c=async()=>{let f;try{f=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...o===void 0?{}:{params:o},...s===void 0?{}:{data:s},...a===void 0?{}:{headers:a},credentials:n.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:n.signal,...n.miniProgramDetail===void 0?{}:{miniProgramDetail:n.miniProgramDetail}})}catch(h){throw h instanceof ue?h:new Ft({endpointId:t.id,cause:h})}if(f.status<200||f.status>=300)throw new Ht({endpointId:t.id,status:f.status,retryAfterMs:$f(f.headers)});const l=Kf(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(l,r)}catch(h){throw new kr({endpointId:t.id,cause:h})}return l.data},d=n.gate;if(!d)return c();const u=Wf(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const Jf=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),Zf=new Set(zt),qo="steam_account",ld=new Set(zt.filter(e=>e!==qo)),Xf=1e3;function eh(e){const t=new Set,r=cd({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??od))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??Hf(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 E("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let N;try{N=await e.authorizationContext.get(e.operationContext)}catch(L){throw yo(L)?Si(L.code,L.message,L):Si("REQUEST_FAILED","读取 Runtime auth context 失败",L)}if(N.steamAccount!==c||N.userDataMode!==d)throw E("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const O=N.token.trim();if(!O)throw E("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:O}}const h=e.account.onChange(N=>{if(w(),A("heybox_app_login_change",N?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),N&&e.account.getAccountKey){const O=i;B().then(L=>{!o&&i===O&&A("heybox_app_login_change",L)}).catch(()=>{})}});function w(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function A(N,O){N==="user_info_authorization_change"&&sh(O)&&r.invalidate();for(const L of t)try{L(N,O)}catch{}}function T(){const N=e.identity.get()?.miniProgramId?.trim();if(!N)throw E("INVALID_STATE","当前能力缺少 canonical 小程序身份");return N}function M(){if(o||e.operationContext.signal.aborted)throw E("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function b(){M();let N;try{N=await e.account.getCurrentUserId(e.operationContext)}catch(O){throw Ps(O,e.operationContext.signal,"读取小黑盒账号失败")}return typeof N=="string"&&N.trim()?N.trim():void 0}async function S(N,O){const L=await b();if(i!==O||L!==N)throw E("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function R(N,O,L=T()){if(!e.account.getAccountKey)throw E("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let P;try{P=await e.account.getAccountKey(L,N,e.operationContext)}catch{throw M(),E("REQUEST_FAILED","读取本地账号标识失败")}if(await S(N,O),T()!==L)throw E("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof P!="string"||!P.trim())throw E("INVALID_RESPONSE","Host 返回了无效的账号标识");return P}async function B(){const N=T(),O=i,L=await b();if(M(),i!==O)throw E("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return L?{isHeyboxAppLoggedIn:!0,accountKey:await R(L,O,N)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function U(N){M();try{await e.account.ensureAuthenticated({trustedUserGesture:N,reason:"runtime_auth",signal:e.operationContext.signal})}catch(L){throw Ps(L,e.operationContext.signal,"小黑盒登录失败")}const O=await b();if(!O)throw E("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return O}async function p(N,O,L=e.operationContext.signal){try{if(L.aborted)throw po();return await oh(mi(e.network,N,O,{...e.operationContext,credentials:"heybox-session",signal:L,...f?{gate:f}:{}}),L)}catch(P){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):P instanceof ue?E("REQUEST_UNSUPPORTED",P.message):P instanceof kr?E("INVALID_RESPONSE","授权接口响应不合法"):P instanceof Ft?E("REQUEST_FAILED","授权请求失败"):P instanceof Ht?u&&(P.status===403||P.status===429)?E("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:P.status,...P.retryAfterMs===void 0?{}:{retryAfterMs:P.retryAfterMs}}):E("REQUEST_FAILED",P.message):yo(P)?P:E("REQUEST_FAILED","授权请求失败")}}async function m(N,O){await p(Pf,{runtimeContext:{miniProgramId:N,...await l()},challenge:O}).catch(()=>{})}function I(N){const O=async()=>{const P=Ls(e.operationContext.signal);a=P;try{return await N(P.signal)}finally{a===P&&(a=void 0),P.abort()}},L=s.then(O,O);return s=L.then(()=>{},()=>{}),L}async function y(N,O,L,P,z){if(!L)throw await m(N,O.challenge),E("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await m(N,O.challenge),E("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return I(async H=>{await S(P,z);const F=await _(N,O.displayedScopes,H);await S(P,z);let Q;try{Q=await e.authPresentation.confirmAuthorization({miniProgramId:N,scopes:O.displayedScopes,...F,signal:H})}catch($){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await S(P,z),await m(N,O.challenge),Si("REQUEST_FAILED","授权确认界面执行失败",$))}if(await S(P,z),Q.status!=="granted")throw await m(N,O.challenge),E("AUTHORIZATION_CANCELLED","用户取消授权");const J=nh(Q.grantedScopes,O.displayedScopes,c);if(!J.includes("identity"))throw await m(N,O.challenge),E("AUTHORIZATION_CANCELLED","用户拒绝授权");return J})}async function _(N,O,L){const P=Ls(L),z=setTimeout(()=>P.abort(),Xf);try{const H=ih(e.miniProgramPresentation),[F,Q]=await Promise.all([H?Promise.resolve(H):g(N,P.signal),O.includes("profile")?D(P.signal):Promise.resolve(void 0)]);return{...F?{miniProgram:F}:{},...Q?{userProfile:Q}:{}}}finally{clearTimeout(z),P.abort()}}async function g(N,O){try{const L=e.identity.get()?.version?.trim(),P=await p(Cf,{mini_program_id:N,...L?{miniprogram_version:L}:{}},O),z=Dt(P,"小程序公开资料"),H=Ct(z.name),F=Ct(z.icon_url);return H||F?{...H?{name:H}:{},...F?{avatarUrl:F}:{}}:void 0}catch{return}}async function D(N){try{const O=await p(ad,void 0,N),L=Dt(O,"账号基础信息"),P=Ct(L.display_username),z=Ct(L.display_avatar);return P||z?{...P?{nickname:P}:{},...z?{avatar:z}:{}}:void 0}catch{return}}async function v(N,O){if(Ff(d,"auth.login"),!c&&N.includes(qo))throw E("INVALID_PARAMS","auth.login 参数不合法");const L=T(),P=await U(O),z=i,H=await p(jf,{runtimeContext:{miniProgramId:L,...await l()},scopes:N});await S(P,z);const F=Dt(H,"小程序登录"),Q=Rs(F,"loginCode"),J=Rs(F,"consentChallenge");if(Q===J)throw E("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let $;if(Q)$=Cs(F.loginCode,c);else{const q=th(F.consentChallenge,c),ce=await y(L,q,O,P,z);await S(P,z);const wt=await p(Uf,{runtimeContext:{miniProgramId:L,...await l()},challenge:q.challenge,selectedScopes:ce});if(await S(P,z),$=Cs(Dt(wt,"小程序登录确认"),c),$.scopes.some(ye=>!ce.includes(ye)))throw E("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const q of $.scopes)n.add(q);r.invalidate();const X=e.account.getAccountKey?await R(P,z,L):void 0;return A("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...X===void 0?{}:{accountKey:X}}),A("user_info_authorization_change",Ti(n,c)),{...$,...X===void 0?{}:{accountKey:X}}}async function k(N,O){const L=i,P=await p(xf,{runtimeContext:{miniProgramId:O,...await l()}});await S(N,L);const z=rh(Dt(P,"用户本地身份"),c);for(const H of c?zt:ld)n.add(H);return A("user_info_authorization_change",Ti(n,c)),z}function x(N){M();const O=T(),L=`${N}\0${O}\0${i}\0${c}`;return r.read(L,()=>k(N,O))}async function C(N){if(!N)throw E("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const O=T(),L=i,P=await b();if(!P)throw E("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const z=await p(kf,{runtimeContext:{miniProgramId:O,...await l()}});await S(P,L),Dt(z,"用户授权撤销"),w(),A("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:B,login:v,async confirmGameSaves(N){if(!N)throw E("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw E("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const O=T(),L=await U(N),P=i;await I(async z=>{await S(L,P);const H=await _(O,["identity"],z),F=await e.authPresentation.confirmAuthorization({miniProgramId:O,scopes:["identity","game_saves"],...H,signal:z});if(await S(L,P),F.status!=="granted"||!F.grantedScopes.includes("game_saves")||!F.grantedScopes.includes("identity"))throw E("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:x,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Ti(n,c),revoke:C,onEvent(N){return t.add(N),()=>t.delete(N)},dispose(){o||(o=!0,w(),r.dispose(),h(),t.clear())}}}function Si(e,t,r){const n=E(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function Dt(e,t){if(!G(e))throw E("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":Jf.has(r)?r:"REQUEST_FAILED";throw E(n,r)}if(!G(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Cs(e,t){if(!G(e))throw E("INVALID_RESPONSE","login code 必须是对象");const r=Yn(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 E("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function th(e,t){if(!G(e))throw E("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Yn(e.requestedScopes,"challenge requestedScopes",t),n=Yn(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 E("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function rh(e,t){if(!G(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw E("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw E("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 nh(e,t,r){const n=Yn(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw E("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Ct(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function ih(e){const t=Ct(e?.name),r=Ct(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Ls(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 oh(e,t){return t.aborted?Promise.reject(po()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(po()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function po(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Yn(e,t,r){const n=r?Zf:ld;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw E("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Ti(e,t){const r=t?zt:zt.filter(n=>n!==qo);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function Rs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function sh(e){return G(e)?Object.values(e).some(t=>t==="denied"):!1}function yo(e){return G(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Ps(e,t,r){return t.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):yo(e)?e:E("REQUEST_FAILED",r)}const ah=new Set(zt);function ch(e){return{[gn]:async t=>{if(t!==void 0)throw E("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[pn]:async(t,r)=>e.authorization.login(dh(t),r.trustedUserGesture)}}function dh(e){if(e===void 0)return["identity"];if(!G(e)||Object.keys(e).some(t=>t!=="scopes"))throw ks();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!ah.has(t))||new Set(e.scopes).size!==e.scopes.length)throw ks();return[...e.scopes]}function ks(){return E("INVALID_PARAMS","auth.login 参数不合法")}const uh={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 le(e,"排行榜记录删除接口响应异常")}},lh={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 le(e,"当前排行榜记录接口响应异常")}},fh={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 le(e,"排行榜信息接口响应异常")}},hh={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 le(e,"排行榜列表接口响应异常")}},mh={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 le(e,"排行榜提交接口响应异常")}};function en(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function W(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:en()}function xs(e){return e instanceof ue?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function K(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(en());let n;try{n=e()}catch(i){return Promise.reject(xs(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(en())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(en()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(xs(d))))})}const gh={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 $o(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await K(()=>mi(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if($n(i)||ir(i,"REQUEST_UNSUPPORTED")||ir(i,"RATE_LIMITED")||ir(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof ue)throw V("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof Ft&&ir(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Ht){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw V("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw V("UNAUTHORIZED","当前用户未登录")}throw i instanceof Ft||i instanceof Ht?qn(e.subject):i instanceof kr?te(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):te(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function ze(e,t,r){if(!ie(e)||typeof e.status!="string")throw te(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw ph(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw te(`${t} 响应缺少 result`);return e.result}function Wo(e,t){try{return e.onChange(t)}catch(r){if(ir(r,qc))return()=>{};throw r}}function ph(e,t){if(e.status==="login"||e.status==="relogin")throw V("UNAUTHORIZED",nr(e.msg)||"当前用户未登录");const r=js(e.result)??js(e),n=nr(r?.user_message)||nr(e.msg)||nr(r?.developer_message)||`${t}请求失败`;throw r?V(yh(r),n,{status:e.status,sbe:r}):V("HEYBOX_API_ERROR",n,{status:e.status})}function js(e){return ie(e)&&ie(e.sbe)?e.sbe:void 0}function yh(e){const t=nr(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 gh[r]||t||"HEYBOX_API_ERROR";if(typeof r=="string"){const n=/^([A-Za-z][A-Za-z0-9_]*)(?:\(\d+\))?$/.exec(r.trim());if(n?.[1])return n[1]}return t||"HEYBOX_API_ERROR"}function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nr(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function ir(e,t){return ie(e)&&e.code===t}function V(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function te(e){return V("INVALID_RESPONSE",e)}function qn(e){return V("REQUEST_FAILED",`${e}请求失败`)}function $n(e){return e instanceof Error&&e.name==="AbortError"}const Eh="default",nt="排行榜",wh=/^[A-Za-z0-9_-]{1,64}$/,Ih=300*1e3,Ah=250,Mh=3;class Nh{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Wo(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(mh,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=ze(i,Be,nt);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),_i(o,Be)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Zt("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(hh,{miniProgramId:r,...t}),s=ze(o,be,nt);if(!ie(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw te(`${be} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw te(`${be} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>_i(a,be)),...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=Zt("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(lh,{miniProgramId:n,...t}),c=ze(a,Je,nt);if(!ie(c))throw te(`${Je} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:_i(c.entry,Je)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(uh,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=ze(i,mt,nt);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!ie(o)||typeof o.deleted!="boolean")throw te(`${mt} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Zt("info"),async()=>{const i=await this.request(fh,{miniProgramId:r,...t}),o=ze(i,Ue,nt);if(!ie(o)||typeof o.key!="string"||!wh.test(o.key))throw te(`${Ue} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw te(`${Ue} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw te(`${Ue} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw te(`${Ue} 返回的 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=Zt(t,n),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,f=o?.generation,l=i().then(h=>(this.assertAccountGeneration(u),o&&s&&o.generation===f&&(r==="list"?s.size>=Ah&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Ih,value:h})),h)).finally(()=>{this.inflight.get(c)?.promise===l&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:l}),l}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=Mh)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)Us(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){Us(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 K(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw $n(n)?n:qn(nt)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw V("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw V("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Zt(t,r??Eh)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw V("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return $o({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:nt,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(W(this.options.operationContext.signal),this.disposed)throw V("INVALID_STATE","Cloud capability 已释放")}}function Dh(e){return new Nh(e)}function _i(e,t){if(!ie(e))throw te(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw te(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw te(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw te(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw te(`${t} 返回的 score 必须是有限数字`);if(!ie(e.extra))throw te(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw te(`${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 Us(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Zt(...e){return JSON.stringify(e)}const Sh={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 le(e,"云端存储删除接口响应异常")}},zs={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 le(e,"云端存储读取接口响应异常")}},Hs={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 le(e,"云端存储 key 列表接口响应异常")}},Th={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 le(e,"云端存储写入接口响应异常")}},it="云端存储",_h=3e4,bh=128,Oh=500;class vh{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Wo(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=ze(await this.request(Hs,{}),gt,it);if(this.assertAccountGeneration(t),!ie(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw te("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"?Oh: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=ze(await this.request(Sh,{key:t}),jt,it);if(this.assertAccountGeneration(r.generation),!ie(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw te("删除结果不合法");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 te("云存储版本超出安全整数范围");const o=ze(await this.request(Th,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),xt,it);if(this.assertAccountGeneration(r.generation),!ie(o)||o.success!==!0)throw te("云存储写入结果不合法");const s=Fs({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw te("写入版本凭证不匹配");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(zs,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=Fs(ze(c,kt,it));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>=bh&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+_h,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([zs.id,Hs.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(V("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(V("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 K(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw $n(o)?o:qn(it)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),V("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),V("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw V("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw V("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw V("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw V("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await K(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw $n(s)?s:qn(it)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw V("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return $o({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:it,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(W(this.options.operationContext.signal),this.disposed)throw V("INVALID_STATE","Cloud capability 已释放")}}function Ch(e){return new vh(e)}function Fs(e){if(!ie(e))throw te("云存储读取结果必须是对象");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 te("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw te("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const Lh=/^[A-Za-z0-9_-]{1,64}$/,Vs=20,Rh=100,Bs=2048,Ph=/^[A-Za-z0-9_-]{1,128}$/,Gs=16*1024;function kh(e){const t=Dh(e),r=Ch(e);return{handlers:{[Be]:async i=>t.submit(xh(i)),[be]:async i=>t.getList(jh(i)),[Je]:async i=>t.getCurrentUserEntry(bi(i,Je)),[mt]:async i=>t.deleteCurrentUserEntry(bi(i,mt)),[Ue]:async i=>t.getInfo(bi(i,Ue)),[kt]:async i=>r.getItem(Qs(i,kt)),[xt]:async i=>{const{key:o,value:s}=Uh(i);return r.setItem(o,s)},[jt]:async i=>r.removeItem(Qs(i,jt)),[gt]:async i=>(Hh(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function xh(e){const t=qt(e,Be,!1);if($t(t,["key","score","extra"],Be),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw pe("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Ko(t.key,Be),score:t.score,...t.extra===void 0?{}:{extra:Fh(t.extra)}}}function jh(e){if(e===void 0)return{limit:Vs};const t=qt(e,be,!0);$t(t,["key","limit","cursor"],be);const r=t.limit===void 0?Vs:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>Rh)throw pe("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw pe("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Ko(t.key,be),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function bi(e,t){if(e===void 0)return{};const r=qt(e,t,!0);return $t(r,["key"],t),Ko(r.key,t)}function Qs(e,t){const r=qt(e,t,!1);return $t(r,["key"],t),fd(r.key,t)}function Uh(e){const t=xt,r=qt(e,t,!1);$t(r,["key","value"],t);const n=fd(r.key,t);if(typeof r.value!="string")throw pe("INVALID_PARAMS",`${t} value 必须是字符串`);if(zh(r.value))throw pe("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>Gs)throw pe("INVALID_PARAMS",`${t} value 不能超过 ${Gs} 字节`);return{key:n,value:r.value}}function zh(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 Hh(e){const t=qt(e,gt,!0);$t(t,[],gt)}function fd(e,t){if(typeof e!="string"||!Ph.test(e))throw pe("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function qt(e,t,r){if(e===void 0&&r)return{};if(!hd(e))throw pe("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function $t(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw pe("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Ko(e,t){if(e===void 0)return{};if(typeof e!="string"||!Lh.test(e))throw pe("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function Fh(e){if(!hd(e))throw pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>Bs)throw pe("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${Bs} 字节`);return e}function hd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pe(e,t){return{code:e,message:t}}const Vh={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 le(e,"游戏存档接口响应异常")}};function md(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw E("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 E("FILE_IO_FAILED","无法生成安全文件标识")}}function gd(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):Eo,remove:o?s=>e.remove(s):yd,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Eo,stat:s=>e.stat(s)})}function pd(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=>gd(e.file(a),n,{allowRemove:o}),directory:a=>pd(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Eo,remove:s?(a,c)=>e.remove(a,c):yd,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Eo(){return Promise.reject(E("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function yd(){return Promise.reject(E("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Bh=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"]),Gh={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 Sr(e){const t=Jo(e),r=t&&Bh.has(t)?E(t,Gh[t]??"文件操作失败"):E("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Ve(e){try{return e()}catch(t){throw Sr(t)}}function Jo(e){try{if(!G(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Ys=1024;class Zo{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new Zo(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 Qr(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Ve(()=>{if(!Array.isArray(t))throw E("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw E("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>Ys)throw E("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw E("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>Qr(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 $s(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Ut(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!Ut(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Yh(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Tr(r.relativePath);Oi(n.origin,i);const o=this.prepareFile(Ve(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=qh(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==="."?".":Tr(r.relativePath);Oi(n.origin,i);const o=this.prepareDirectory(i==="."?n.hostHandle:Ve(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Ks(t),Qr(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Ve(()=>{if(!Array.isArray(r))throw E("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw E("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw E("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&G(a)&&typeof a.name=="string"&&Ed(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Ve(()=>{if(G(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Qr(n.handle,qs(t.ref,n.handle.name))}if(G(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return $s(n.handle,Qh(t.ref,n.handle.name))}throw E("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=xr(r);Oi(t.origin,n);const i=this.prepareFile(Ve(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:qs(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw E("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Ve(()=>{Ks(t);const i=n??t.mode;return Ws(t.mode,i),{handle:gd(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Ve(()=>{Wh(t,i);const o=n??t.mode;return Ws(t.mode,o),{handle:pd(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Ys)throw E("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=md();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw E("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!$h(t))throw E("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw E("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw E("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Ne("files.sandbox");return this.prepareDirectory(Ve(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw E("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Ne("files")}}function Tr(e){if(!Go(e))throw E("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Oi(e,t){if(e==="sandbox"&&Ed(t))throw E("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function Ed(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function xr(e,t="文件名"){const r=Tr(e);if(r.includes("/"))throw E("INVALID_PARAMS",`${t} 只能是 basename`);return r}function qs(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Tr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Qh(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Tr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Qr(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function $s(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Ws(e,t){if(t==="readwrite"&&e!=="readwrite")throw E("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Yh(e){return Ut(e)||wd(),e}function qh(e){return Uc(e)||wd(),e}function wd(){throw E("INVALID_PARAMS","文件引用不合法")}function $h(e){return/^[0-9a-f]{32}$/.test(e)}function Ks(e){if(!G(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 E("FILE_IO_FAILED","Host 返回了无效 File handle");xr(e.name,"Host File name")}function Wh(e,t=!1){if(!G(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 E("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw E("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&xr(e.name,"Host Directory name")}const Kh=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Jh=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Zh=new Set(["range","if-range","a-im"]),Xh=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"]),em=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Yr={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class tm{constructor(t){this.signal=t}phase="initial";transition(t){if(Yr[t]<=Yr[this.phase])throw E("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Yr[this.phase]<Yr.committed&&this.signal.aborted)throw Md()}normalizeHostError(t,r){return this.throwIfCancelled(),es(t,r,this.signal)}}async function Id(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Ne("network.download");const o=ve(r.operationContext,t.signal),s=new tm(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await om(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=am(c);cm(c,u);const f=dm(c.status,u);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw E("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const l=sm(e,a,u,i);let h=0;const w=nm(f.expectedBytes,e.maxBytes);Ci(t,vi(0,f));const A={...o,onProgress(b){!Number.isSafeInteger(b)||b<h||w!==void 0&&b>w||(h=b,Ci(t,vi(h,f)))}};s.transition("transfer"),d=!0;let T;try{T=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}},A)}catch(b){throw s.normalizeHostError(b,"transfer")}s.transition("committed"),h=rm(T,f,h,e.maxBytes),Ci(t,vi(h,f));const M=i.describeFile(l.handle,l.ref);return s.transition("completed"),M}finally{d||im(n.network,c.body)}}function rm(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 nm(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function im(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function om(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return wo(i.handle.mode),await pm(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return wo(n.handle.mode),await ym(n.handle,r),{kind:"directory",...n}}function sm(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=lm(e,r),o=n.deriveFile(t,i);return wo(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function am(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 E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!G(e.headers))throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!Kh.has(r)||!Array.isArray(n)||n.length===0)throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function cm(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw E("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:gm(t,Jh)});if((t["content-range"]?.length??0)>0)throw E("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function dm(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw E("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw E("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw E("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=um(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 um(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 Ci(e,t){try{e.postProgress(t)}catch{}}function lm(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=fm(i);if(o&&tn(o))return o}for(const i of r){const o=hm(i);if(o&&tn(o))return o}if(e.suggestedName!==void 0)return Xo(e.suggestedName);const n=mm(e.url);return n&&tn(n)?n:"download.bin"}function fm(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 hm(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 mm(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Xo(e){try{xr(e,"suggestedName")}catch{throw E("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!tn(e))throw E("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function tn(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||em.test(e))}function gm(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function pm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Ad()}catch(r){throw es(r,"file",t.signal)}}async function ym(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Ad()}catch(r){throw es(r,"file",t.signal)}}function wo(e){if(e!=="readwrite")throw E("FILE_ACCESS_DENIED","下载目标只允许读取")}const Em={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 es(e,t,r){if(r.aborted)return Md();const n=wm(e);if(n&&Xh.has(n)){const o=E(n,Em[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?E("DOWNLOAD_TIMEOUT","下载网络请求超时"):E("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?E("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):E("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function wm(e){return G(e)&&typeof e.code=="string"?e.code:void 0}function Ad(){return E("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Md(){return E("DOWNLOAD_CANCELLED","下载已取消")}function Im(e){if(!e)return;const t=Object.keys(e).find(r=>Zh.has(r.trim().toLowerCase()));if(t)throw E("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}function Io(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=>Io(r,t+1)):ie(e)&&Object.values(e).every(r=>Io(r,t+1))}function Am(e,t){const r=t==="2358720"?"blackMythWukong":t==="3678970"?"taskbarHero":void 0;if(!r)return{status:"unsupported"};const n={status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}};if(!ie(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 V(String(e.error_code),"账号或授权已变化");return n}return e.status!=="ready"||!ie(e.data)||!Io(e.data)?n:{status:"ready",data:e.data}}function Mm(e){const t=new Map,r=new Map,n=a=>`hb_runtime_game_save_sync_v1_${[a.miniProgramId,a.userId,a.gameId].map(encodeURIComponent).join(":")}`;async function i(a,c,d){const u=n(a),f=r.get(u)??Promise.resolve();let l;const h=new Promise(A=>{l=A}),w=f.then(()=>h);r.set(u,w);try{return await K(()=>f,c.signal),W(c.signal),await d()}finally{l(),r.get(u)===w&&w.then(()=>{r.get(u)===w&&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 K(()=>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{W(c.signal);return}}async function s(a,c,d){W(d.signal);const u=n(a),f=c?{...a,version:1,taskId:c}:void 0;if(t.set(u,f),!!e)try{await K(()=>e.setRaw(u,f?JSON.stringify(f):"",d),d.signal)}catch{W(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 Li=8*1024*1024,Js=32*1024*1024,Nm=2e3,Dm=5*6e4;function Sm(e){const t=Mm(e.storage);let r=0,n=!1,i,o=0;const s=new Set,a={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},c=p=>p.remove(a),d=new Set;let u=new AbortController,f;const l=()=>{u.abort(),u=new AbortController,f=void 0},h=(p=!0)=>{p&&t.clear(a),r++,l();for(const m of d)m.abort();for(const m of s)c(m).catch(()=>{});s.clear(),o=0},w=Wo(e.account,p=>{i&&p!==i&&(h(),i=void 0)}),A=e.authorization.onEvent(()=>h());function T(p,m,I,y){if(M(I),y.signal.aborted||!p.account_id||!e.presentation?.showSteamLoginRequired)return;const _=`${p.account_id}:${p.game_id}:${p.task_id??"sync"}`;if(f!==_){f=_;try{e.presentation.showSteamLoginRequired({userId:m,accountId:p.account_id},ve(e.operationContext,u.signal))}catch{}}}function M(p){if(n||e.operationContext.signal.aborted)throw V("RUNTIME_DESTROYED","小程序已关闭");if(p!==r)throw V("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function b(p,m,I){if(M(m),await e.account.getCurrentUserId(I)!==p)throw h(),V("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");M(m)}async function S(p,m,I,y){if(await b(m,I,y),!e.authorizationContext)throw V("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const _=await e.authorizationContext.get(y);if(!_.token||_.expiresAt<=Date.now())throw V("UNAUTHORIZED","小程序运行上下文已过期");const g=await $o({network:e.network,operationContext:y,subject:"游戏存档",assertUsable:()=>M(I),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},Vh,{...p,runtime_auth_context_token:_.token});await b(m,I,y);const D=ze(g,p.action,"游戏存档");if(!ie(D))throw V("INVALID_RESPONSE","存档响应不合法");return D}async function R(p,m,I){const y=Tm(p,m),_=r;if(M(_),p==="file"&&(!e.transfer||!e.files))throw V("METHOD_FORBIDDEN","宿主不支持存档文件读取");const g=new AbortController;d.add(g);let D=!1;const v=p==="sync"?setTimeout(()=>{D=!0,g.abort()},Dm):void 0,k=ve(ve(e.operationContext,I.signal),g.signal);try{const x=await e.account.getCurrentUserId(k);if(!x)throw V("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==x)throw h(),V("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=x,p==="sync"||p==="parsed"){if(p==="sync"&&l(),!y.account_id){const Q=await S({action:"check",game_id:y.game_id},x,_,k);y.account_id=_r(Q.account_id)}if(p==="sync")return await B(y,x,_,k)}const C=await S({action:p,...y},x,_,k);if(p==="list")return _m(C);if(p==="parsed")return Am(C.parsed_data,y.game_id);const N=Nd(C.file);if(N.fileId!==y.file_id)throw V("INVALID_RESPONSE","文件标识不匹配");if(N.sizeBytes>Li)throw V("FILE_TOO_LARGE","首期存档文件上限为 8 MiB");if(o+N.sizeBytes>Js)throw V("FILE_QUOTA_EXCEEDED","当前会话存档文件已达 32 MiB");const O={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:st(C.download_url)},timeout:6e4};if(!xl(O)||new URL(st(C.download_url)).pathname!=="/cloud_archive/"+y.file_id+".zip"||Wn(C.expires_at)<=Date.now())throw V("INVALID_RESPONSE","存档下载地址无效");const L=".hb-game-saves/"+md()+".zip",P=e.files.sandbox.file(L);if(!P.remove)throw V("METHOD_FORBIDDEN","宿主不支持存档临时文件清理");await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},k);const z=e.fileRegistry.createTransferScope();let H=!1,F=!1;try{await P.create({recursive:!0,exclusive:!0},k),F=!0;const Q=z.registerFile(P,"game-save","readwrite");await Id({request:O,url:new URL(st(C.download_url)),to:Q.ref,targetKind:"file",maxBytes:Li},{...I,signal:k.signal,postProgress:()=>{}},{transfer:e.transfer,fileRegistry:z,operationContext:k}),await b(x,_,k);const J=await P.stat(k);if(J.size===void 0||!Number.isSafeInteger(J.size)||J.size<0||J.size>Li)throw V("FILE_TOO_LARGE","存档文件超过 8 MiB");if(await b(x,_,k),o+J.size>Js)throw V("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达 32 MiB");if(k.signal.aborted)throw V("DOWNLOAD_CANCELLED","存档下载已取消");const $=J.size,X=async ye=>{try{M(_),await S({action:"check",game_id:y.game_id,account_id:y.account_id},x,_,ye)}catch(Ae){throw ie(Ae)&&["GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","UNAUTHORIZED"].includes(String(Ae.code))?(h(),V("FILE_ACCESS_REVOKED","游戏存档授权已失效")):Ae}},q=async()=>{throw V("FILE_ACCESS_DENIED","存档文件只读")},ce={kind:"file",mode:"read",name:N.name,create:q,write:q,async read(ye){await X(ye);const Ae=await P.read(ye);try{if(await b(x,_,ye),!(Ae instanceof Uint8Array)||Ae.byteLength!==$)throw V("INVALID_RESPONSE","存档文件长度不匹配");return Ae}catch(ku){throw Ae instanceof Uint8Array&&Ae.fill(0),ku}},async stat(ye){return await X(ye),{kind:"file",size:$,modifiedAt:N.modifiedAt}}},wt=e.fileRegistry.registerFile(ce,"game-save","read");return s.add(P),o+=$,H=!0,wt}finally{z.dispose(),F&&!H&&await c(P)}}catch(x){throw D?V("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):x}finally{v!==void 0&&clearTimeout(v),d.delete(g)}}async function B(p,m,I,y){const _=e.identity.get()?.miniProgramId;if(!_)throw V("INVALID_STATE","小程序身份尚未确认");const g={miniProgramId:_,userId:m,gameId:p.game_id,accountId:p.account_id},D=k=>S({action:"status",...p,task_id:k},m,I,y);let v;try{const k=await t.run(g,y,async()=>{await b(m,I,y);const C=await t.get(g,y);if(C){v=C;try{return{taskId:C,status:await D(C)}}catch(O){if(!ie(O)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(O.code)))throw O;await t.set(g,void 0,y),v=void 0}}const N=await S({action:"sync",...p},m,I,y);return v=_r(N.task_id),await t.set(g,v,y),await b(m,I,y),{taskId:v,status:void 0}});v=k.taskId;let x=k.status;for(;;){if(M(I),y.signal.aborted)throw V("REQUEST_CANCELLED","已停止等待存档同步");if(x??=await D(v),x.state==="succeeded"||x.state==="failed"){if(await t.remove(g,v,y),await b(m,I,y),x.state==="succeeded")return{state:"succeeded"};throw V(x.error_code?st(x.error_code):"SYNC_FAILED",x.message?st(x.message):"存档同步失败")}if(x.state!=="syncing"&&x.state!=="uploading")throw V("INVALID_RESPONSE","同步状态不合法");x=void 0,await bm(Nm,y.signal)}}catch(k){if(ie(k)){const x=String(k.code);x==="STEAM_LOGIN_REQUIRED"&&T({...p,task_id:v},m,I,y),v&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(x)&&await t.remove(g,v,a)}throw k}}return{handlers:{"gameSaves.list":(p,m)=>R("list",p,m),"gameSaves.sync":(p,m)=>R("sync",p,m),"gameSaves.readParsedData":(p,m)=>R("parsed",p,m),"gameSaves.getFile":(p,m)=>R("file",p,m)},allowsRead(p,m){return["file.readBytes","file.readText","file.stat","file.exists"].includes(p)&&ie(m)&&e.fileRegistry.isGameSaveRef(m.target)},dispose(){n||(n=!0,h(!1),w(),A())}}}function Tm(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!ie(t)||Object.keys(t).some(i=>!r.includes(i)))throw V("INVALID_PARAMS","存档参数不合法");const n=or(t.gameId);if(Number(n)>2147483647)throw V("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:or(t.accountId)}:{},...e==="file"?{save_id:or(t.saveId),file_id:or(t.fileId)}:{}}}function or(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw V("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function _r(e){try{return or(e)}catch{throw V("INVALID_RESPONSE","服务端存档标识无效")}}function st(e){if(typeof e!="string")throw V("INVALID_RESPONSE","服务端存档字段无效");return e}function Wn(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw V("INVALID_RESPONSE","服务端存档数值无效");return e}function Nd(e){if(!ie(e))throw V("INVALID_RESPONSE","存档文件信息无效");return{fileId:_r(e.file_id),name:st(e.name),originalPath:st(e.original_path),sizeBytes:Wn(e.size_bytes),modifiedAt:Wn(e.modified_at)}}function _m(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw V("INVALID_RESPONSE","存档列表无效");return{accountId:_r(e.account_id),saves:e.saves.map(t=>{if(!ie(t)||!Array.isArray(t.files)||t.files.length>200)throw V("INVALID_RESPONSE","存档文件列表无效");return{saveId:_r(t.save_id),createdAt:Wn(t.created_at),files:t.files.map(Nd)}})}}function bm(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(o),t.removeEventListener("abort",i),n(V("REQUEST_CANCELLED","已停止等待存档同步"))},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}const Om=new Set(["stdio","attachments","notifications"]),Dd=new Set(["windows-x64","macos-arm64"]),vm=new Set(["unsigned","valid","invalid","unknown"]),Cm=/^[a-f0-9]{64}$/,Lm=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Rm=new Set(Qc),Pm=new Set([...Qc,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Sd=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 km(e){const t=async(n,i,o,s)=>{const a=xm(n);try{je(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return je(i.signal),c}catch(c){throw Mo(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw E("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw E("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>jm(d,i)).catch(d=>{throw Mo(d)});je(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(je(o.signal),c.status!=="granted")throw E("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[ri]:(n,i)=>t(n,i,async(o,s)=>Ao(await e.companion.getInfo(o,s),o)),[ni]:(n,i)=>t(n,i,async(o,s)=>Zs(await e.companion.getPreparationStatus(o,s))),[ii]:(n,i)=>t(n,i,async(o,s)=>{const a=Zs(await e.companion.getPreparationStatus(o,s));return je(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),je(i.signal),Ao(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(_d(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[oi]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[si]:(n,i)=>t(n,i,async(o,s)=>Xs(await e.companion.getActiveSession(o,s),o)),[ai]:(n,i)=>t(n,i,async(o,s)=>{const a=Xs(await e.companion.getActiveSession(o,s),o);return je(i.signal),a||(await r("launch",o,i),je(i.signal),bd(await e.companion.launch(o,s),o))}),[ci]:(n,i)=>St(n,i,e,"write"),[di]:(n,i)=>St(n,i,e,"closeStdin"),[ui]:(n,i)=>St(n,i,e,"terminate"),[li]:(n,i)=>St(n,i,e,"ackOutput"),[fi]:async(n,i)=>{const o=await St(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[hi]:(n,i)=>St(n,i,e,"showNotification")}}function xm(e){if(!G(e)||typeof e.alias!="string"||!Tl.test(e.alias))throw E("INVALID_PARAMS","Companion alias 不合法");return e.alias}function je(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function St(e,t,r,n){if(!G(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw E("INVALID_PARAMS","Companion Session controller 不合法");try{je(t.signal);const i=await r.companion[n](Um(e,n),{...r.operationContext,signal:t.signal});return je(t.signal),i}catch(i){throw Mo(i)}}function Ce(){throw E("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Td(e){return!Array.isArray(e)||e.some(t=>!Om.has(t))?Ce():Object.freeze([...new Set(e)])}function Ao(e,t){return!G(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Dd.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!vm.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?Ce():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Td(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function jm(e,t){const r=Ao(e,t);return!G(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!Cm.test(e.sha256)?Ce():Object.freeze({...r,sha256:e.sha256})}function _d(e){return G(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}):Ce():Ce()}function Zs(e){return G(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:_d(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&G(e.error)&&typeof e.error.code=="string"&&Rm.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:Sd[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):Ce():Ce()}function bd(e,t){return!G(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Dd.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?Ce():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Td(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Xs(e,t){return e===void 0?void 0:bd(e,t)}function Um(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Fc(r.data))throw E("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 E("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw E("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw E("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function zm(e){return!G(e)||!Lm.has(String(e.reason))?Ce():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):Ce():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?Ce():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Hm(e){if(!G(e)||!G(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||!Fc(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:zm(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 Mo(e,t){return G(e)&&typeof e.code=="string"&&Pm.has(e.code)?E(e.code,Sd[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&G(e)&&e.name==="AbortError"?E(t,"Companion 准备已取消"):E("COMPANION_HOST_FAILED","Companion Host 操作失败")}const ea=5e3,ta=1e4;function me(e){throw{code:"INVALID_PARAMS",message:e}}function ts(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Od(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&me(`${r} 不支持字段: ${n.join(", ")}`)}function Fm(e){if(e===void 0)return{intensity:"light",delay:0};if(!ts(e))return me("device.vibrate 参数必须是对象");Od(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return me("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>ea?me(`device.vibrate delay 必须是 0-${ea} 的整数毫秒`):{intensity:r,delay:n}}function Vm(e){return ts(e)?(Od(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?me("device.setClipboard text 必须是非空字符串"):e.text.length>ta?me(`device.setClipboard text 不能超过 ${ta} 字符`):{text:e.text}):me("device.setClipboard 参数必须是对象")}function Bm(e){return typeof e=="string"?e.trim()?e:me("device.executeProtocol 协议字符串不能为空"):ts(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?me("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(No(e,new Set),e):me("device.executeProtocol 参数必须是协议字符串或协议对象")}function No(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||me("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":me("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":me(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&me("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)No(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&me("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))No(i,t);t.delete(r)}function Gm(e){return{[Hn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.vibrate(Fm(t),e.operationContext),e.operationContext.signal)},[Fn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.setClipboard(Vm(t),e.operationContext),e.operationContext.signal)},[Vn]:async(t,r)=>{const n=ve(e.operationContext,r.signal);W(n.signal);const i=Bm(t);await K(()=>e.protocol.invoke(i,n),n.signal)}}}const ra=1e3,Qm=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function Ym(e){const t=r=>ve(e.operationContext,r.signal);return{files:{[bn]:async(r,n)=>{Ri(n);const i=Pi(e.picker),o=qm(r),s=await Ee(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[On]:async(r,n)=>{Ri(n);const i=Pi(e.picker),o=$m(r),s=await Ee(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[vn]:async(r,n)=>{Ri(n);const i=Pi(e.picker),o=Wm(r).suggestedName,s=t(n);if(!i.saveFile)throw Ne("files.saveFile");const a=await Ee(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[yr]:async(r,n)=>{const i=Me(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);Tt(o.mode),await Ee(()=>o.create(na(i),t(n)))},[Er]:async(r,n)=>{const i=Me(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),Tt(o.handle.mode),!o.handle.remove)throw Ne(Er);await Ee(()=>o.handle.remove(t(n)))},[Cn]:async(r,n)=>{const i=Me(r);return ia(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!G(o)||o.kind!=="file")throw sa()})},[wr]:async(r,n)=>{const i=Me(r),o=oa(await Ee(()=>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 E("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Ln]:async(r,n)=>{const i=Me(r,["content"]);typeof i.content!="string"&&Te("content 必须是字符串");const o=e.registry.resolveFile(i.target);Tt(o.mode),await Ee(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[Ir]:async(r,n)=>{const i=Me(r),o=await Ee(()=>e.registry.resolveFile(i.target).read(t(n)));return oa(o)},[Rn]:async(r,n)=>{const i=Me(r,["content"]),o=e.registry.resolveFile(i.target);Tt(o.mode),await Ee(()=>o.write(Jm(i.content),t(n)))},[Ar]:async(r,n)=>{const i=Me(r),o=await Ee(()=>e.registry.resolveFile(i.target).stat(t(n)));return Zm(o)}},directory:{[Pn]:async(r,n)=>{const i=Me(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);Tt(o.mode),await Ee(()=>o.create(na(i),t(n)))},[Mr]:async(r,n)=>{const i=Me(r,["recursive"]);if(G(i.target)&&i.target.relativePath===".")throw E("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),Tt(o.handle.mode),!o.handle.remove)throw Ne(Mr);await Ee(()=>o.handle.remove({recursive:i.recursive===void 0?!1:Kn(i.recursive,"recursive")},t(n)))},[kn]:async(r,n)=>{const i=Me(r);return ia(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!G(o)||o.kind!=="directory")throw sa()})},[xn]:async(r,n)=>{const i=Me(r,["limit"]),o=Km(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await Ee(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function qm(e){if(e===void 0)return{mode:"read",multiple:!1};G(e)||Te("pickFiles 参数必须是对象"),gi(e,["mode","accept","multiple"]);const t=vd(e.mode,"read"),r=e.multiple===void 0?!1:Kn(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)))&&Te("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function $m(e){return e===void 0?{mode:"read"}:(G(e)||Te("pickDirectory 参数必须是对象"),gi(e,["mode"]),{mode:vd(e.mode,"read")})}function Wm(e){return G(e)||Te("saveFile 参数必须是对象"),gi(e,["suggestedName"]),{suggestedName:xr(e.suggestedName,"suggestedName")}}function Me(e,t=[]){return(!G(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Te("文件操作参数必须包含 target"),gi(e,["target",...t]),e}function na(e){return{recursive:e.recursive===void 0?!1:Kn(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Kn(e.exclusive,"exclusive")}}function vd(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&Te("mode 必须是 read 或 readwrite"),e)}function Kn(e,t){return typeof e!="boolean"&&Te(`${t} 必须是布尔值`),e}function Km(e){if(e===void 0)return ra;if((!Number.isSafeInteger(e)||e<=0)&&Te("limit 必须是正整数"),e>ra)throw E("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function gi(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&Te(`不支持字段: ${r.join(", ")}`)}function Tt(e){if(e!=="readwrite")throw E("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Ri(e){if(!e.trustedUserGesture)throw E("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Pi(e){if(!e)throw Ne("files.external");return e}async function ia(e){try{return await e(),!0}catch(t){if(Qm.has(Jo(t)??""))return!1;throw Sr(t)}}async function Ee(e){try{return await e()}catch(t){throw Sr(t)}}function Jm(e){return e instanceof Uint8Array||Te("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Te("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function oa(e){if(!(e instanceof Uint8Array))throw E("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function sa(){return E("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Zm(e){if(!G(e)||e.kind!=="file"||!Xm(e.size))throw E("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!eg(e[t]))throw E("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 Xm(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function eg(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Te(e){throw E("INVALID_PARAMS",e)}const tg=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),ki={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function rg(e){if(e instanceof ue)return E("REQUEST_UNSUPPORTED",ki.REQUEST_UNSUPPORTED);const t=Cd(e);return t!==void 0&&tg.has(t)?E(t,ki[t]??"媒体操作失败"):E("MEDIA_PREPARE_FAILED",ki.MEDIA_PREPARE_FAILED)}function Cd(e){try{if(!G(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const ng=["source","mediaType","maxCount"],rn=Object.freeze({source:"album",mediaType:"all",maxCount:1});function ig(e){if(e===void 0)return rn;if(!hl(e))throw E("INVALID_PARAMS",sg(e));return og(e)}function og(e){return Object.freeze({source:e.source??rn.source,mediaType:e.mediaType??rn.mediaType,maxCount:e.maxCount??rn.maxCount})}function sg(e){if(!G(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!ng.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 ag=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),cg={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class dg{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=ug(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>fg(s,i[a]));if(!ml(o))throw He("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(hg).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=Cd(n);throw i!==void 0&&ag.has(i)?n:He("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function aa(e,t){if(e.signal.aborted)throw E("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw E("REQUEST_CANCELLED","media.pick 已取消")}function ug(e,t){if(!Array.isArray(e))throw He("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw He("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw He("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw He("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw He("Host 返回了稀疏媒体结果");lg(e[n],n)}return e}function lg(e,t){if(!G(e))throw He(`第 ${t+1} 项不是对象`);if(!Hc({...e,file:cg}))throw He(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!G(e.file))throw He(`第 ${t+1} 项缺少文件句柄`)}function fg(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 hg(e){return"handleId"in e.ref?e.ref.handleId:void 0}function He(e){return E("MEDIA_PREPARE_FAILED",e)}function mg(e){const t=e.media?new dg(e.registry,e.media,e.operationContext):void 0;return{handlers:{[Nr]:async(n,i)=>{const o=ig(n);pg(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw Ne(Nr);const c=ve(e.operationContext,i.signal);aa(e.operationContext,i.signal);const d=await gg(s,o,c,e.operationContext,i.signal);aa(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function gg(e,t,r,n,i){try{return await K(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?E("REQUEST_CANCELLED","media.pick 已取消"):rg(o)}}function pg(e){if(!e.trustedUserGesture)throw E("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const qr=4294967296;function yg(e){const t=new Eg;return t.write(e),t.finish()}class Eg{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<qr?(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=wg(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<qr)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/qr),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/qr)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function wg(e){const t=new Uint8Array(Ig(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 Ig(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 Ld(e){Do(e);const t=yg(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 Do(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)Do(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");Do(s,t+1,r)}r.delete(e)}const Ag=["pc","console","mobile"],Mg=["game","wiki"];function Jn(e){throw{code:"INVALID_PARAMS",message:e}}function Ng(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xe(e,t){return typeof e!="string"||!e.trim()?Jn(t):e.trim()}function ca(e,t,r){return typeof e!="string"||!t.includes(e)?Jn(r):e}function Dg(e){const t={target:"game_detail",appId:Xe(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:ca(e.gameType,Ag,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=ca(e.page,Mg,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Xe(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Xe(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Sg(e){return{target:"user_detail",userId:Xe(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Tg(e){const t={target:"post_detail",linkId:Xe(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Xe(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Xe(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function _g(e){const t={target:"mini_program",miniProgramId:Xe(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function bg(e){return Ng(e)?e.target==="game_detail"?Dg(e):e.target==="user_detail"?Sg(e):e.target==="post_detail"?Tg(e):e.target==="mini_program"?_g(e):Jn("navigation.openAppPage target 不支持"):Jn("navigation.openAppPage options 必须是对象")}function Og(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 vg(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Cg(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 Lg(e){const t=e;return t.target==="game_detail"?Og(t):t.target==="user_detail"?vg(t):Cg(t)}const Rg="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",Pg="data-hb-sdk-fullscreen-exit",kg=3e3,xg=2e3,da="var(--white-70a,rgba(255,255,255,.7))",ua="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function jg(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(Pg,""),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 ${da}`,`box-shadow:${ua}`,"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=Rg,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let o=!0,s=!1,a=!1,c,d;function u(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function f(){o||(t.style.width=u())}function l(){d?.cancel(),d=void 0}function h(T=xg){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")},T)}function w(){l(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=da,t.style.boxShadow=ua,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),h()}async function A(){if(!(s||a)){if(!o){w();return}a=!0,clearTimeout(c),l();try{await e()}catch{}finally{a=!1,s||w()}}}return t.addEventListener("click",A),window.addEventListener("resize",f),document.body.append(t),!r&&t.animate&&(d=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),h(kg),{dispose(){s=!0,clearTimeout(c),l(),t.removeEventListener("click",A),window.removeEventListener("resize",f),t.remove()}}}const Rd=1e4;function Pd(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()},Rd);return{signal:r.signal,async run(s){try{return await K(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 xi(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Xt(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function Ug(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(w){if(!w.hideCapsule){c();return}a??=jg(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",c,{once:!0});function u(w,A){if(n===w){if(n=void 0,clearTimeout(w.timer),e.operationContext.signal.removeEventListener("abort",f),"error"in A)w.controller.abort();else if(i={options:w.options,result:A.result},o=w.options,d(w.options),e.onApplied?.(w.options),A.result.supported&&!xi(s,w.options)){s={...w.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:w.source})}catch{}}for(const T of w.subscribers)T.dispose(),"error"in A?T.reject(A.error):T.resolve(A.result);w.subscribers.clear()}}function f(){n&&u(n,{error:Xt()})}function l(w,A){return new Promise((T,M)=>{const b=()=>{w.subscribers.delete(S),S.dispose(),M(Xt()),w.subscribers.size===0&&u(w,{error:Xt()})},S={resolve:T,reject:M,dispose:()=>A?.removeEventListener("abort",b)};w.subscribers.add(S),A?.addEventListener("abort",b,{once:!0}),A?.aborted&&b()})}const h={async runDisplayRequest(w,A,T){const M=++t,b=Pd(A,e.operationContext.signal);try{return await b.run(async()=>{if(await T(b.signal),b.signal.aborted)throw Xt();if(la(w),M<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=M,h.apply(w,b.signal)})}finally{b.dispose()}},async apply(w,A,T="api"){if(W(e.operationContext.signal),A?.aborted)throw Xt();const M=la(w),b=n?.options??o,S={mode:M.orientation??b.mode,hideCapsule:M.fullscreen??b.hideCapsule};S.mode==="landscape"&&(S.hideCapsule=!0);const R=e.presentation.applyOrientation;if(!R)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&xi(n.options,S))return l(n,A);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&xi(i.options,S))return i.result;i=void 0;const B={options:S,source:T,controller:new AbortController,subscribers:new Set};n=B;const U=l(B,A);return e.operationContext.signal.addEventListener("abort",f,{once:!0}),A||(B.timer=setTimeout(()=>{u(B,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Rd)),K(()=>R.call(e.presentation,S,{...e.operationContext,signal:B.controller.signal}),B.controller.signal).then(p=>u(B,{result:p??{supported:!0}}),p=>u(B,{error:p})),U},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return h}function kd(e){throw{code:"INVALID_PARAMS",message:e}}function fa(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&kd(`${t} 不支持参数`)}function zg(e){return{[Bn]:async t=>{W(e.operationContext.signal),fa(t,"navigation.close"),await K(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Gn]:async t=>{W(e.operationContext.signal),fa(t,"navigation.reload"),await K(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[Qn]:async(t,r)=>{const n=ve(e.operationContext,r?.signal);W(n.signal);const i=bg(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Ld(i.extra)}catch{kd("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=Pd(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}W(n.signal),await K(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await K(()=>e.presentation.openAppPage(Lg(i),n),n.signal)}}}const ha={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function Hg(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw Ne("network.upload");const o=ve(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw E("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(l){throw s(),Sr(l)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw E("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw E("FILE_TOO_LARGE","文件超过大小限制");let d=0,u=!1;const f=l=>{u||o.signal.aborted||!Number.isSafeInteger(l)||l<d||l>c.size||(d=l,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:l,...h}=e,w=await n.upload(a,{...h,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:f});if(u=!0,!Number.isSafeInteger(w.uploadedBytes)||w.uploadedBytes<d||w.uploadedBytes>c.size)throw E("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(w.status>=200&&w.status<300&&w.uploadedBytes!==c.size)throw E("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:w.uploadedBytes,total:c.size,lengthComputable:!0}),w}catch(l){u=!0;const h=Jo(l);throw h&&ha[h]?E(h,ha[h]):o.signal.aborted?E("UPLOAD_CANCELLED","上传已取消"):h?.startsWith("FILE_")||h?.startsWith("DIRECTORY_")?Sr(l):E("UPLOAD_NETWORK_FAILED","上传网络失败")}}const rs="withCredentials",Fg=new Set(["url","method","params","data","headers","timeout",rs]),Vg=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",rs]),Bg=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),ma=3e4,So=2*1024*1024,Gg=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,xd=/[\u0000-\u0008\u000A-\u001F\u007F]/,Qg=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Yg="network.request 不支持 multipart/form-data,请使用专用上传能力";function qg(e){const t=$g(e.runtimePermissions),r=cp(e.allowedHttpOrigins);return{[_n]:async(n,i)=>{const o=Kg(n,{permission:t,allowedHttpOrigins:r}),s=await Hg(o,i,e),{uploadedBytes:a,...c}=s;return pa(c)},[Tn]:async(n,i)=>{const o=Jg(n,{permission:t,allowedHttpOrigins:r});return Id(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Sn]:async(n,i)=>{const o=ve(e.operationContext,i?.signal);W(o.signal);const s=Wg(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await K(()=>e.network.request(s,o),o.signal)}catch(c){throw up(c)?c:lp(c,"REQUEST_UNSUPPORTED")?Y("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):Y("REQUEST_FAILED","网络请求失败")}return pa(a)}}}function $g(e){const t=Oe(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Wg(e,t){const r=Vt(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!Fg.has(c));if(n.length>0)throw Y("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);jd(r,"network.request");const i=ns(r,t,"network.request"),o=Xg(r.method),s=r.data;s!==void 0&&rp(s),ip(i.headers,s);const a=op(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 Kg(e,t){const r=Vt(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 Y("INVALID_PARAMS","network.upload 包含不支持的字段");const i=ns(r,t,"network.upload");if(i.official)throw Y("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw Y("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!Ut(r.from))throw Y("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Y("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw Y("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw Y("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 Y("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(u=>u.toLowerCase()==="content-type"))throw Y("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=ga(r.fieldName),c=r.fields===void 0?void 0:Vt(r.fields,"fields 必须是字符串字典");for(const[u,f]of Object.entries(c??{}))if(ga(u),typeof f!="string"||u===a)throw Y("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw Y("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||xd.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw Y("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>So)throw Y("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:Xo(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function ga(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw Y("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function Jg(e,t){const r=Vt(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!Vg.has(c));if(n.length>0)throw Y("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);jd(r,"network.download");const i=ns(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw Y("INVALID_PARAMS","network.download timeout 必须是有限正数");Im(i.headers);const o=Ut(r.to),s=Uc(r.to);if(!o&&!s)throw Y("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw Y("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw Y("INVALID_PARAMS","suggestedName 必须是字符串");a=Xo(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw Y("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Y("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 ns(e,t,r){const n=Zg(e.url,t.allowedHttpOrigins,r),i=df(n);if(i&&!t.permission.useOfficialDomain)throw Y("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(cf(n.pathname,i))throw Y("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Vt(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:ep(e.headers,r),timeout:tp(e.timeout,r)}}function Zg(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw Y("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw Y("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Y("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw Y("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw Y("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Xg(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw Y("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!Bg.has(t))throw Y("INVALID_PARAMS","network.request method 不合法");return t}function ep(e,t="network.request"){const r=Vt(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!Gg.test(s)||typeof o!="string"||xd.test(o))throw Y("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(uf(s))throw Y("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function jd(e,t){const r=e[rs];if(r!==void 0&&typeof r!="boolean")throw Y("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function tp(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw Y("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>ma)throw Y("INVALID_PARAMS",`${t} timeout 不能超过 ${ma}ms`);return e}}function rp(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw Y("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(np(e)>So)throw Y("INVALID_PARAMS",`network.request data 不能超过 ${So} 字节`)}function np(e){if(typeof e=="string")return ji(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return ji(e.toString());try{const t=JSON.stringify(e);return t?ji(t):0}catch{throw Y("INVALID_PARAMS","network.request data 必须可序列化")}}function ip(e,t){const r=Ud(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 Y("INVALID_PARAMS",Yg)}function op(e,t,r){if(t===void 0)return;const n=Ud(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)||ap(t))?"form":sp(t)?"json":void 0}function Ud(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function sp(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function ap(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function cp(e){const t=new Set;for(const r of e??[])try{const n=new URL(r);n.protocol==="http:"&&!n.username&&!n.password&&n.pathname==="/"&&!n.search&&!n.hash&&dp(n.hostname)&&t.add(n.origin)}catch{}return t}function dp(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 pa(e){return Object.keys(e.headers).some(ya)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!ya(t)))}:e}function ya(e){const t=e.trim().toLowerCase();return Qg.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function up(e){return e instanceof Error&&e.name==="AbortError"}function lp(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Vt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Y("INVALID_PARAMS",t);return e}function ji(e){return new TextEncoder().encode(e).length}function Y(e,t){return{code:e,message:t}}function fp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hp(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 mp(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=hp(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function gp(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 zd(e,t){if(e==null)return{};if(!fp(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=mp(e.topicIds),n=gp(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 pp(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function yp(e){try{if(pp(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function fe(e){throw{code:"INVALID_PARAMS",message:e}}function jr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function To(e,t){return typeof e!="string"||!e.trim()?fe(t):e}function Ep(e,t){const r=To(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?fe(t):r}catch{return fe(t)}}function wp(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Hd(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 Ip(e,t){if(!jr(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&&!wp(r))return fe("share.showShareMenu channel 不合法");const n=Fd(e.extra,"share.showShareMenu");return{title:To(e.title,"share.showShareMenu title 必须是非空字符串"),description:To(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Hd(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:Ep(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Fd(e,t){if(e!==void 0)try{return Ld(e)}catch{return fe(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function Vd(e,t){return e.invalidMessage&&await K(()=>yp(t.environment),t.operationContext.signal)?fe(e.invalidMessage):e.post}function Ea(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Ap(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Ea(t.windowWidth,0),height:Ea(t.windowHeight,0)}}function _o(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?fe(t):r}function wa(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?fe(t):r}function Mp(e){return jr(e)?{left:_o(e.left,"share.screenshot rect.left 必须是非负数字"),top:_o(e.top,"share.screenshot rect.top 必须是非负数字"),width:wa(e.width,"share.screenshot rect.width 必须是正数"),height:wa(e.height,"share.screenshot rect.height 必须是正数")}:fe("share.screenshot rect 必须是对象")}function Np(e,t){if(e!=null&&!jr(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?Ap(t):Mp(r.rect),...r.delay===void 0?{}:{delay:_o(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function Dp(e,t){W(t.operationContext.signal);const r=Ip(e,t);let n=zd(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await Vd(n,t);return K(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function Sp(e,t){if(W(t.operationContext.signal),e!==void 0&&!jr(e))return fe("share.copyLink 参数必须是对象");const r=Fd(e?.extra,"share.copyLink"),n=Hd(t,"share.copyLink",r);return await K(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Tp(e,t,r){W(t.operationContext.signal);const n=zd(jr(e)?e.post:void 0,{method:"share.screenshot"}),i=await Vd(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=_p(),{watermarkTheme:a,...c}=r;let d=!1,u,f;try{d=!0,await K(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),u=await t.prepareScreenshot?.(r.rect,t.operationContext.signal,a),f={status:"fulfilled",value:await K(()=>t.presentation.captureAndShare({...c,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(h){f={status:"rejected",error:h}}finally{u?.()}const l=d?await bp(t.presentation,s,t.operationContext.signal):void 0;if(f.status==="rejected")throw f.error;if(l)throw l;return f.value}function _p(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function bp(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await K(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function Op(e){let t=Promise.resolve();return{[In]:(r,n)=>Sp(r,e),[An]:(r,n)=>Dp(r,e),[Mn]:async(r,n)=>{const i=ve(e.operationContext,n.signal);W(i.signal);const o=Np(r,e.presentation),s=t.then(()=>Tp(r,{...e,operationContext:i},o));return t=s.then(()=>{},()=>{}),K(()=>s,i.signal)}}}const Ia=new WeakMap;function Bd(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return Ul(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${$c(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Gd(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=Ia.get(t);f||(f=new Map,Ia.set(t,f));const l=f.get(u)??Promise.resolve(),h=async()=>(W(c.signal,{preserveReason:!0}),d(u)),w=l.catch(()=>{}).then(()=>e.lock?e.lock(u,h):h());f.set(u,w);try{return await w}finally{f.get(u)===w&&f.delete(u)}},o=async(c,d,u=!1)=>{const f=It(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(w=>w.key.startsWith(f)&&w.value!=="").map(w=>w.key.slice(f.length)))];const l=await e.storage.getRaw(Vr(c),d);if((l===void 0||l==="")&&!u)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let h;try{h=l?JSON.parse(l):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(h)||h.length>Es||h.some(w=>typeof w!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(w)))throw new Error("本地数据索引异常");return[...new Set(h)]},s=async(c,d)=>{if(e.diagnostics){const l=It(c,"");return(await e.diagnostics.listRaw(d)).filter(h=>h.key.startsWith(l)&&h.value!=="").map(h=>({...h,key:h.key.slice(l.length)}))}const u=[],f=await o(c,d);for(let l=0;l<f.length;l+=16){W(d.signal,{preserveReason:!0});const h=await Promise.all(f.slice(l,l+16).map(async w=>{const A=await e.storage.getRaw(It(c,w),d);return A!==void 0&&A!==""?{area:"local",key:w,value:A}:void 0}));for(const w of h)w&&u.push(w)}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(It(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>=Es)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const h=[...new Set([...l,c])];await e.storage.setRaw(Vr(f),JSON.stringify(h),u)}W(u.signal,{preserveReason:!0}),await e.storage.setRaw(It(f,c),d,u),W(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(Vr(d),JSON.stringify(u),c);for(let f=0;f<u.length;f+=16){W(c.signal,{preserveReason:!0});const h=(await Promise.allSettled(u.slice(f,f+16).map(w=>e.storage.setRaw(It(d,w),"",c)))).find(w=>w.status==="rejected");if(h)throw h.reason}W(c.signal,{preserveReason:!0}),await e.storage.setRaw(Vr(d),"[]",c)})}}}function vp(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 Cp=128,Lp=/^[A-Za-z0-9_-]+$/;function Rp(e){const t=e.scopedStorage??Gd({storage:e.storage,resolveScope:()=>Bd({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[gr]:async n=>{W(e.operationContext.signal);const i=Aa(n,gr,e.storageLimits?.maxKeyLength),o=await K(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:Ma(o)}},[pr]:async n=>{W(e.operationContext.signal);const i=Qd(n,"storage.setStorage 参数必须是对象"),o=Aa(i,pr,e.storageLimits?.maxKeyLength),s=Pp(i.data,e.storageLimits?.maxValueBytes);await K(()=>t.set(o,s,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(W(e.operationContext.signal),(await K(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?lt("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:Ma(o),serializedValue:o,bytes:Yd(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function Aa(e,t,r=Cp){const i=Qd(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw lt("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!Lp.test(i))throw lt("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function Pp(e,t){let r;try{r=JSON.stringify(e)}catch{throw lt("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw lt("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Yd(r)>t)throw lt("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Ma(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Qd(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw lt("INVALID_PARAMS",t);return e}function Yd(e){return new TextEncoder().encode(e).length}function lt(e,t){return{code:e,message:t}}const Na=120;function We(e){throw{code:"INVALID_PARAMS",message:e}}function is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qd(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&We(`${r} 不支持字段: ${n.join(", ")}`)}function kp(e){if(!is(e))return We("ui.showToast 参数必须是对象");if(qd(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return We("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Na)return We(`ui.showToast message 不能超过 ${Na} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return We("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function xp(e){return e===void 0?{dismissible:!1}:is(e)?(qd(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?We("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):We("ui.showLoading 参数必须是对象")}function jp(e){e!==void 0&&(!is(e)||Object.keys(e).length)&&We("ui.hideLoading 不支持参数")}function Up(e){return{[jn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.showToast(kp(t),e.operationContext),e.operationContext.signal)},[Un]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.showLoading(xp(t),e.operationContext),e.operationContext.signal)},[zn]:async t=>{W(e.operationContext.signal),jp(t),await K(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const zp={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return le(e,"当前用户首页资料接口响应异常")}},Hp=3e4;function Fp(e,t,r={}){const n=r.ttlMs??Hp,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function d(){let f;try{f=await mi(e,zp,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(l){throw t.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):l instanceof ue?E("REQUEST_UNSUPPORTED",l.message):l instanceof kr?E("INVALID_RESPONSE","user home_v2 响应不合法"):l instanceof Ft?E("REQUEST_FAILED","user home_v2 请求失败"):l instanceof Ht?i&&(l.status===403||l.status===429)?E("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:l.status,...l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs}}):E("REQUEST_FAILED",l.message):Bp(l)?l:E("REQUEST_FAILED","user home_v2 请求失败")}return Vp(f,"user home_v2")}function u(f){const l=Date.now();if(a?.userId===f&&a.expiresAt>l)return Promise.resolve(a.value);if(c?.userId===f&&c.generation===s)return c.promise;const h=s,w=d().then(A=>(s===h&&(a={userId:f,value:A,expiresAt:Date.now()+n}),A)).finally(()=>{c?.promise===w&&(c=void 0)});return c={userId:f,generation:h,promise:w},w}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function Vp(e,t){if(!G(e))throw E("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 E(n,r)}if(!G(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Bp(e){return G(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Gp={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 le(e,"Steam 游戏库接口响应异常")}};function Qp(e,t=go){const r=ff({version:"2",validate:qp}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):go,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 Da(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 Yp(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 qp(e){if(!G(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Sa(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Lt();for(const t of e.gameList){if(!G(t)||!bo(t.appid)||!bo(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Lt();for(const r of["image","portraitImage","icon"])$p(t,r);for(const r of["playtimeForever","playtime2Weeks"])Sa(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Lt()}return e}function bo(e){return typeof e=="number"&&Number.isFinite(e)}function Sa(e,t){if(e[t]!==void 0&&!bo(e[t]))throw Lt()}function $p(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Lt()}function Lt(){return E("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const $d=20,Wp=100,Kp=128,Wd=0,Kd="weeks",Jp=100,Zp=new Set(["weeks","all","achieved"]);function Xp(){return{nickname:"",avatar:""}}function ey(e){const t=Fp(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??Jc(),i=Qp(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(m,I){const y=JSON.stringify([m,I]);return(!o||o.key!==y)&&(o={key:y,scope:n.createScope(I,n.createScope(m))}),o.scope}function d(){const m=o;o=void 0,m&&n.invalidateScope(m.scope).catch(()=>{}),s.clear()}const u=cd({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??sd))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let l=0,h=!1;const w=e.account.onChange(()=>{l+=1,t.clear(),u.invalidate(),d()}),A=e.authorization.onEvent((m,I)=>{m==="user_info_authorization_change"&&Object.values(I).some(y=>y==="denied")&&(l+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(h)return;const y=await e.account.getCurrentUserId(e.operationContext);typeof y=="string"&&y.trim()&&await n.invalidateScope(c(M(),y.trim()))}).catch(()=>{}))});function T(){if(h||e.operationContext.signal.aborted)throw E("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function M(){const m=e.identity.get()?.miniProgramId?.trim();if(!m)throw E("INVALID_STATE","用户能力缺少 canonical 小程序身份");return m}async function b(){T(),await a,T();let m;try{m=await e.account.getCurrentUserId(e.operationContext)}catch(I){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):ba(I)?I:E("REQUEST_FAILED","读取小黑盒账号失败")}return typeof m=="string"&&m.trim()?m.trim():void 0}async function S(m,I){const y=await b();if(l!==I||y!==m)throw E("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function R(m,I,y=e.operationContext.signal){try{return await mi(e.network,m,I,{...e.operationContext,signal:y,credentials:"heybox-session",...f?{gate:f}:{}})}catch(_){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):_ instanceof ue?E("REQUEST_UNSUPPORTED",_.message):_ instanceof kr?E("INVALID_RESPONSE","用户接口响应不合法"):_ instanceof Ft?E("REQUEST_FAILED","用户请求失败"):_ instanceof Ht?r&&(_.status===403||_.status===429)?E("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:_.status,..._.retryAfterMs===void 0?{}:{retryAfterMs:_.retryAfterMs}}):E("REQUEST_FAILED",_.message):ba(_)?_:E("REQUEST_FAILED","用户请求失败")}}async function B(){M();const m=l,I=await b();if(!I)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[y,_]=await Promise.all([e.authorization.getOrCreateLocalIdentity(I),U(I).catch(()=>Xp())]);return await S(I,m),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:y.appUserId,profile:_,...y.steamId?{steam_id:y.steamId}:{}}}}function U(m){return u.read(m,()=>R(ad,void 0).then(I=>{const y=Ta(I,"账号基础信息");if(y.display_username!==void 0&&typeof y.display_username!="string")throw E("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(y.display_avatar!==void 0&&typeof y.display_avatar!="string")throw E("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:y.display_username??"",avatar:y.display_avatar??""}}))}async function p(m){const I=ty(m),y=M(),_=l,g=await b();if(!g)return d(),{isLogin:!1,isBound:!1,data:null};const D=await t.get(g);await S(g,_);const v=Jd(D.steam_id_info);if(Object.keys(v).length===0)return await n.invalidateScope(c(y,g)).catch(()=>{}),await S(g,_),s.delete(JSON.stringify([y,g])),{isLogin:!0,isBound:!1,data:null};const k=JSON.stringify([y,g]),x=c(y,g),C=Da({...I,steamId:void 0},v),N=Zd(v.personal_infomation_open??v.personal_information_open),O=JSON.stringify([C??null,N??null]),L=s.get(k);L&&L.identity!==O&&(await n.invalidateScope(x).catch(()=>{}),await S(g,_));const P={identity:O,scope:n.createScope(O,x)};s.set(k,P);const z=Da(I,v),H=z?i.persistent:i.unresolved,F=n.createScope(z??"unresolved",P.scope),Q=async()=>{if(await S(g,_),M()!==y||s.get(k)?.identity!==O)throw E("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},J=await H.read({scope:F,key:Yp({miniProgramId:y,userId:g,effectiveSteamId:z,personalInformationOpen:N,query:I}),signal:e.operationContext.signal,load:async $=>{const X=await R(Gp,{userId:g,...I,personalInformationOpen:N},$);return await Q(),sy(Ta(X,"Steam 游戏库"),I)}}).catch(async $=>{throw await Q(),$});return await Q(),{isLogin:!0,isBound:!0,data:J}}return{getInfo:B,getSteamGameList:p,async invalidateSteamGameListCache(){const m=M(),I=l,y=await b();if(!y)return;const _=c(m,y);await Promise.all([i.persistent.invalidateScope(_),i.unresolved.invalidateScope(_)]),t.clear(),s.delete(JSON.stringify([m,y])),await S(y,I)},dispose(){h||(h=!0,l+=1,w(),A(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function ty(e){if(e==null)return{limit:$d,offset:Wd,sort:Kd,includeHidden:!1};if(!G(e))throw Ke("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Ke(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:ry(e.limit),offset:ny(e.offset),sort:iy(e.sort),includeHidden:oy(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>Kp)throw Ke("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ke("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Jp))}return r}function ry(e){if(e===void 0)return $d;if(!Number.isInteger(e)||Number(e)<1)throw Ke("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Wp)}function ny(e){if(e===void 0)return Wd;if(!Number.isInteger(e)||Number(e)<0)throw Ke("user.getSteamGameList offset 必须是非负整数");return Number(e)}function iy(e){if(e===void 0)return Kd;if(typeof e!="string"||!Zp.has(e))throw Ke("user.getSteamGameList sort 不支持");return e}function oy(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ke("user.getSteamGameList includeHidden 必须是 boolean");return e}function sy(e,t){if(!Array.isArray(e.game_list))throw E("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(ay).filter(a=>a!==void 0),n=Zn(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=Zd(e.is_me);return s!==void 0&&(o.isMe=s),o}function ay(e){const t=Jd(e),r=Zn(t.appid),n=Zn(t.steam_appid)??r,i=os(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};Ui(o,"image",t.image),typeof t.vertical_head_image=="string"&&Ui(o,"portraitImage",t.vertical_head_image),Ui(o,"icon",t.appicon??t.icon),_a(o,"playtimeForever",t.playtime_forever),_a(o,"playtime2Weeks",t.playtime_2weeks);const s=cy(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function Ta(e,t){if(!G(e))throw E("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 E(n,r)}if(!G(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Jd(e){return G(e)?e:{}}function os(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function cy(e){return Array.isArray(e)?e.map(os).filter(Boolean):[]}function Zn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function Zd(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function Ui(e,t,r){const n=os(r);n&&Object.assign(e,{[t]:n})}function _a(e,t,r){const n=Zn(r);n!==void 0&&Object.assign(e,{[t]:n})}function Ke(e){return E("INVALID_PARAMS",e)}function ba(e){return G(e)&&typeof e.code=="string"&&typeof e.message=="string"}function dy(e){return{[yn]:async t=>(Oa(t,"user.getInfo"),e.user.getInfo()),[En]:async(t,r)=>{Oa(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[wn]:async t=>e.user.getSteamGameList(t)}}function Oa(e,t){if(e!==void 0)throw E("INVALID_PARAMS",`${t} 不接收入参`)}function va(e){throw{code:"INVALID_PARAMS",message:e}}function er(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Xd(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function $r(e,t,r){return Math.min(Xd(e,t),r)}async function uy(e){try{return Xd(await e.getNavigationBarHeight(),0)}catch{return 0}}function ly(e,t,r,n){const i=$r(e.safeArea?.left,0,t),o=Math.max(i,$r(e.safeArea?.right,t,t)),s=$r(e.safeArea?.top,n,r),a=Math.max(s,$r(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Ca(e){const t=e.getViewportMetrics(),r=er(t.windowWidth,0),n=er(t.windowHeight,0),i=await uy(e);return{pixelRatio:er(t.pixelRatio,1),screenWidth:er(t.screenWidth,r),screenHeight:er(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:ly(t,r,n,i),screenTop:i}}function fy(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;Ca(r.presentation).then(l=>{if(n||r.operationContext.signal.aborted||f!==i)return;const h=JSON.stringify(l);h!==o&&(o=h,r.onViewportChange?.(l))}).catch(()=>{})},c=Ug({...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:{[ht]:async(f,l)=>c.apply(f,l?.signal),[Nn]:async()=>(W(r.operationContext.signal),Ca(r.presentation)),[Dn]:async f=>{if(W(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return va("viewport.setNavigationBarStyle 参数必须是对象");const l=f.foregroundStyle;if(l!=="light"&&l!=="dark")return va("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await K(()=>r.presentation.setNavigationBarStyle(l,e.operationContext),r.operationContext.signal)}},runDisplayRequest:c.runDisplayRequest,applyOrientation:(f,l)=>c.apply({orientation:f.mode,fullscreen:f.hideCapsule},l),notifyChange:()=>{o=void 0,a()},dispose:d}}const hy=new Map(Ze.map(e=>[e.method,e]));function nn(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function my(e){const t=_l(e);return r=>t(r.requirement,r.method)}function gy(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 py(e){const t=my(e.runtimePermissions),r=Oe(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??yy,c=e.onTrace?a():0,d=e.onTrace?`cap_${++n}`:"";try{if(e.terminalSignal.aborted)throw nn("RUNTIME_DESTROYED","小程序 Runtime 已终止");Hl(i,e.effectiveCapabilities);const u=hy.get(i);if(!u)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const f=t(u),l=!f.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,o)===!0,h=!f.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,o)===!0;if(!f.allowed&&!l&&!h)throw nn(f.code,f.message,f.data);const w=e.handlers[i];if(!w)throw new Error(`Capability method ${i} 缺少 handler`);const A=async b=>{for(const S of e.policies??[]){const R=await S.evaluate({method:i,payload:o,capability:u});if(e.terminalSignal.aborted||b.aborted)throw Pa();if(!R.allowed)throw nn(R.code,R.message,R.data)}if(e.terminalSignal.aborted||b.aborted)throw Pa()},M=await gy(async()=>{if(i===ht){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,A)}return await A(e.terminalSignal),w(o,s)},void 0,s,e.terminalSignal);return La(e.onTrace,Ra(d,i,o,c,M),a),M}catch(u){throw La(e.onTrace,Ra(d,i,o,c,{status:"error",error:u}),a),u}}}}function yy(){return typeof performance>"u"?Date.now():performance.now()}function La(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 Ra(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:Ey(i.error)}:{},...wy(t,r,i)}}function Ey(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function wy(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"&&eu(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 eu(e){return typeof e=="object"&&e!==null}function Pa(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Iy(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=bf(e.requestPolicy);let n;if(e.files)try{n=Ef(e.files,t)}catch{}const i=Jc({store:n}),o=e.onRequestPolicyReport??(r.debugReport?Ay:void 0),s=r.enabled?Df({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Zo(e.files,e.miniProgramDetail),c=Ym({registry:a,picker:e.picker,operationContext:t}),d=eh({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode,authorizationContext:e.authorizationContext,identityTtlMs:r.identityTtlMs,requestGate:s,requestPolicyEnabled:r.enabled});let u,f,l,h,w,A=()=>{},T=()=>{};try{u=fy({operationContext:t,presentation:e.hostPresentation,onDisplayChange:m=>e.eventSink.postEvent("display_change",m),onViewportChange:m=>e.eventSink.postEvent("viewport_change",m)}),l=ey({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}),A=d.onEvent((m,I)=>e.eventSink.postEvent(m,I)),T=e.hostCompanion?.onSessionEvent?.(m=>{const I=Hm(m);!e.terminalSignal.aborted&&I&&e.eventSink.postEvent(I.type,I.payload)})??(()=>{}),h=kh({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled}),w=Sm({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 M=Rp({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});f=mg({registry:a,media:e.media,operationContext:t});const b=[{name:"gameSaves",handlers:w.handlers},{name:"auth",handlers:ch({authorization:d})},{name:"user",handlers:dy({user:l,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:Op({prepareScreenshot:e.prepareScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:u.handlers},{name:"storage",handlers:M.handlers},{name:"network",handlers:qg({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[mn]:async()=>{throw nn("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:Up({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Gm({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:zg({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:m=>u.applyOrientation({mode:"portrait",hideCapsule:!1},m)}:{}})},{name:"cloud",handlers:h.handlers},{name:"companion",handlers:km({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],S=My(b);let R=!1;const B=()=>{R||(R=!0,e.terminalSignal.removeEventListener("abort",B),u?.dispose(),f?.dispose(),h?.dispose(),w?.dispose(),A(),T(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?B():e.terminalSignal.addEventListener("abort",B,{once:!0});const U=new Set(["file.readText","file.readBytes","file.stat"]),p=(m,I)=>U.has(m)&&eu(I)&&a.isCompanionAttachmentRef(I.target);return{modules:b,handlers:S,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:p,allowsGameSaveAccess:w.allowsRead,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...M.diagnostics?{storageDiagnostics:M.diagnostics}:{},dispose:B}}catch(M){throw u?.dispose(),f?.dispose(),h?.dispose(),w?.dispose(),A(),T(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),M}}function Ay(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function My(e){const t=new Map(Ze.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=Ze.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Ze.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Ny="heybox-mini-dev:";function ka(e){try{return Dy(new URL(e))}catch{return!1}}function Dy(e){return e.protocol===Ny}function Sy(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Ty(e)}function Ty(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 _y=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function by(e,t){const r=[],n=Oy(e.environmentInfo,r),i=on(n?.appVersion,"host.appVersion",r),o=Cy(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:vy(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:on(t.miniProgramId),version:on(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function Oy(e,t){if(e!=null){if(tu(e))return e;t.push("environmentInfo")}}function vy(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function Cy(e,t){if(e==null)return{name:"unknown",version:null};if(!tu(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=_y.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:on(e.version,"operatingSystem.version",t)}}function on(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function tu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Ly="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",Ry="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",Py="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",ky="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function xy(e,t,r,n,i="dark"){W(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?Py:Ly,l.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const h=e.createElement("div");h.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${c};border-radius:11px;padding:0 7px 0 6px;`;const w=e.createElement("img");w.src=a?ky:Ry,w.style.cssText="width:12px;height:12px;flex-shrink:0;";const A=e.createElement("span");A.textContent=t?.trim()||"小程序工坊",A.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const T=e.createElement("div");T.textContent="小黑盒工坊小程序",T.style.cssText=`margin-top:6px;color:${a?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,h.append(w,A),f.append(l,h),u.append(f,T),s.append(u),e.body.append(s);const M=()=>{s.remove(),n.removeEventListener("abort",M)};n.addEventListener("abort",M,{once:!0});try{return await K(()=>Promise.all([l.decode(),w.decode()]),n),await K(()=>new Promise(b=>{let S=o.requestAnimationFrame(()=>{S=o.requestAnimationFrame(()=>{n.removeEventListener("abort",R),b()})});const R=()=>o.cancelAnimationFrame(S);n.addEventListener("abort",R,{once:!0})}),n),M}catch(b){throw M(),b}}const jy=1,ru="allow-scripts allow-same-origin",Uy="",zy="no-referrer";function Hy(e=ru){return!e.split(/\s+/).includes("allow-same-origin")}function xa(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Fy=new Set(["javascript:","data:","blob:","file:"]),ja="xiaoheihe.cn";function Vy(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(Fy.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!qy(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function By(e,t){const r=new URL(e);return r.searchParams.set(ol,t),r.toString()}function Gy(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Qy(r)??Yy(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Qy(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Yy(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function Ua(e){const t=new URL(e);return ss(t)?"loopback":as(t)?"lan":"production"}function qy(e,t,r){return $y(e)||ss(e)||as(e)&&Ky(t,r)}function $y(e){return e.protocol==="https:"&&Xy(e.hostname)}function ss(e){return e.protocol==="http:"&&Wy(e.hostname)}function Wy(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function as(e){return e.protocol==="http:"&&Jy(e.hostname)}function Ky(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return ss(r)||as(r)}catch{return!1}}function Jy(e){const t=Zy(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Zy(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 Xy(e){return e===ja||e.endsWith(`.${ja}`)}const eE=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"]),tE=new Set(["url","inline","eval","unknown"]),rE=/^\/(?:\:segment(?:\/\:segment)*)?$/,nE=/^[a-f0-9]{64}$/,iE=255,oE=160,sE=256;function aE(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!eE.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>sE||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!tE.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=cE(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>oE||!rE.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!nE.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 cE(e){if(e!==void 0&&!(typeof e!="string"||e.length>iE))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const dE=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function uE(e){if(!e?.minimumSdkVersion)throw ee("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=ct(e.minimumSdkVersion),r=e.sdkVersion?ct(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=ct("0.6.0");if(!r){if(sn(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(sn(r,t)<0)throw ee("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:sn(r,ct("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function lE(e,t){if(typeof t!="string"||!ct(t))throw ee("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw ee("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function nu(e,t){const r=ct(e),n=ct(t);if(!(!r||!n))return sn(r,n)}function ct(e){const t=dE.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 sn(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 pi=["android","ios","ohos","windows","macos","linux"],fE="0.9.0",hE=Object.freeze(["android","ios","ohos","windows","macos"]),iu="该小程序暂不支持当前平台",mE="PLATFORM_UNSUPPORTED";function gE(e){return typeof e=="string"&&pi.includes(e)}function pE(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 yE(e){const t=e.manifest;if(!ME(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Ha(e.sdkVersion)??Ha(t.sdkVersion);return IE(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:wE()}const r=ou(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function EE(e){const t=pE(e.operatingSystemName);if(!t)return Ot("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Ot("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:pi,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=yE({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Ot("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):za(t,s)}if(r.effectivePlatforms===void 0)return Ot("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=ou(r.effectivePlatforms);if("reason"in n)return Ot("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=AE(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return za(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function za(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Ot("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Ot(e,t={}){return{status:"denied",reason:e,message:iu,...t}}function wE(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:hE,platformsDeclared:!1,policy:"legacy_mobile_default"}}function ou(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(!gE(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(pi.filter(r=>t.has(r)))}}function IE(e){if(typeof e!="string"||!e.trim())return!1;const t=nu(e.trim(),fE);return t!==void 0&&t>=0}function Ha(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function AE(e){return e==="explicit"||e==="legacy_mobile_default"}function ME(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const NE=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 DE(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:SE(i.pathname),sanitizedPathnameHash:TE(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function SE(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function TE(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 T=0;T<16;T+=1)o[T]=s.getUint32(a+T*4,!1);for(let T=16;T<64;T+=1){const M=o[T-15],b=o[T-2],S=ke(M,7)^ke(M,18)^M>>>3,R=ke(b,17)^ke(b,19)^b>>>10;o[T]=o[T-16]+S+o[T-7]+R>>>0}let[c,d,u,f,l,h,w,A]=i;for(let T=0;T<64;T+=1){const M=A+(ke(l,6)^ke(l,11)^ke(l,25))+(l&h^~l&w)+NE[T]+o[T]>>>0,b=(ke(c,2)^ke(c,13)^ke(c,22))+(c&d^c&u^d&u);A=w,w=h,h=l,l=f+M>>>0,f=u,u=d,d=c,c=M+b>>>0}[c,d,u,f,l,h,w,A].forEach((T,M)=>{i[M]=i[M]+T>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ke(e,t){return e>>>t|e<<32-t}const _E=1e4,bE=1e4,zi=2e3,OE=2,vE="open-with-native-credential-policy",su="安全提示",au="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class CE{nonce=xa();runtimeId=xa();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=Kc(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??_E,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics;return t?{storage:t}:{}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??ee("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??ee("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(HE(),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=bl(t.runtimePermissions),this.runtimeFeatures=t.runtimeFeatures?Object.freeze({...t.runtimeFeatures}):void 0,this.miniProgramPresentation=t.miniProgramPresentation,this.locationBasePath=t.locationBasePath,this.anonymousStorageScope=t.anonymousStorageScope??this.options.anonymousStorageScope;const r=t.allowedHttpOrigins??this.options.allowedHttpOrigins;this.allowedHttpOrigins=r?Object.freeze([...r]):void 0,this.bindCanonicalIdentity(t.canonicalIdentity),this.sdkVersionDecision=uE(t.sdkVersionPolicy);const n=by(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=EE({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw BE(this.platformGateDecision);if(this.miniProgramDetail=GE(t),this.effectiveCapabilities=Wc(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),kE(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(jE(i)),this.launchUrl=i,this.miniProgramSrc=By(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=Yo(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:ht,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ge(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[ht])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=Iy({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||(nu(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):xy(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=py({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}:{}};Ge(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new Pl({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 PE(t)?t:cu(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 Vy(t,r,{allowPrivateNetwork:ka(r)||Fa(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??zE)({message:au,title:su,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Ua(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!ka(r)&&!Fa(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{Va(),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(()=>Va())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Uy),this.iframe.setAttribute("referrerpolicy",zy),this.iframe.setAttribute("sandbox",ru)}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(),Ge(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(),Ge(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{lE(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>=OE)){this.failRuntime(ee("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Hr,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:Hr})}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(Hr,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Hr})}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?bE: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===al){this.handleCspViolation(t.payload);return}if(t.method!==sl)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"||!Gy(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=aE(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){Ge(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=DE(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:jy,launchUrlType:Ua(t),networkPolicy:vE})}failRuntime(t){const r=LE(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),Ge(this.options.onError,RE(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,Ge(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ge(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 LE(e){const t=Yo(e);return Xn(e)&&"cause"in e&&cu(t,e.cause),t}function cu(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function RE(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function PE(e){return Xn(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Xn(e){return!!e&&typeof e=="object"}function Ge(e,t){try{e?.(t)}catch{}}function kE(e,t,r){try{e?.(t,r)}catch{}}function Fa(e){try{const t=new URL(e);return t.protocol==="http:"&&Sy(t.hostname)}catch{return!1}}function xE(e){try{return new URL(e).origin}catch{return}}function jE(e){return Hy()?"*":xE(e)}function UE(e){return`${su}
1
+ import{H as gs,aD as xu,b2 as ju,P as Uu,aN as zu,aO as Hu,ap as Rr,bc as Z,ag as Fu,aq as vc,aw as Vu,b6 as Bu,r as Gu,as as Qu,f as Yu,aK as Lc,ae as qu,az as Cc,u as $u,aF as Rc,q as Wu,aJ as Ku,ab as Ju,b4 as Zu,b3 as Xu,e as el}from"./desktop-app-launch-BXS6eaj9.js";const mn="workspaceCards.requestRefresh",gn="auth.getAccountState",pn="auth.login",tl="gameSaves.list",rl="gameSaves.sync",nl="gameSaves.getFile",il="gameSaves.readParsedData",yn="user.getInfo",En="user.revokeAuthorization",wn="user.getSteamGameList",In="share.copyLink",An="share.showShareMenu",Mn="share.screenshot",ht="viewport.setDisplay",Nn="viewport.getWindowInfo",Dn="viewport.setNavigationBarStyle",gr="storage.getStorage",pr="storage.setStorage",Sn="network.request",Tn="network.download",_n="network.upload",bn="files.pickFiles",On="files.pickDirectory",vn="files.saveFile",yr="file.create",Er="file.remove",Ln="file.exists",wr="file.readText",Cn="file.writeText",Ir="file.readBytes",Rn="file.writeBytes",Ar="file.stat",Pn="directory.create",Mr="directory.remove",kn="directory.exists",xn="directory.list",Nr="media.pick",jn="ui.showToast",Un="ui.showLoading",zn="ui.hideLoading",Hn="device.vibrate",Fn="device.setClipboard",Vn="device.executeProtocol",Bn="navigation.close",Gn="navigation.reload",Qn="navigation.openAppPage",Be="cloud.leaderboard.submit",be="cloud.leaderboard.getList",Je="cloud.leaderboard.getCurrentUserEntry",mt="cloud.leaderboard.deleteCurrentUserEntry",Ue="cloud.leaderboard.getInfo",kt="cloud.storage.getStorage",xt="cloud.storage.setStorage",jt="cloud.storage.removeItem",gt="cloud.storage.getKeys",ri="companion.getInfo",ni="companion.getPreparationStatus",ii="companion.prepare",oi="companion.cancelPreparation",si="companion.getActiveSession",ai="companion.launch",ci="companion.session.write",di="companion.session.closeStdin",ui="companion.session.terminate",li="companion.session.ackOutput",fi="companion.openAttachment",hi="companion.showNotification",Ze=[...[tl,rl,nl,il].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),{method:mn,module:"workspaceCards",capability:mn,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:gn,module:"auth",capability:gn,requirement:{kind:"none"},risk:"low"},{method:pn,module:"auth",capability:pn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:yn,module:"user",capability:yn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:En,module:"user",capability:En,requirement:{kind:"none"},risk:"high"},{method:wn,module:"user",capability:wn,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:In,module:"share",capability:In,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:An,module:"share",capability:An,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Mn,module:"share",capability:Mn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Nn,module:"viewport",capability:Nn,requirement:{kind:"none"},risk:"low"},{method:Dn,module:"viewport",capability:Dn,requirement:{kind:"none"},risk:"low"},{method:ht,module:"viewport",capability:ht,requirement:{kind:"none"},risk:"low"},{method:gr,module:"storage",capability:gr,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:pr,module:"storage",capability:pr,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Sn,module:"network",capability:Sn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Tn,module:"network",capability:Tn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:_n,module:"network",capability:_n,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:bn,module:"files",capability:bn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:On,module:"files",capability:On,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:vn,module:"files",capability:vn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:yr,module:"file",capability:yr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Er,module:"file",capability:Er,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ln,module:"file",capability:Ln,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:wr,module:"file",capability:wr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Cn,module:"file",capability:Cn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ir,module:"file",capability:Ir,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Rn,module:"file",capability:Rn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ar,module:"file",capability:Ar,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Pn,module:"directory",capability:Pn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mr,module:"directory",capability:Mr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:kn,module:"directory",capability:kn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:xn,module:"directory",capability:xn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Nr,module:"media",capability:Nr,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:jn,module:"ui",capability:jn,requirement:{kind:"none"},risk:"low"},{method:Un,module:"ui",capability:Un,requirement:{kind:"none"},risk:"low"},{method:zn,module:"ui",capability:zn,requirement:{kind:"none"},risk:"low"},{method:Hn,module:"device",capability:Hn,requirement:{kind:"none"},risk:"low"},{method:Fn,module:"device",capability:Fn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Vn,module:"device",capability:Vn,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:Bn,module:"navigation",capability:Bn,requirement:{kind:"none"},risk:"medium"},{method:Gn,module:"navigation",capability:Gn,requirement:{kind:"none"},risk:"medium"},{method:Qn,module:"navigation",capability:Qn,requirement:{kind:"none"},risk:"medium"},{method:Be,module:"cloud",capability:Be,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:be,module:"cloud",capability:be,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Je,module:"cloud",capability:Je,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:mt,module:"cloud",capability:mt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ue,module:"cloud",capability:Ue,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:kt,module:"cloud",capability:kt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:xt,module:"cloud",capability:xt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:jt,module:"cloud",capability:jt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:gt,module:"cloud",capability:gt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[ri,ni,ii,oi,si,ai,ci,di,ui,li,fi,hi].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],ot="heybox:miniprogram",Pc=2,ol="hb_mini_bridge_nonce",kc="sdk.handshake",Hr="runtime.location.probe",sl="sdk.location.report",al="sdk.csp.violation",xc="operation.progress",cl="companion.session.output",dl="companion.session.exit",ul="companion.session.ownershipLost";function ll(e){return!Ce(e)||e.namespace!==ot||e.version!==1&&e.version!==2||!oe(e.nonce)?!1:e.type==="handshake"?oe(e.id)&&e.method===kc&&e.error===void 0&&wl(e.payload):e.type==="request"?oe(e.id)&&oe(e.method)&&e.error===void 0:e.type==="response"?oe(e.id)&&(e.method===void 0||oe(e.method))&&(e.error===void 0||Il(e.error)):e.type==="event"?!oe(e.method)||e.error!==void 0?!1:e.method===xc?e.version===2&&oe(e.id)&&El(e.payload):e.id===void 0||oe(e.id):e.type==="cancel"?e.version===2&&oe(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Go(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function jc(e){return Ce(e)?e.kind==="sandbox"?Se(e,["kind"]):e.kind==="directory"&&oe(e.handleId)&&Se(e,["kind","handleId"]):!1}function Ut(e){return!Ce(e)||e.kind!=="file"?!1:oe(e.handleId)?Se(e,["kind","handleId"]):jc(e.root)&&Go(e.relativePath)&&Se(e,["kind","root","relativePath"])}function Uc(e){return!Ce(e)||e.kind!=="directory"?!1:oe(e.handleId)?Se(e,["kind","handleId"]):jc(e.root)&&(e.relativePath==="."||Go(e.relativePath))&&Se(e,["kind","root","relativePath"])}function fl(e){return Ce(e)&&e.kind==="file"&&oe(e.name)&&Al(e.mode)&&Ut(e.ref)&&Se(e,["kind","name","mode","ref"])}const zc=20,ps=["type","mimeType","size","width","height","previewUrl","file"];function hl(e){return e===void 0?!0:!(!Ce(e)||!Se(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&&(!Ml(e.maxCount,1,zc)||e.source==="camera"&&e.maxCount!==1))}function Hc(e){if(!Ce(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!Se(e,t?[...ps,"durationMs"]:ps)||!oe(e.mimeType)||!$e(e.size)||!ys(e.width)||!ys(e.height)||!oe(e.previewUrl)||!gl(e.file)?!1:t?$e(e.durationMs):!0}function ml(e){if(!Array.isArray(e)||e.length<1||e.length>zc)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!Hc(e[t]))return!1;return!0}function gl(e){return!fl(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&oe(e.ref.handleId)}function Fc(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function pl(e){return!Ce(e)||!$e(e.loaded)||typeof e.lengthComputable!="boolean"||!Se(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?$e(e.total)&&e.loaded<=e.total:e.total===void 0}function yl(e){return Ce(e)?e.phase==="downloading"?$e(e.loaded)&&(e.total===void 0||$e(e.total)&&e.loaded<=e.total)&&Se(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:$e(e.processed)&&$e(e.total)&&e.processed<=e.total&&Se(e,["phase","processed","total"]):!1}function El(e){return pl(e)||yl(e)}function wl(e){return Ce(e)&&oe(e.href)&&typeof e.userAgent=="string"&&oe(e.sdkVersion)}function Il(e){return Ce(e)&&oe(e.code)&&typeof e.message=="string"}function Al(e){return e==="read"||e==="readwrite"}function $e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ys(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Ml(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function oe(e){return typeof e=="string"&&e.length>0}function Se(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Ce(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Dr=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards"],Vc=[{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(Dr);const Nl=new Set(Dr);function Dl(e){return Nl.has(e)}function Oe(e){if(!Fr(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(!Fr(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),!!Dl(o)){if(o==="network"){const s=n.config;if(!Fr(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&&(!Fr(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 Fr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Zr=["network","companion","appProtocol"];function Bc(e){if(!Wt(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>Zr.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Wt(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(!Wt(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(!Wt(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Wt(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>Zr.indexOf(n.key)-Zr.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Sl(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Oe(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of Zr)!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 Qo(e){const t=Oe(e.runtimePermissions),r=Bc(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of Dr)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:Vc.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=Gc(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:Dr.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function Gc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wt(e,t){return Gc(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const zt=["identity","profile","steam_account"],Tl=/^[a-z][a-z0-9-]{0,31}$/,Qc=["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"];Ze.map(e=>e.method);function _l(e){const t=Oe(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 bl(e){const t=Oe(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 Yo(e){return Ol(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?ee("RUNTIME_ERROR",e.message):ee("UNKNOWN_ERROR","小程序运行时异常",e)}function Ol(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function vl(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Ll=1e3;function Cl(e,t=vl()){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<=Ll}const Rl="runtime.gate.probe",Yc=new Set(Ze.map(e=>e.method));class Pl{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=Pc;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:ot,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:ot,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:ot,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:ot,version:2,nonce:this.nonce,type:"event",id:t,method:xc,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=Cl(this.iframe,{activeElement:document.activeElement,userActivation:navigator.userActivation,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{n=!1}this.handleRequest(r,n);return}if(r.type==="cancel"&&this.handshaken&&r.id){this.operations.get(r.id)?.abort();return}r.type==="event"&&this.handshaken&&this.onInternalEvent?.(r)}onUserInteraction(t){const r=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||r.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&ll(t.data)&&(!this.handshaken||t.data.version===this.bridgeVersion)&&((this.handshaken?this.bridgeVersion:t.data.version)===1||this.targetOrigin==="*"||t.origin===this.targetOrigin)&&t.data.nonce===this.nonce}handleHandshake(t,r){const n=t.payload,i=t.version,o=!this.handshaken;if(o){if(this.onHandshake?.(n)===!1)return;this.bridgeVersion=i,i===1&&this.targetOrigin!=="*"&&r&&r!=="null"&&(this.targetOrigin=r),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.environmentInfo&&t.id&&this.postMessage({namespace:ot,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:kc,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===Rl){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,ee("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Yc.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=Yo(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:ot,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!kl(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 kl(e){return typeof e=="string"&&Yc.has(e)}function xl(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 qc="METHOD_FORBIDDEN";function Ne(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=qc,t}class ue 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 jl=/^[A-Za-z0-9_-]{1,64}$/,Es=1e3;function $c(e){return jl.test(e)?e:zl(e)}function Ul(e){return`id_${$c(e.trim())}`}function It(e,t){return`hb_miniprogram_${e}_${t}`}function Vr(e){return`hb_miniprogram_keys_${e}`}function zl(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 ws={"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"],[mn]:["workspaceCards.requestRefresh"],[gn]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[pn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[yn]:["account.getCurrentUserId","account.onChange","network.request"],[En]:["account.getCurrentUserId","account.onChange","network.request"],[wn]:["account.getCurrentUserId","account.onChange","network.request"],[In]:["presentation.setClipboard"],[An]:["presentation.showShareMenu"],[Mn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ht]:["presentation.applyOrientation"],[Nn]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Dn]:["presentation.setNavigationBarStyle"],[gr]:["storage.getRaw"],[pr]:["storage.setRaw"],[Sn]:["network.request"],[Tn]:["network.stream","files.transfer","files.access"],[_n]:["network.upload","files.access"],[bn]:["files.external"],[On]:["files.external"],[vn]:["files.save"],[yr]:["files.access"],[Er]:["files.removeFile"],[Ln]:["files.access"],[wr]:["files.access"],[Cn]:["files.access"],[Ir]:["files.access"],[Rn]:["files.access"],[Ar]:["files.access"],[Pn]:["files.access"],[Mr]:["files.removeDirectory"],[kn]:["files.access"],[xn]:["files.access"],[Nr]:["media.pick"],[jn]:["presentation.showToast"],[Un]:["presentation.showLoading"],[zn]:["presentation.hideLoading"],[Hn]:["presentation.vibrate"],[Fn]:["presentation.setClipboard"],[Vn]:["protocol.invoke"],[Bn]:["presentation.close"],[Gn]:["presentation.reload"],[Qn]:["presentation.openAppPage"],[Be]:["account.getCurrentUserId","account.onChange","network.request"],[be]:["account.onChange","network.request"],[Je]:["account.getCurrentUserId","account.onChange","network.request"],[mt]:["account.getCurrentUserId","account.onChange","network.request"],[Ue]:["account.onChange","network.request"],[kt]:["account.getCurrentUserId","account.onChange","network.request"],[xt]:["account.getCurrentUserId","account.onChange","network.request"],[jt]:["account.getCurrentUserId","account.onChange","network.request"],[gt]:["account.getCurrentUserId","account.onChange","network.request"],[ri]:["companion.getInfo"],[ni]:["companion.getPreparationStatus"],[ii]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[oi]:["companion.cancelPreparation"],[si]:["companion.getActiveSession"],[ai]:["companion.getInfo","companion.launch"],[ci]:["companion.session.write"],[di]:["companion.session.closeStdin"],[ui]:["companion.session.terminate"],[li]:["companion.session.ackOutput"],[fi]:["companion.openAttachment"],[hi]:["companion.showNotification"]};function Hl(e,t){if(t[e]!==!0)throw Ne(e)}const Fl=32*1024*1024,Vl=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Bl(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:Fl},i);return Gl(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Gl(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:Ql(t,ql(e,"content-type"))}}function Ql(e,t){Yl(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new ue("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!Vl.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function Yl(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new ue(`Host network response 不支持 charset=${t}`)}function ql(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function j(e){return typeof e=="function"}function Is(e){return(...t)=>{throw Ne(e)}}function ae(e){return async(...t)=>{throw Ne(e)}}const $l=(e,t)=>{},Wl=()=>()=>{};function Kl(e){const t={request:j(e.network?.request)?e.network.request.bind(e.network):ae("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):ae("account.getCurrentUserId"),ensureAuthenticated:j(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):ae("account.ensureAuthenticated"),onChange:j(e.account?.onChange)?e.account.onChange.bind(e.account):Wl},n={getRaw:j(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):ae("storage.getRaw"),setRaw:j(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):ae("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):ae("presentation.close"),reload:j(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):ae("presentation.reload"),openAppPage:j(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):ae("presentation.openAppPage"),openWindow:j(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):ae("presentation.openWindow"),getViewportMetrics:j(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Is("presentation.getViewportMetrics"),getNavigationBarHeight:j(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Is("presentation.getNavigationBarHeight"),setNavigationBarStyle:j(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):ae("presentation.setNavigationBarStyle"),showShareMenu:j(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):ae("presentation.showShareMenu"),setScreenshotChromeHidden:j(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):$l,captureAndShare:j(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):ae("presentation.captureAndShare"),showToast:j(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):ae("presentation.showToast"),showLoading:j(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):ae("presentation.showLoading"),hideLoading:j(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):ae("presentation.hideLoading"),vibrate:j(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):ae("presentation.vibrate"),setClipboard:j(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):ae("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):ae(`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):ae("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 Jl(e){const t=Zl(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.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 Zl(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 As(e,t){return t?.[e]!==!1}function Xl(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function Wc(e,t={}){const r={};for(const n of Object.keys(ws)){const o=ws[n].every(a=>e[a]),s=!Xl(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=As(n,t.callerCapabilities)&&As(n,t.hostCapabilities)&&o&&s}return r}function Kc(e={},t={}){const r=Jl(e),n=Wc(r,t);return{ports:Kl(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function ve(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):ef(e.signal,t);return{...e,signal:r}}function ef(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 tf(e){if(!e||typeof e!="object"||e.lifecycle!=="cleanup")return!1;const t=e.signal;return!!t&&typeof t=="object"&&typeof t.aborted=="boolean"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"}const rf=4,nf=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],of=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),sf=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],af=["/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 cf(e,t){const r=lf(e);return r===null||Ms(r,sf)?!0:t&&Ms(r,af)}function df(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return nf.some(r=>t===r||t.endsWith(`.${r}`))}function uf(e){const t=e.trim().toLowerCase();return of.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function lf(e){let t=e;for(let r=0;r<rf;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Ns(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Ns(t)}function Ms(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Ns(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function At(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Ds(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function Jc(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(A,T){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:A,type:T})).catch(()=>{})}catch{}}function u(A){const T=r.get(A);if(!T)throw new Error("Unknown runtime cache scope");return T}function f(A,T){return A.flatMap((M,b)=>{const S=JSON.stringify(A.slice(0,b+1));return[JSON.stringify([S]),JSON.stringify([S,T])]})}function l(A,T){return JSON.stringify(f(A,T).map(M=>n.get(M)??0))}async function h(A,T){const M=u(A),b=JSON.stringify([JSON.stringify(M),...T?[T]:[]]),S=(n.get(b)??0)+1;n.set(b,S),i.add(b);for(const R of a)R(M,T);if(!e.store){i.delete(b),d(T??"*","invalidation");return}try{await e.store.invalidate(M,T)}catch(R){throw d(T??"*","storage_error"),R}n.get(b)===S&&i.delete(b),d(T??"*","invalidation")}function w(A){if(c)throw new Error("Runtime cache manager disposed");const T=o.get(A.namespace);if(T){if(T.sourceCodec!==A.codec||T.definition.codec.version!==A.codec.version||JSON.stringify(T.definition.policy)!==JSON.stringify(A.policy))throw new Error("Conflicting runtime cache namespace");return T.cache}if(!A.namespace||!A.codec.version)throw new Error("Invalid runtime cache definition");const M=Object.freeze({...A.policy}),b=Object.freeze({version:A.codec.version,encode:A.codec.encode.bind(A.codec),decode:A.codec.decode.bind(A.codec),validate:A.codec.validate.bind(A.codec),clone:A.codec.clone.bind(A.codec)}),S=A.namespace;for(const L of[M.ttlMs,M.memoryMaxEntries,M.diskMaxEntries,M.diskMaxBytes,M.maxEntryBytes])if(!Number.isFinite(L)||L<0)throw new Error("Invalid runtime cache policy");const R=new Map,B=new Map,U=new Map;let p=!1;function g(L,N,O){if(c||p||L.aborted||l(N,S)!==O)throw At()}function I(L){return M.ttlMs>0&&M.persistence==="memory-and-disk"&&!!e.store&&!f(L,S).some(N=>i.has(N))}function y(L,N,O){const C=t();return L.envelopeVersion===1&&JSON.stringify(L.address)===JSON.stringify(N)&&Ds(L.revisions,O)&&L.payload.byteLength<=M.maxEntryBytes&&Number.isFinite(L.cachedAt)&&Number.isFinite(L.expiresAt)&&L.cachedAt<=C&&L.cachedAt>=0&&L.expiresAt>L.cachedAt&&Math.min(L.expiresAt,L.cachedAt+M.ttlMs)>C}function _(L,N,O,C,P){if(!(M.ttlMs<=0||M.memoryMaxEntries<1)){for(const[z,H]of R)Math.min(H.entry.expiresAt,H.entry.cachedAt+M.ttlMs)<=t()&&R.delete(z);for(R.delete(L);R.size>=Math.floor(M.memoryMaxEntries);){const z=R.keys().next();if(z.done)break;R.delete(z.value)}R.set(L,{entry:N,value:O,epoch:C,persistent:P})}}async function m(L,N,O,C){const P={namespace:S,codecVersion:b.version,scopeIds:N,key:L.key},z=JSON.stringify(P);let H=[],F=I(N);if(F)try{H=await e.store.readRevisions(N,S)}catch{F=!1,d(S,"storage_error")}g(C.signal,N,O);async function Q(){if(!F)return!0;try{return Ds(H,await e.store.readRevisions(N,S))}catch{return F=!1,d(S,"storage_error"),!1}}const J=R.get(z);if(M.ttlMs>0&&J&&J.epoch===O&&y(J.entry,P,H)&&J.persistent===F&&await Q())return g(C.signal,N,O),d(S,"memory_hit"),J.value;if(R.delete(z),F){let q,ce;try{q=await e.store.read(P,M.maxEntryBytes),q&&y(q,P,H)?ce=b.decode(q.payload):q=void 0}catch{q=void 0,d(S,"storage_error")}if(g(C.signal,N,O),q&&await Q())return g(C.signal,N,O),_(z,q,ce,O,!0),d(S,"disk_hit"),ce}d(S,"miss");const $=b.validate(await L.load(C.signal));g(C.signal,N,O);const X=b.clone($);if(!await Q()&&F)throw At();if(g(C.signal,N,O),M.ttlMs>0){const q=t();let ce;try{ce=b.encode(X)}catch{return X}const wt={envelopeVersion:1,address:P,revisions:F?H:[],cachedAt:q,expiresAt:q+M.ttlMs,payload:ce};if(F&&ce.byteLength<=M.maxEntryBytes){let ye=!0,Ae=!1;try{ye=await e.store.publish(wt,M),Ae=ye}catch{d(S,"storage_error")}if(g(C.signal,N,O),!ye)throw At();Ae&&d(S,"published")}g(C.signal,N,O),_(z,wt,X,O,F)}return X}async function D(L){if(c||p||L.signal?.aborted)return Promise.reject(At());const N=u(L.scope),O=l(N,S);let C;if(I(N)){const F=new AbortController;U.set(F,N);const Q=()=>F.abort();L.signal?.addEventListener("abort",Q,{once:!0});let J=()=>{};try{C=await Promise.race([e.store.readRevisions(N,S),new Promise(($,X)=>{const q=()=>X(At());F.signal.addEventListener("abort",q,{once:!0}),J=()=>F.signal.removeEventListener("abort",q)})])}catch{F.signal.aborted||d(S,"storage_error")}finally{J(),U.delete(F),L.signal?.removeEventListener("abort",Q)}}g(L.signal??new AbortController().signal,N,O);const P=JSON.stringify([N,L.key,O,C]);let z=B.get(P);if(z?.controller.signal.aborted&&(z=void 0),!z){const F=new AbortController;z={ids:N,controller:F,waiters:0,promise:Promise.resolve(void 0)};const Q=z;Q.promise=m(L,N,O,F).finally(()=>{B.get(P)===Q&&B.delete(P)}),B.set(P,Q)}const H=z;return H.waiters+=1,new Promise((F,Q)=>{let J=!1;function $(q){J||(J=!0,L.signal?.removeEventListener("abort",X),H.controller.signal.removeEventListener("abort",X),H.waiters-=1,H.waiters===0&&H.controller.abort(),q())}function X(){$(()=>Q(At()))}L.signal?.addEventListener("abort",X,{once:!0}),H.controller.signal.addEventListener("abort",X,{once:!0}),H.promise.then(q=>$(()=>{try{g(L.signal??new AbortController().signal,N,O),F(b.clone(q))}catch(ce){Q(ce)}}),q=>$(()=>Q(q)))})}function v(L,N){if(N&&N!==S)return;const O=C=>L.every((P,z)=>C[z]===P);for(const[C,P]of R)O(P.entry.address.scopeIds)&&R.delete(C);for(const[C,P]of B)O(P.ids)&&(P.controller.abort(),B.delete(C));for(const[C,P]of U)O(P)&&C.abort()}function k(){if(!p){p=!0,R.clear();for(const L of U.keys())L.abort();U.clear();for(const L of B.values())L.controller.abort();B.clear(),s.delete(k),a.delete(v),o.get(S)?.cache===x&&o.delete(S)}}const x={read:D,invalidateScope:L=>h(L,S),dispose:k};return s.add(k),a.add(v),o.set(S,{definition:{namespace:S,codec:b,policy:M},sourceCodec:A.codec,cache:x}),x}return{createScope(A,T){if(c||!A)throw new Error("Invalid runtime cache scope");const M=Object.freeze({});return r.set(M,[...T?u(T):[],A]),M},register:w,invalidateScope:A=>h(A),dispose(){if(!c){c=!0;for(const A of[...s])A();o.clear(),n.clear(),i.clear()}}}}function ff(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 hf=".hb-runtime-cache-v1",mf=1e3,Di=64*1024,Mt=1e3,gf=2048,Kt=32*1024*1024,pf=1024,Xr=new TextEncoder,Ss=new TextDecoder("utf-8",{fatal:!0});function Jt(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Br(e){const t=await globalThis.crypto.subtle.digest("SHA-256",Xr.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Re(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Ts(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function yf(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 Ef(e,t){const r=e.sandbox.directory(hf),n=r.directory("revisions"),i=r.directory("entries");for(const m of[r,n,i,i.directory("capability-check")])_s(m,["directory","file","create","stat","list","remove"]),_s(m.file("capability-check"),["create","stat","read","write","remove"]);const o=new AbortController,s=()=>o.abort();t.signal.aborted?s():t.signal.addEventListener("abort",s,{once:!0});const a={...t,signal:o.signal};let c=Promise.resolve(),d;function u(m){d=m,o.abort(),t.signal.removeEventListener("abort",s)}function f(m){if(yf(m))throw u(m),m}function l(){if(d)throw d;if(a.signal.aborted)throw Jt()}function h(m,D=a.signal){const v=c.then(()=>{if(D.aborted)throw d??Jt();return l(),m()},()=>{if(D.aborted)throw d??Jt();return l(),m()}).catch(N=>{throw f(N),N});if(c=v.catch(()=>{}),D.aborted)return Promise.reject(d??Jt());let k=()=>{};const x=new Promise((N,O)=>{const C=()=>O(d??Jt());D.addEventListener("abort",C,{once:!0}),k=()=>D.removeEventListener("abort",C)}),L=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},mf);return Promise.race([v,x]).finally(()=>{clearTimeout(L),k()})}async function w(){l(),await n.create({recursive:!0,exclusive:!1},a),l(),await i.create({recursive:!0,exclusive:!1},a),l()}async function A(m,D){const v=n.file(`${await Br([m,D??null])}.revision`);await M(v);let k=!1;try{await v.create({recursive:!1,exclusive:!0},a),k=!0}catch(N){f(N),l()}if(k){const N=Ts();return await v.write(Xr.encode(N),a),l(),N}const x=await v.stat(a);if(x.size<1||x.size>128)throw new Error("缓存 revision 文件损坏");const L=Ss.decode(await v.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(L))throw new Error("缓存 revision 文件损坏");return l(),L}async function T(m){const D=await m.list({limit:Mt},a);if(D.length>=Mt)throw new Error("缓存目录超过治理上限");return D}async function M(m){try{await m.stat(a);return}catch(v){if(!Gr(v))throw v}if((await T(n)).length>=Mt-1)throw new Error("缓存 metadata 超过治理上限")}async function b(m,D){await w();const v=[];for(let k=0;k<m.length;k+=1){const x=m.slice(0,k+1);v.push(await A(x),await A(x,D))}return v}async function S(m){return r.directory(`entries/${await Br([m.namespace,m.codecVersion,m.scopeIds])}`)}async function R(m){return(await S(m)).file(`${await Br(m.key)}.cache`)}async function B(m,D){const v=await m.stat(a);if(v.size<5||v.size>D+Di+4)throw new Error("缓存条目超过大小限制");const k=await m.read(a);if(l(),k.length!==v.size)throw new Error("缓存条目读取不完整");const x=new DataView(k.buffer,k.byteOffset,k.byteLength).getUint32(0);if(x<1||x>Di||x+4>k.length)throw new Error("缓存信封损坏");const L=JSON.parse(Ss.decode(k.subarray(4,x+4))),N=k.slice(x+4);if(L.envelopeVersion!==1||!L.address||!Array.isArray(L.address.scopeIds)||!L.address.scopeIds.every(O=>typeof O=="string")||typeof L.address.namespace!="string"||typeof L.address.codecVersion!="string"||typeof L.address.key!="string"||!Array.isArray(L.revisions)||L.revisions.length!==L.address.scopeIds.length*2||!L.revisions.every(O=>typeof O=="string"&&O.length>0)||!Number.isSafeInteger(L.cachedAt)||!Number.isSafeInteger(L.expiresAt)||L.cachedAt<0||L.expiresAt<=L.cachedAt||L.payloadBytes!==N.length||N.length>D)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:L.address,revisions:L.revisions,cachedAt:L.cachedAt,expiresAt:L.expiresAt,payload:N}}async function U(m){if(!m.remove)throw new Error("Host 不支持缓存文件删除");await m.remove(a)}async function p(m){try{if((await m.file.stat(a)).size!==m.size)return!1;const D=await B(m.file,Kt);return!Re(D.address,m.entry.address)||!Re(D.revisions,m.entry.revisions)||D.cachedAt!==m.entry.cachedAt||D.expiresAt!==m.entry.expiresAt||!Re(await g(D.payload),await g(m.entry.payload))?!1:(await U(m.file),!0)}catch(D){if(Gr(D))return!0;throw D}}async function g(m){const D=await globalThis.crypto.subtle.digest("SHA-256",m);return Array.from(new Uint8Array(D),v=>v.toString(16).padStart(2,"0")).join("")}async function I(){const m=await T(n);let D=0;for(const L of m)if(L.kind==="file"&&(D+=(await L.stat(a)).size,D>Kt))throw new Error("缓存扫描超过字节上限");const v=[];let k=0,x=D;for(const L of await T(i)){if(L.kind!=="directory")throw new Error("缓存目录结构损坏");for(const N of await T(L)){if(N.kind!=="file"||++k>gf)throw new Error("缓存文件超过治理上限");const O=(await N.stat(a)).size;if(x+=O,x>Kt)throw new Error("缓存扫描超过字节上限");try{const C=await B(N,Kt);v.push({file:N,entry:C,size:(await N.stat(a)).size,bucketName:L.name})}catch(C){f(C),l(),Gr(C)||await U(N)}}}return{entries:v,metadataBytes:D}}async function y(){for(const m of await T(i))if(m.kind==="directory"&&m.remove&&(await T(m)).length===0)try{await m.remove({recursive:!1},a)}catch(D){f(D),l()}}function _(m){const{payload:D,...v}=m,k=Xr.encode(JSON.stringify({...v,payloadBytes:D.length}));if(k.length>Di)throw new Error("缓存信封过大");const x=new Uint8Array(4+k.length+D.length);return new DataView(x.buffer).setUint32(0,k.length),x.set(k,4),x.set(D,k.length+4),x}return{readRevisions:(m,D)=>h(()=>b(m,D)),read:(m,D)=>h(async()=>{l();const v=await R(m);let k;try{k=await B(v,D)}catch(x){if(l(),Gr(x))return;throw x}if(!(!Re(k.address,m)||k.expiresAt<=Date.now())&&Re(k.revisions,await b(m.scopeIds,m.namespace)))return k}),publish:(m,D)=>h(async()=>{l();const{address:v}=m;if(!Re(m.revisions,await b(v.scopeIds,v.namespace)))return!1;const k=_(m);if(m.payload.length>D.maxEntryBytes||k.length>D.diskMaxBytes||D.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await w();const x=await S(v),L=await R(v),N=await I(),O=[],C=new Map;for(const H of N.entries){if(H.bucketName===x.name&&H.file.name===L.name)continue;const F=JSON.stringify([H.entry.address.scopeIds,H.entry.address.namespace]);let Q=C.get(F);if(Q||(Q=await b(H.entry.address.scopeIds,H.entry.address.namespace),C.set(F,Q)),H.entry.expiresAt<=Date.now()||!Re(H.entry.revisions,Q)){if(!await p(H))throw new Error("缓存治理期间条目已变化")}else O.push(H)}O.sort((H,F)=>H.entry.cachedAt-F.entry.cachedAt);function P(){const H=O.filter(F=>F.bucketName===x.name);return O.length+1>pf||k.length+N.metadataBytes+O.reduce((F,Q)=>F+Q.size,0)>Kt||H.length+1>Math.min(D.diskMaxEntries,Mt-1)||k.length+H.reduce((F,Q)=>F+Q.size,0)>D.diskMaxBytes}for(;P();){const H=O.filter(J=>J.bucketName===x.name),Q=H.length+1>Math.min(D.diskMaxEntries,Mt-1)||k.length+H.reduce((J,$)=>J+$.size,0)>D.diskMaxBytes?H[0]:O[0];if(!Q||!await p(Q))throw new Error("缓存容量不足或条目已变化");O.splice(O.indexOf(Q),1)}await y();const z=await T(i);if(!z.some(H=>H.name===x.name)&&z.length>=Mt-1)throw new Error("缓存目录超过治理上限");if(await x.create({recursive:!0,exclusive:!1},a),!Re(m.revisions,await b(v.scopeIds,v.namespace)))return!1;try{await L.create({recursive:!1,exclusive:!0},a)}catch(H){f(H),await L.stat(a)}return await L.write(k,a),l(),Re(m.revisions,await b(v.scopeIds,v.namespace))}),invalidate:(m,D)=>h(async()=>{await w();const v=n.file(`${await Br([m,D??null])}.revision`);await M(v);try{await v.create({recursive:!1,exclusive:!0},a)}catch(k){f(k),await v.stat(a)}await v.write(Xr.encode(Ts()),a),l();try{const{entries:k}=await I();for(const x of k){if(D!==void 0&&x.entry.address.namespace!==D||!m.every((N,O)=>x.entry.address.scopeIds[O]===N))continue;const L=await b(x.entry.address.scopeIds,x.entry.address.namespace);Re(x.entry.revisions,L)||await p(x)}await y()}catch(k){f(k),l()}})}}function Gr(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const wf="RATE_LIMITED_BY_RUNTIME",If="RATE_LIMITED",Zc=20,Xc=40,ed=150,td=20,rd=1e4,nd=45e3,id=1,Af=300*1e3,Mf=64;function Nt(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Nf(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Df(e={}){const t=e.now??Date.now,r=Nf(e.coalesceWindowMs,ed),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,Nt(e.budget?.ratePerSecond,Zc)),burst:Math.max(1,Math.floor(Nt(e.budget?.burst,Xc)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(Nt(e.loopDetection?.maxCalls,td))),windowMs:Math.max(1,Math.floor(Nt(e.loopDetection?.windowMs,rd)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(Nt(e.circuitBreaker?.failureThreshold,id))),openMs:Math.max(1,Math.floor(Nt(e.circuitBreaker?.openMs,nd)))},s=new Map,a=new Map,c=new Set,d=new Map,u=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},f={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let l=!1;function h(p){try{e.onReport?.(p)}catch{}}function w(p,g){if(!i)return{exceeded:!1,count:0};const I=a.get(p)??[],y=g-i.windowMs;let _=0;for(;_<I.length&&I[_]<=y;)_+=1;_>0&&I.splice(0,_);const m=I.length>=i.maxCalls;return m||(I.push(g),I.length>i.maxCalls+1&&I.splice(0,I.length-(i.maxCalls+1))),a.set(p,I),{exceeded:m,count:I.length}}function A(p){if(!n)return!0;const g=Math.max(0,p-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+g*n.ratePerSecond),u.updatedAt=p,u.tokens<1?!1:(u.tokens-=1,!0)}function T(p){if(!n)return 0;const g=Math.max(0,p-u.updatedAt)/1e3,I=Math.min(n.burst,u.tokens+g*n.ratePerSecond);return Math.max(0,Math.ceil((1-I)/n.ratePerSecond*1e3))}function M(p,g,I,y,_){if(!o)return;const m=d.get(g),D=(m?.open?0:m?.failures??0)+1;if(D<o.failureThreshold){d.set(g,{open:!1,openedAt:0,openMs:0,failures:D});return}const v=Math.min(Math.max(o.openMs,y),Af);d.set(g,{open:!0,openedAt:_,openMs:v,failures:D}),f.circuitOpened+=1,h({type:"circuit_opened",capability:p,endpointId:g,status:I,openMs:v,timestamp:_})}function b(p){const g=d.get(p);g&&!g.open&&d.delete(p)}function S(p){for(const[g,I]of s)!I.pending&&I.expiresAt<=p&&s.delete(g);for(;s.size>=Mf;){const g=[...s].find(([,I])=>!I.pending);if(!g)break;s.delete(g[0])}}function R(p,g){if(p===void 0)return;const I=s.get(p);I?.promise===g&&(I.pending=!1)}function B(p,g){if(p===void 0)return;s.get(p)?.promise===g&&s.delete(p)}async function U(p){if(l)return p.load();const g=t();if(o){const m=d.get(p.endpointId);if(m?.open){const D=m.openedAt+m.openMs-g;if(D>0)throw f.circuitRejected+=1,h({type:"circuit_rejected",capability:p.capability,endpointId:p.endpointId,retryAfterMs:D,timestamp:g}),_f("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:p.endpointId,retryAfterMs:D});d.delete(p.endpointId)}}const I=w(p.endpointId,g);I.exceeded&&i?c.has(p.endpointId)||(c.add(p.endpointId),h({type:"loop_detected",capability:p.capability,endpointId:p.endpointId,count:I.count,windowMs:i.windowMs,timestamp:g})):c.delete(p.endpointId);const y=r>0?p.coalesceKey:void 0;if(y!==void 0){const m=s.get(y);if(m&&(m.pending||m.expiresAt>g))return f.coalesced+=1,h({type:"coalesced",capability:p.capability,endpointId:p.endpointId,timestamp:g}),m.promise;m&&s.delete(y)}if(I.exceeded&&i)throw f.loopRejected+=1,bs("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:p.capability,endpointId:p.endpointId,count:I.count,windowMs:i.windowMs});if(!A(g)){f.budgetRejected+=1;const m=T(g);throw h({type:"budget_exhausted",capability:p.capability,endpointId:p.endpointId,retryAfterMs:m,timestamp:g}),bs("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:p.capability,endpointId:p.endpointId,retryAfterMs:m})}y!==void 0&&S(g);const _=p.load().then(m=>(R(y,_),b(p.endpointId),m),m=>{B(y,_);const D=Sf(m);throw D!==void 0&&M(p.capability,p.endpointId,D,Tf(m),g),m});return y!==void 0&&s.set(y,{endpointId:p.endpointId,promise:_,expiresAt:g+r,pending:!0}),_}return{execute:U,invalidateCoalescing(p){if(p===void 0){s.clear();return}for(const[g,I]of s)p.includes(I.endpointId)&&s.delete(g)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,p])=>p.open).map(([p])=>p)}},dispose(){l||(l=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function Sf(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 Tf(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 bs(e,t){return{code:wf,message:e,data:t}}function _f(e,t){return{code:If,message:e,data:t}}const od=3e4,sd=6e4,go=1440*60*1e3;function bf(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??od)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??sd)):0,steamGameListTtlMs:t?Of(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:Zc,burst:Xc},coalesceWindowMs:r?.coalesceWindowMs??ed,loopDetection:r?.loopDetection??{maxCalls:td,windowMs:rd},circuitBreaker:r?.circuitBreaker??{failureThreshold:id,openMs:nd}}}}function Of(e){return e===void 0||!Number.isFinite(e)?go:Math.max(0,Math.floor(e))}function E(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function G(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vf(e){return typeof e=="object"&&e!==null}function le(e,t){const r=e.data;if(!vf(r)||typeof r.status!="string")throw new Error(t);return r}const ad={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Lf={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 le(e,"工坊小程序详情加载失败")}};function Pr(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Cf(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Rf(e){const t=le(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=Cf(r.consent_challenge)),{...t,result:n}}const Pf={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=>({...Pr(e.runtimeContext),challenge:e.challenge}),parse:e=>le(e,"小程序授权取消接口响应异常")},kf={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=>Pr(e.runtimeContext),parse:e=>le(e,"小程序授权撤销接口响应异常")},xf={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=>Pr(e.runtimeContext),parse(e){const t=le(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}:{}}}}},jf={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=>({...Pr(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Rf(e)},Uf={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=>({...Pr(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=le(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},zf=64;function cd(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??zf)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(f){for(const[l,h]of i)h.expiresAt<=f&&i.delete(l)}function d(f,l,h){if(a||t<=0||h!==s)return;const w=n();for(c(w),i.delete(f);i.size>=r;){const A=i.keys().next();if(A.done)break;i.delete(A.value)}i.set(f,{expiresAt:w+t,value:l})}function u(f,l){if(a)return l();if(t>0){const T=i.get(f);if(T&&T.expiresAt>n())return Promise.resolve(T.value);T&&i.delete(f)}const h=o.get(f);if(h)return h;const w=s,A=l().then(T=>(d(f,T,w),T)).finally(()=>{o.get(f)===A&&o.delete(f)});return o.set(f,A),A}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 Hf(e,t){return t?e?"server":"local":"legacy"}function Ff(e,t){if(e==="local")throw E("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const Vf=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],Bf=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Gf=/authorization|cookie|pkey|password|secret|token/i,dd=/authorization|cookie|pkey|token|password|secret/i;function Pe(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Qf(e){for(const t of Object.keys(e))if(!Bf.has(t))throw new ue(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of Vf)if(Object.prototype.hasOwnProperty.call(e,t)&&Pe(e,t)!==void 0)throw new ue(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Pe(e,"bodyEncoding")!==void 0&&Pe(e,"bodyEncoding")!=="json"&&Pe(e,"bodyEncoding")!=="form")throw new ue("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Pe(e,"failurePresentation")!==void 0&&Pe(e,"failurePresentation")!=="none")throw new ue("endpoint failurePresentation 必须为 none");if(Pe(e,"auth")!==void 0&&Pe(e,"auth")!=="none"&&Pe(e,"auth")!=="optional"&&Pe(e,"auth")!=="required")throw new ue("endpoint auth 必须为 none、optional 或 required")}function cr(e){if(Array.isArray(e))return e.map(cr);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Gf.test(n)||(r[n]=cr(i));return r}function Os(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))dd.test(r)||(t[r]=n);return t}function Yf(e){if(!e)return;const t=Object.keys(e).find(r=>dd.test(r));if(t)throw new ue(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Ht 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,t.retryAfterMs!==void 0&&(this.retryAfterMs=t.retryAfterMs),Object.setPrototypeOf(this,new.target.prototype)}}const vs=1440*60*1e3,qf=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function $f(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,vs):void 0}if(!qf.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,vs):void 0}function Wf(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 Ft 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 kr 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 Kf(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:cr(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Os(o),method:e.method,metadata:{endpointId:e.id},query:cr(n),timeout:e.timeout,url:r},data:cr(a.data),headers:Os(a.headers)||{},status:a.status,statusText:a.statusText}}async function mi(e,t,r,n){if(!n||!n.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(n.credentials!=="heybox-session"&&n.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(Qf(t),typeof t.id!="string"||!t.id)throw new ue("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new ue("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new ue("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;Yf(a);const c=async()=>{let f;try{f=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...o===void 0?{}:{params:o},...s===void 0?{}:{data:s},...a===void 0?{}:{headers:a},credentials:n.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:n.signal,...n.miniProgramDetail===void 0?{}:{miniProgramDetail:n.miniProgramDetail}})}catch(h){throw h instanceof ue?h:new Ft({endpointId:t.id,cause:h})}if(f.status<200||f.status>=300)throw new Ht({endpointId:t.id,status:f.status,retryAfterMs:$f(f.headers)});const l=Kf(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(l,r)}catch(h){throw new kr({endpointId:t.id,cause:h})}return l.data},d=n.gate;if(!d)return c();const u=Wf(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const Jf=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),Zf=new Set(zt),qo="steam_account",ld=new Set(zt.filter(e=>e!==qo)),Xf=1e3;function eh(e){const t=new Set,r=cd({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??od))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??Hf(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 E("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let N;try{N=await e.authorizationContext.get(e.operationContext)}catch(C){throw yo(C)?Si(C.code,C.message,C):Si("REQUEST_FAILED","读取 Runtime auth context 失败",C)}if(N.steamAccount!==c||N.userDataMode!==d)throw E("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const O=N.token.trim();if(!O)throw E("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:O}}const h=e.account.onChange(N=>{if(w(),A("heybox_app_login_change",N?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),N&&e.account.getAccountKey){const O=i;B().then(C=>{!o&&i===O&&A("heybox_app_login_change",C)}).catch(()=>{})}});function w(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function A(N,O){N==="user_info_authorization_change"&&sh(O)&&r.invalidate();for(const C of t)try{C(N,O)}catch{}}function T(){const N=e.identity.get()?.miniProgramId?.trim();if(!N)throw E("INVALID_STATE","当前能力缺少 canonical 小程序身份");return N}function M(){if(o||e.operationContext.signal.aborted)throw E("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function b(){M();let N;try{N=await e.account.getCurrentUserId(e.operationContext)}catch(O){throw Ps(O,e.operationContext.signal,"读取小黑盒账号失败")}return typeof N=="string"&&N.trim()?N.trim():void 0}async function S(N,O){const C=await b();if(i!==O||C!==N)throw E("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function R(N,O,C=T()){if(!e.account.getAccountKey)throw E("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let P;try{P=await e.account.getAccountKey(C,N,e.operationContext)}catch{throw M(),E("REQUEST_FAILED","读取本地账号标识失败")}if(await S(N,O),T()!==C)throw E("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof P!="string"||!P.trim())throw E("INVALID_RESPONSE","Host 返回了无效的账号标识");return P}async function B(){const N=T(),O=i,C=await b();if(M(),i!==O)throw E("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return C?{isHeyboxAppLoggedIn:!0,accountKey:await R(C,O,N)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function U(N){M();try{await e.account.ensureAuthenticated({trustedUserGesture:N,reason:"runtime_auth",signal:e.operationContext.signal})}catch(C){throw Ps(C,e.operationContext.signal,"小黑盒登录失败")}const O=await b();if(!O)throw E("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return O}async function p(N,O,C=e.operationContext.signal){try{if(C.aborted)throw po();return await oh(mi(e.network,N,O,{...e.operationContext,credentials:"heybox-session",signal:C,...f?{gate:f}:{}}),C)}catch(P){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):P instanceof ue?E("REQUEST_UNSUPPORTED",P.message):P instanceof kr?E("INVALID_RESPONSE","授权接口响应不合法"):P instanceof Ft?E("REQUEST_FAILED","授权请求失败"):P instanceof Ht?u&&(P.status===403||P.status===429)?E("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:P.status,...P.retryAfterMs===void 0?{}:{retryAfterMs:P.retryAfterMs}}):E("REQUEST_FAILED",P.message):yo(P)?P:E("REQUEST_FAILED","授权请求失败")}}async function g(N,O){await p(Pf,{runtimeContext:{miniProgramId:N,...await l()},challenge:O}).catch(()=>{})}function I(N){const O=async()=>{const P=Cs(e.operationContext.signal);a=P;try{return await N(P.signal)}finally{a===P&&(a=void 0),P.abort()}},C=s.then(O,O);return s=C.then(()=>{},()=>{}),C}async function y(N,O,C,P,z){if(!C)throw await g(N,O.challenge),E("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await g(N,O.challenge),E("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return I(async H=>{await S(P,z);const F=await _(N,O.displayedScopes,H);await S(P,z);let Q;try{Q=await e.authPresentation.confirmAuthorization({miniProgramId:N,scopes:O.displayedScopes,...F,signal:H})}catch($){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await S(P,z),await g(N,O.challenge),Si("REQUEST_FAILED","授权确认界面执行失败",$))}if(await S(P,z),Q.status!=="granted")throw await g(N,O.challenge),E("AUTHORIZATION_CANCELLED","用户取消授权");const J=nh(Q.grantedScopes,O.displayedScopes,c);if(!J.includes("identity"))throw await g(N,O.challenge),E("AUTHORIZATION_CANCELLED","用户拒绝授权");return J})}async function _(N,O,C){const P=Cs(C),z=setTimeout(()=>P.abort(),Xf);try{const H=ih(e.miniProgramPresentation),[F,Q]=await Promise.all([H?Promise.resolve(H):m(N,P.signal),O.includes("profile")?D(P.signal):Promise.resolve(void 0)]);return{...F?{miniProgram:F}:{},...Q?{userProfile:Q}:{}}}finally{clearTimeout(z),P.abort()}}async function m(N,O){try{const C=e.identity.get()?.version?.trim(),P=await p(Lf,{mini_program_id:N,...C?{miniprogram_version:C}:{}},O),z=Dt(P,"小程序公开资料"),H=Lt(z.name),F=Lt(z.icon_url);return H||F?{...H?{name:H}:{},...F?{avatarUrl:F}:{}}:void 0}catch{return}}async function D(N){try{const O=await p(ad,void 0,N),C=Dt(O,"账号基础信息"),P=Lt(C.display_username),z=Lt(C.display_avatar);return P||z?{...P?{nickname:P}:{},...z?{avatar:z}:{}}:void 0}catch{return}}async function v(N,O){if(Ff(d,"auth.login"),!c&&N.includes(qo))throw E("INVALID_PARAMS","auth.login 参数不合法");const C=T(),P=await U(O),z=i,H=await p(jf,{runtimeContext:{miniProgramId:C,...await l()},scopes:N});await S(P,z);const F=Dt(H,"小程序登录"),Q=Rs(F,"loginCode"),J=Rs(F,"consentChallenge");if(Q===J)throw E("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let $;if(Q)$=Ls(F.loginCode,c);else{const q=th(F.consentChallenge,c),ce=await y(C,q,O,P,z);await S(P,z);const wt=await p(Uf,{runtimeContext:{miniProgramId:C,...await l()},challenge:q.challenge,selectedScopes:ce});if(await S(P,z),$=Ls(Dt(wt,"小程序登录确认"),c),$.scopes.some(ye=>!ce.includes(ye)))throw E("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const q of $.scopes)n.add(q);r.invalidate();const X=e.account.getAccountKey?await R(P,z,C):void 0;return A("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...X===void 0?{}:{accountKey:X}}),A("user_info_authorization_change",Ti(n,c)),{...$,...X===void 0?{}:{accountKey:X}}}async function k(N,O){const C=i,P=await p(xf,{runtimeContext:{miniProgramId:O,...await l()}});await S(N,C);const z=rh(Dt(P,"用户本地身份"),c);for(const H of c?zt:ld)n.add(H);return A("user_info_authorization_change",Ti(n,c)),z}function x(N){M();const O=T(),C=`${N}\0${O}\0${i}\0${c}`;return r.read(C,()=>k(N,O))}async function L(N){if(!N)throw E("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const O=T(),C=i,P=await b();if(!P)throw E("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const z=await p(kf,{runtimeContext:{miniProgramId:O,...await l()}});await S(P,C),Dt(z,"用户授权撤销"),w(),A("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:B,login:v,async confirmGameSaves(N){if(!N)throw E("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw E("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const O=T(),C=await U(N),P=i;await I(async z=>{await S(C,P);const H=await _(O,["identity"],z),F=await e.authPresentation.confirmAuthorization({miniProgramId:O,scopes:["identity","game_saves"],...H,signal:z});if(await S(C,P),F.status!=="granted"||!F.grantedScopes.includes("game_saves")||!F.grantedScopes.includes("identity"))throw E("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:x,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Ti(n,c),revoke:L,onEvent(N){return t.add(N),()=>t.delete(N)},dispose(){o||(o=!0,w(),r.dispose(),h(),t.clear())}}}function Si(e,t,r){const n=E(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function Dt(e,t){if(!G(e))throw E("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":Jf.has(r)?r:"REQUEST_FAILED";throw E(n,r)}if(!G(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Ls(e,t){if(!G(e))throw E("INVALID_RESPONSE","login code 必须是对象");const r=Yn(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 E("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function th(e,t){if(!G(e))throw E("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Yn(e.requestedScopes,"challenge requestedScopes",t),n=Yn(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 E("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function rh(e,t){if(!G(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw E("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw E("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 nh(e,t,r){const n=Yn(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw E("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Lt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function ih(e){const t=Lt(e?.name),r=Lt(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Cs(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 oh(e,t){return t.aborted?Promise.reject(po()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(po()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function po(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Yn(e,t,r){const n=r?Zf:ld;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw E("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Ti(e,t){const r=t?zt:zt.filter(n=>n!==qo);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function Rs(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function sh(e){return G(e)?Object.values(e).some(t=>t==="denied"):!1}function yo(e){return G(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Ps(e,t,r){return t.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):yo(e)?e:E("REQUEST_FAILED",r)}const ah=new Set(zt);function ch(e){return{[gn]:async t=>{if(t!==void 0)throw E("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[pn]:async(t,r)=>e.authorization.login(dh(t),r.trustedUserGesture)}}function dh(e){if(e===void 0)return["identity"];if(!G(e)||Object.keys(e).some(t=>t!=="scopes"))throw ks();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!ah.has(t))||new Set(e.scopes).size!==e.scopes.length)throw ks();return[...e.scopes]}function ks(){return E("INVALID_PARAMS","auth.login 参数不合法")}const uh={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 le(e,"排行榜记录删除接口响应异常")}},lh={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 le(e,"当前排行榜记录接口响应异常")}},fh={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 le(e,"排行榜信息接口响应异常")}},hh={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 le(e,"排行榜列表接口响应异常")}},mh={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 le(e,"排行榜提交接口响应异常")}};function en(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function W(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:en()}function xs(e){return e instanceof ue?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function K(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(en());let n;try{n=e()}catch(i){return Promise.reject(xs(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(en())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(en()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(xs(d))))})}const gh={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 $o(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await K(()=>mi(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if($n(i)||ir(i,"REQUEST_UNSUPPORTED")||ir(i,"RATE_LIMITED")||ir(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof ue)throw V("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof Ft&&ir(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Ht){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw V("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw V("UNAUTHORIZED","当前用户未登录")}throw i instanceof Ft||i instanceof Ht?qn(e.subject):i instanceof kr?te(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):te(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function ze(e,t,r){if(!ne(e)||typeof e.status!="string")throw te(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw ph(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw te(`${t} 响应缺少 result`);return e.result}function Wo(e,t){try{return e.onChange(t)}catch(r){if(ir(r,qc))return()=>{};throw r}}function ph(e,t){if(e.status==="login"||e.status==="relogin")throw V("UNAUTHORIZED",nr(e.msg)||"当前用户未登录");const r=js(e.result)??js(e),n=nr(r?.user_message)||nr(e.msg)||nr(r?.developer_message)||`${t}请求失败`;throw r?V(yh(r),n,{status:e.status,sbe:r}):V("HEYBOX_API_ERROR",n,{status:e.status})}function js(e){return ne(e)&&ne(e.sbe)?e.sbe:void 0}function yh(e){const t=nr(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 gh[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 ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nr(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function ir(e,t){return ne(e)&&e.code===t}function V(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function te(e){return V("INVALID_RESPONSE",e)}function qn(e){return V("REQUEST_FAILED",`${e}请求失败`)}function $n(e){return e instanceof Error&&e.name==="AbortError"}const Eh="default",nt="排行榜",wh=/^[A-Za-z0-9_-]{1,64}$/,Ih=300*1e3,Ah=250,Mh=3;class Nh{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Wo(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(mh,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=ze(i,Be,nt);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),_i(o,Be)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Zt("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(hh,{miniProgramId:r,...t}),s=ze(o,be,nt);if(!ne(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw te(`${be} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw te(`${be} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>_i(a,be)),...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=Zt("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(lh,{miniProgramId:n,...t}),c=ze(a,Je,nt);if(!ne(c))throw te(`${Je} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:_i(c.entry,Je)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(uh,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=ze(i,mt,nt);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!ne(o)||typeof o.deleted!="boolean")throw te(`${mt} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Zt("info"),async()=>{const i=await this.request(fh,{miniProgramId:r,...t}),o=ze(i,Ue,nt);if(!ne(o)||typeof o.key!="string"||!wh.test(o.key))throw te(`${Ue} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw te(`${Ue} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw te(`${Ue} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw te(`${Ue} 返回的 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=Zt(t,n),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,f=o?.generation,l=i().then(h=>(this.assertAccountGeneration(u),o&&s&&o.generation===f&&(r==="list"?s.size>=Ah&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Ih,value:h})),h)).finally(()=>{this.inflight.get(c)?.promise===l&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:l}),l}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=Mh)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)Us(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){Us(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 K(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw $n(n)?n:qn(nt)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw V("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw V("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Zt(t,r??Eh)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw V("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return $o({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:nt,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(W(this.options.operationContext.signal),this.disposed)throw V("INVALID_STATE","Cloud capability 已释放")}}function Dh(e){return new Nh(e)}function _i(e,t){if(!ne(e))throw te(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw te(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw te(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw te(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw te(`${t} 返回的 score 必须是有限数字`);if(!ne(e.extra))throw te(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw te(`${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 Us(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Zt(...e){return JSON.stringify(e)}const Sh={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 le(e,"云端存储删除接口响应异常")}},zs={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 le(e,"云端存储读取接口响应异常")}},Hs={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 le(e,"云端存储 key 列表接口响应异常")}},Th={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 le(e,"云端存储写入接口响应异常")}},it="云端存储",_h=3e4,bh=128,Oh=500;class vh{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Wo(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=ze(await this.request(Hs,{}),gt,it);if(this.assertAccountGeneration(t),!ne(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw te("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"?Oh: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=ze(await this.request(Sh,{key:t}),jt,it);if(this.assertAccountGeneration(r.generation),!ne(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw te("删除结果不合法");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 te("云存储版本超出安全整数范围");const o=ze(await this.request(Th,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),xt,it);if(this.assertAccountGeneration(r.generation),!ne(o)||o.success!==!0)throw te("云存储写入结果不合法");const s=Fs({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw te("写入版本凭证不匹配");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(zs,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=Fs(ze(c,kt,it));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>=bh&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+_h,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([zs.id,Hs.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(V("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(V("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 K(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw $n(o)?o:qn(it)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),V("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),V("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw V("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw V("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw V("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw V("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await K(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw $n(s)?s:qn(it)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw V("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return $o({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:it,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(W(this.options.operationContext.signal),this.disposed)throw V("INVALID_STATE","Cloud capability 已释放")}}function Lh(e){return new vh(e)}function Fs(e){if(!ne(e))throw te("云存储读取结果必须是对象");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 te("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw te("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const Ch=/^[A-Za-z0-9_-]{1,64}$/,Vs=20,Rh=100,Bs=2048,Ph=/^[A-Za-z0-9_-]{1,128}$/,Gs=16*1024;function kh(e){const t=Dh(e),r=Lh(e);return{handlers:{[Be]:async i=>t.submit(xh(i)),[be]:async i=>t.getList(jh(i)),[Je]:async i=>t.getCurrentUserEntry(bi(i,Je)),[mt]:async i=>t.deleteCurrentUserEntry(bi(i,mt)),[Ue]:async i=>t.getInfo(bi(i,Ue)),[kt]:async i=>r.getItem(Qs(i,kt)),[xt]:async i=>{const{key:o,value:s}=Uh(i);return r.setItem(o,s)},[jt]:async i=>r.removeItem(Qs(i,jt)),[gt]:async i=>(Hh(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function xh(e){const t=qt(e,Be,!1);if($t(t,["key","score","extra"],Be),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw pe("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Ko(t.key,Be),score:t.score,...t.extra===void 0?{}:{extra:Fh(t.extra)}}}function jh(e){if(e===void 0)return{limit:Vs};const t=qt(e,be,!0);$t(t,["key","limit","cursor"],be);const r=t.limit===void 0?Vs:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>Rh)throw pe("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw pe("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Ko(t.key,be),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function bi(e,t){if(e===void 0)return{};const r=qt(e,t,!0);return $t(r,["key"],t),Ko(r.key,t)}function Qs(e,t){const r=qt(e,t,!1);return $t(r,["key"],t),fd(r.key,t)}function Uh(e){const t=xt,r=qt(e,t,!1);$t(r,["key","value"],t);const n=fd(r.key,t);if(typeof r.value!="string")throw pe("INVALID_PARAMS",`${t} value 必须是字符串`);if(zh(r.value))throw pe("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>Gs)throw pe("INVALID_PARAMS",`${t} value 不能超过 ${Gs} 字节`);return{key:n,value:r.value}}function zh(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 Hh(e){const t=qt(e,gt,!0);$t(t,[],gt)}function fd(e,t){if(typeof e!="string"||!Ph.test(e))throw pe("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function qt(e,t,r){if(e===void 0&&r)return{};if(!hd(e))throw pe("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function $t(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw pe("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Ko(e,t){if(e===void 0)return{};if(typeof e!="string"||!Ch.test(e))throw pe("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function Fh(e){if(!hd(e))throw pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw pe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>Bs)throw pe("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${Bs} 字节`);return e}function hd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pe(e,t){return{code:e,message:t}}const Vh={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 le(e,"游戏存档接口响应异常")}};function md(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw E("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 E("FILE_IO_FAILED","无法生成安全文件标识")}}function gd(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):Eo,remove:o?s=>e.remove(s):yd,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Eo,stat:s=>e.stat(s)})}function pd(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=>gd(e.file(a),n,{allowRemove:o}),directory:a=>pd(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Eo,remove:s?(a,c)=>e.remove(a,c):yd,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Eo(){return Promise.reject(E("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function yd(){return Promise.reject(E("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Bh=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"]),Gh={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 Sr(e){const t=Jo(e),r=t&&Bh.has(t)?E(t,Gh[t]??"文件操作失败"):E("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Ve(e){try{return e()}catch(t){throw Sr(t)}}function Jo(e){try{if(!G(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Ys=1024;class Zo{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new Zo(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 Qr(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Ve(()=>{if(!Array.isArray(t))throw E("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw E("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>Ys)throw E("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw E("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>Qr(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 $s(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Ut(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!Ut(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Yh(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Tr(r.relativePath);Oi(n.origin,i);const o=this.prepareFile(Ve(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=qh(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==="."?".":Tr(r.relativePath);Oi(n.origin,i);const o=this.prepareDirectory(i==="."?n.hostHandle:Ve(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Ks(t),Qr(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Ve(()=>{if(!Array.isArray(r))throw E("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw E("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw E("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&G(a)&&typeof a.name=="string"&&Ed(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Ve(()=>{if(G(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Qr(n.handle,qs(t.ref,n.handle.name))}if(G(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return $s(n.handle,Qh(t.ref,n.handle.name))}throw E("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=xr(r);Oi(t.origin,n);const i=this.prepareFile(Ve(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:qs(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw E("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Ve(()=>{Ks(t);const i=n??t.mode;return Ws(t.mode,i),{handle:gd(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Ve(()=>{Wh(t,i);const o=n??t.mode;return Ws(t.mode,o),{handle:pd(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Ys)throw E("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=md();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw E("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!$h(t))throw E("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw E("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw E("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Ne("files.sandbox");return this.prepareDirectory(Ve(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw E("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Ne("files")}}function Tr(e){if(!Go(e))throw E("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Oi(e,t){if(e==="sandbox"&&Ed(t))throw E("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function Ed(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function xr(e,t="文件名"){const r=Tr(e);if(r.includes("/"))throw E("INVALID_PARAMS",`${t} 只能是 basename`);return r}function qs(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Tr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Qh(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Tr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Qr(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function $s(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Ws(e,t){if(t==="readwrite"&&e!=="readwrite")throw E("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Yh(e){return Ut(e)||wd(),e}function qh(e){return Uc(e)||wd(),e}function wd(){throw E("INVALID_PARAMS","文件引用不合法")}function $h(e){return/^[0-9a-f]{32}$/.test(e)}function Ks(e){if(!G(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 E("FILE_IO_FAILED","Host 返回了无效 File handle");xr(e.name,"Host File name")}function Wh(e,t=!1){if(!G(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 E("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw E("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&xr(e.name,"Host Directory name")}const Kh=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Jh=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Zh=new Set(["range","if-range","a-im"]),Xh=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"]),em=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Yr={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class tm{constructor(t){this.signal=t}phase="initial";transition(t){if(Yr[t]<=Yr[this.phase])throw E("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Yr[this.phase]<Yr.committed&&this.signal.aborted)throw Md()}normalizeHostError(t,r){return this.throwIfCancelled(),es(t,r,this.signal)}}async function Id(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Ne("network.download");const o=ve(r.operationContext,t.signal),s=new tm(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await om(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=am(c);cm(c,u);const f=dm(c.status,u);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw E("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const l=sm(e,a,u,i);let h=0;const w=nm(f.expectedBytes,e.maxBytes);Li(t,vi(0,f));const A={...o,onProgress(b){!Number.isSafeInteger(b)||b<h||w!==void 0&&b>w||(h=b,Li(t,vi(h,f)))}};s.transition("transfer"),d=!0;let T;try{T=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}},A)}catch(b){throw s.normalizeHostError(b,"transfer")}s.transition("committed"),h=rm(T,f,h,e.maxBytes),Li(t,vi(h,f));const M=i.describeFile(l.handle,l.ref);return s.transition("completed"),M}finally{d||im(n.network,c.body)}}function rm(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 nm(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function im(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function om(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return wo(i.handle.mode),await pm(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return wo(n.handle.mode),await ym(n.handle,r),{kind:"directory",...n}}function sm(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=lm(e,r),o=n.deriveFile(t,i);return wo(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function am(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 E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!G(e.headers))throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!Kh.has(r)||!Array.isArray(n)||n.length===0)throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw E("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function cm(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw E("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:gm(t,Jh)});if((t["content-range"]?.length??0)>0)throw E("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function dm(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw E("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw E("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw E("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=um(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 um(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 Li(e,t){try{e.postProgress(t)}catch{}}function lm(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=fm(i);if(o&&tn(o))return o}for(const i of r){const o=hm(i);if(o&&tn(o))return o}if(e.suggestedName!==void 0)return Xo(e.suggestedName);const n=mm(e.url);return n&&tn(n)?n:"download.bin"}function fm(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 hm(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 mm(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Xo(e){try{xr(e,"suggestedName")}catch{throw E("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!tn(e))throw E("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function tn(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||em.test(e))}function gm(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function pm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Ad()}catch(r){throw es(r,"file",t.signal)}}async function ym(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Ad()}catch(r){throw es(r,"file",t.signal)}}function wo(e){if(e!=="readwrite")throw E("FILE_ACCESS_DENIED","下载目标只允许读取")}const Em={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 es(e,t,r){if(r.aborted)return Md();const n=wm(e);if(n&&Xh.has(n)){const o=E(n,Em[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?E("DOWNLOAD_TIMEOUT","下载网络请求超时"):E("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?E("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):E("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function wm(e){return G(e)&&typeof e.code=="string"?e.code:void 0}function Ad(){return E("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Md(){return E("DOWNLOAD_CANCELLED","下载已取消")}function Im(e){if(!e)return;const t=Object.keys(e).find(r=>Zh.has(r.trim().toLowerCase()));if(t)throw E("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}function Io(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=>Io(r,t+1)):ne(e)&&Object.values(e).every(r=>Io(r,t+1))}function Am(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(!ne(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 V(String(e.error_code),"账号或授权已变化");return n}return e.status!=="ready"||!ne(e.data)||!Io(e.data)?n:{status:"ready",data:e.data}}function Mm(e){const t=new Map,r=new Map,n=a=>`hb_runtime_game_save_sync_v1_${[a.miniProgramId,a.userId,a.gameId].map(encodeURIComponent).join(":")}`;async function i(a,c,d){const u=n(a),f=r.get(u)??Promise.resolve();let l;const h=new Promise(A=>{l=A}),w=f.then(()=>h);r.set(u,w);try{return await K(()=>f,c.signal),W(c.signal),await d()}finally{l(),r.get(u)===w&&w.then(()=>{r.get(u)===w&&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 K(()=>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{W(c.signal);return}}async function s(a,c,d){W(d.signal);const u=n(a),f=c?{...a,version:1,taskId:c}:void 0;if(t.set(u,f),!!e)try{await K(()=>e.setRaw(u,f?JSON.stringify(f):"",d),d.signal)}catch{W(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 Ci=8*1024*1024,Js=32*1024*1024,Nm=2e3,Dm=5*6e4;function Sm(e){const t=Mm(e.storage);let r=0,n=!1,i,o=0;const s=new Set,a={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},c=p=>p.remove(a),d=new Set;let u=new AbortController,f;const l=()=>{u.abort(),u=new AbortController,f=void 0},h=(p=!0)=>{p&&t.clear(a),r++,l();for(const g of d)g.abort();for(const g of s)c(g).catch(()=>{});s.clear(),o=0},w=Wo(e.account,p=>{i&&p!==i&&(h(),i=void 0)}),A=e.authorization.onEvent(()=>h());function T(p,g,I,y){if(M(I),y.signal.aborted||!p.account_id||!e.presentation?.showSteamLoginRequired)return;const _=`${p.account_id}:${p.game_id}:${p.task_id??"sync"}`;if(f!==_){f=_;try{e.presentation.showSteamLoginRequired({userId:g,accountId:p.account_id},ve(e.operationContext,u.signal))}catch{}}}function M(p){if(n||e.operationContext.signal.aborted)throw V("RUNTIME_DESTROYED","小程序已关闭");if(p!==r)throw V("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function b(p,g,I){if(M(g),await e.account.getCurrentUserId(I)!==p)throw h(),V("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");M(g)}async function S(p,g,I,y){if(await b(g,I,y),!e.authorizationContext)throw V("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const _=await e.authorizationContext.get(y);if(!_.token||_.expiresAt<=Date.now())throw V("UNAUTHORIZED","小程序运行上下文已过期");const m=await $o({network:e.network,operationContext:y,subject:"游戏存档",assertUsable:()=>M(I),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},Vh,{...p,runtime_auth_context_token:_.token});if(await b(g,I,y),m.status==="failed"&&ne(m.result)&&m.result.error_code==="RECENT_SAVE_AVAILABLE")throw V("RECENT_SAVE_AVAILABLE",typeof m.msg=="string"&&m.msg?m.msg:"已有近期存档,请直接查询使用");const D=ze(m,p.action,"游戏存档");if(!ne(D))throw V("INVALID_RESPONSE","存档响应不合法");return D}async function R(p,g,I){const y=Tm(p,g),_=r;if(M(_),p==="file"&&(!e.transfer||!e.files))throw V("METHOD_FORBIDDEN","宿主不支持存档文件读取");const m=new AbortController;d.add(m);let D=!1;const v=p==="sync"?setTimeout(()=>{D=!0,m.abort()},Dm):void 0,k=ve(ve(e.operationContext,I.signal),m.signal);try{const x=await e.account.getCurrentUserId(k);if(!x)throw V("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==x)throw h(),V("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=x,p==="sync"||p==="parsed"){if(p==="sync"&&l(),!y.account_id){const Q=await S({action:"check",game_id:y.game_id},x,_,k);y.account_id=_r(Q.account_id)}if(p==="sync")return await B(y,x,_,k)}const L=await S({action:p,...y},x,_,k);if(p==="list")return _m(L);if(p==="parsed")return Am(L.parsed_data,y.game_id);const N=Nd(L.file);if(N.fileId!==y.file_id)throw V("INVALID_RESPONSE","文件标识不匹配");if(N.sizeBytes>Ci)throw V("FILE_TOO_LARGE","首期存档文件上限为 8 MiB");if(o+N.sizeBytes>Js)throw V("FILE_QUOTA_EXCEEDED","当前会话存档文件已达 32 MiB");const O={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:st(L.download_url)},timeout:6e4};if(!xl(O)||new URL(st(L.download_url)).pathname!=="/cloud_archive/"+y.file_id+".zip"||Wn(L.expires_at)<=Date.now())throw V("INVALID_RESPONSE","存档下载地址无效");const C=".hb-game-saves/"+md()+".zip",P=e.files.sandbox.file(C);if(!P.remove)throw V("METHOD_FORBIDDEN","宿主不支持存档临时文件清理");await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},k);const z=e.fileRegistry.createTransferScope();let H=!1,F=!1;try{await P.create({recursive:!0,exclusive:!0},k),F=!0;const Q=z.registerFile(P,"game-save","readwrite");await Id({request:O,url:new URL(st(L.download_url)),to:Q.ref,targetKind:"file",maxBytes:Ci},{...I,signal:k.signal,postProgress:()=>{}},{transfer:e.transfer,fileRegistry:z,operationContext:k}),await b(x,_,k);const J=await P.stat(k);if(J.size===void 0||!Number.isSafeInteger(J.size)||J.size<0||J.size>Ci)throw V("FILE_TOO_LARGE","存档文件超过 8 MiB");if(await b(x,_,k),o+J.size>Js)throw V("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达 32 MiB");if(k.signal.aborted)throw V("DOWNLOAD_CANCELLED","存档下载已取消");const $=J.size,X=async ye=>{try{M(_),await S({action:"check",game_id:y.game_id,account_id:y.account_id},x,_,ye)}catch(Ae){throw ne(Ae)&&["GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","UNAUTHORIZED"].includes(String(Ae.code))?(h(),V("FILE_ACCESS_REVOKED","游戏存档授权已失效")):Ae}},q=async()=>{throw V("FILE_ACCESS_DENIED","存档文件只读")},ce={kind:"file",mode:"read",name:N.name,create:q,write:q,async read(ye){await X(ye);const Ae=await P.read(ye);try{if(await b(x,_,ye),!(Ae instanceof Uint8Array)||Ae.byteLength!==$)throw V("INVALID_RESPONSE","存档文件长度不匹配");return Ae}catch(ku){throw Ae instanceof Uint8Array&&Ae.fill(0),ku}},async stat(ye){return await X(ye),{kind:"file",size:$,modifiedAt:N.modifiedAt}}},wt=e.fileRegistry.registerFile(ce,"game-save","read");return s.add(P),o+=$,H=!0,wt}finally{z.dispose(),F&&!H&&await c(P)}}catch(x){throw D?V("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):x}finally{v!==void 0&&clearTimeout(v),d.delete(m)}}async function B(p,g,I,y){const _=e.identity.get()?.miniProgramId;if(!_)throw V("INVALID_STATE","小程序身份尚未确认");const m={miniProgramId:_,userId:g,gameId:p.game_id,accountId:p.account_id},D=k=>S({action:"status",...p,task_id:k},g,I,y);let v;try{const k=await t.run(m,y,async()=>{await b(g,I,y);const L=await t.get(m,y);if(L){v=L;try{return{taskId:L,status:await D(L)}}catch(O){if(!ne(O)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(O.code)))throw O;await t.set(m,void 0,y),v=void 0}}const N=await S({action:"sync",...p},g,I,y);return v=_r(N.task_id),await t.set(m,v,y),await b(g,I,y),{taskId:v,status:void 0}});v=k.taskId;let x=k.status;for(;;){if(M(I),y.signal.aborted)throw V("REQUEST_CANCELLED","已停止等待存档同步");if(x??=await D(v),x.state==="succeeded"||x.state==="failed"){if(await t.remove(m,v,y),await b(g,I,y),x.state==="succeeded")return{state:"succeeded"};throw V(x.error_code?st(x.error_code):"SYNC_FAILED",x.message?st(x.message):"存档同步失败")}if(x.state!=="syncing"&&x.state!=="uploading")throw V("INVALID_RESPONSE","同步状态不合法");x=void 0,await bm(Nm,y.signal)}}catch(k){if(ne(k)){const x=String(k.code);x==="STEAM_LOGIN_REQUIRED"&&T({...p,task_id:v},g,I,y),v&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(x)&&await t.remove(m,v,a)}throw k}}return{handlers:{"gameSaves.list":(p,g)=>R("list",p,g),"gameSaves.sync":(p,g)=>R("sync",p,g),"gameSaves.readParsedData":(p,g)=>R("parsed",p,g),"gameSaves.getFile":(p,g)=>R("file",p,g)},allowsRead(p,g){return["file.readBytes","file.readText","file.stat","file.exists"].includes(p)&&ne(g)&&e.fileRegistry.isGameSaveRef(g.target)},dispose(){n||(n=!0,h(!1),w(),A())}}}function Tm(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!ne(t)||Object.keys(t).some(i=>!r.includes(i)))throw V("INVALID_PARAMS","存档参数不合法");const n=or(t.gameId);if(Number(n)>2147483647)throw V("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:or(t.accountId)}:{},...e==="file"?{save_id:or(t.saveId),file_id:or(t.fileId)}:{}}}function or(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw V("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function _r(e){try{return or(e)}catch{throw V("INVALID_RESPONSE","服务端存档标识无效")}}function st(e){if(typeof e!="string")throw V("INVALID_RESPONSE","服务端存档字段无效");return e}function Wn(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw V("INVALID_RESPONSE","服务端存档数值无效");return e}function Nd(e){if(!ne(e))throw V("INVALID_RESPONSE","存档文件信息无效");return{fileId:_r(e.file_id),name:st(e.name),originalPath:st(e.original_path),sizeBytes:Wn(e.size_bytes),modifiedAt:Wn(e.modified_at)}}function _m(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw V("INVALID_RESPONSE","存档列表无效");return{accountId:_r(e.account_id),saves:e.saves.map(t=>{if(!ne(t)||!Array.isArray(t.files)||t.files.length>200)throw V("INVALID_RESPONSE","存档文件列表无效");return{saveId:_r(t.save_id),createdAt:Wn(t.created_at),files:t.files.map(Nd)}})}}function bm(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(o),t.removeEventListener("abort",i),n(V("REQUEST_CANCELLED","已停止等待存档同步"))},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}const Om=new Set(["stdio","attachments","notifications"]),Dd=new Set(["windows-x64","macos-arm64"]),vm=new Set(["unsigned","valid","invalid","unknown"]),Lm=/^[a-f0-9]{64}$/,Cm=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Rm=new Set(Qc),Pm=new Set([...Qc,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Sd=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 km(e){const t=async(n,i,o,s)=>{const a=xm(n);try{je(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return je(i.signal),c}catch(c){throw Mo(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw E("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw E("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>jm(d,i)).catch(d=>{throw Mo(d)});je(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(je(o.signal),c.status!=="granted")throw E("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[ri]:(n,i)=>t(n,i,async(o,s)=>Ao(await e.companion.getInfo(o,s),o)),[ni]:(n,i)=>t(n,i,async(o,s)=>Zs(await e.companion.getPreparationStatus(o,s))),[ii]:(n,i)=>t(n,i,async(o,s)=>{const a=Zs(await e.companion.getPreparationStatus(o,s));return je(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),je(i.signal),Ao(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(_d(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[oi]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[si]:(n,i)=>t(n,i,async(o,s)=>Xs(await e.companion.getActiveSession(o,s),o)),[ai]:(n,i)=>t(n,i,async(o,s)=>{const a=Xs(await e.companion.getActiveSession(o,s),o);return je(i.signal),a||(await r("launch",o,i),je(i.signal),bd(await e.companion.launch(o,s),o))}),[ci]:(n,i)=>St(n,i,e,"write"),[di]:(n,i)=>St(n,i,e,"closeStdin"),[ui]:(n,i)=>St(n,i,e,"terminate"),[li]:(n,i)=>St(n,i,e,"ackOutput"),[fi]:async(n,i)=>{const o=await St(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[hi]:(n,i)=>St(n,i,e,"showNotification")}}function xm(e){if(!G(e)||typeof e.alias!="string"||!Tl.test(e.alias))throw E("INVALID_PARAMS","Companion alias 不合法");return e.alias}function je(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function St(e,t,r,n){if(!G(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw E("INVALID_PARAMS","Companion Session controller 不合法");try{je(t.signal);const i=await r.companion[n](Um(e,n),{...r.operationContext,signal:t.signal});return je(t.signal),i}catch(i){throw Mo(i)}}function Le(){throw E("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Td(e){return!Array.isArray(e)||e.some(t=>!Om.has(t))?Le():Object.freeze([...new Set(e)])}function Ao(e,t){return!G(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Dd.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!vm.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?Le():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Td(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function jm(e,t){const r=Ao(e,t);return!G(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!Lm.test(e.sha256)?Le():Object.freeze({...r,sha256:e.sha256})}function _d(e){return G(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):Le():Le()}function Zs(e){return G(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:_d(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&G(e.error)&&typeof e.error.code=="string"&&Rm.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:Sd[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):Le():Le()}function bd(e,t){return!G(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Dd.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?Le():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Td(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Xs(e,t){return e===void 0?void 0:bd(e,t)}function Um(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Fc(r.data))throw E("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 E("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw E("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw E("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function zm(e){return!G(e)||!Cm.has(String(e.reason))?Le():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):Le():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?Le():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Hm(e){if(!G(e)||!G(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||!Fc(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:zm(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 Mo(e,t){return G(e)&&typeof e.code=="string"&&Pm.has(e.code)?E(e.code,Sd[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&G(e)&&e.name==="AbortError"?E(t,"Companion 准备已取消"):E("COMPANION_HOST_FAILED","Companion Host 操作失败")}const ea=5e3,ta=1e4;function me(e){throw{code:"INVALID_PARAMS",message:e}}function ts(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Od(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&me(`${r} 不支持字段: ${n.join(", ")}`)}function Fm(e){if(e===void 0)return{intensity:"light",delay:0};if(!ts(e))return me("device.vibrate 参数必须是对象");Od(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return me("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>ea?me(`device.vibrate delay 必须是 0-${ea} 的整数毫秒`):{intensity:r,delay:n}}function Vm(e){return ts(e)?(Od(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?me("device.setClipboard text 必须是非空字符串"):e.text.length>ta?me(`device.setClipboard text 不能超过 ${ta} 字符`):{text:e.text}):me("device.setClipboard 参数必须是对象")}function Bm(e){return typeof e=="string"?e.trim()?e:me("device.executeProtocol 协议字符串不能为空"):ts(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?me("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(No(e,new Set),e):me("device.executeProtocol 参数必须是协议字符串或协议对象")}function No(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||me("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":me("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":me(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&me("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)No(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&me("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))No(i,t);t.delete(r)}function Gm(e){return{[Hn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.vibrate(Fm(t),e.operationContext),e.operationContext.signal)},[Fn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.setClipboard(Vm(t),e.operationContext),e.operationContext.signal)},[Vn]:async(t,r)=>{const n=ve(e.operationContext,r.signal);W(n.signal);const i=Bm(t);await K(()=>e.protocol.invoke(i,n),n.signal)}}}const ra=1e3,Qm=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function Ym(e){const t=r=>ve(e.operationContext,r.signal);return{files:{[bn]:async(r,n)=>{Ri(n);const i=Pi(e.picker),o=qm(r),s=await Ee(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[On]:async(r,n)=>{Ri(n);const i=Pi(e.picker),o=$m(r),s=await Ee(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[vn]:async(r,n)=>{Ri(n);const i=Pi(e.picker),o=Wm(r).suggestedName,s=t(n);if(!i.saveFile)throw Ne("files.saveFile");const a=await Ee(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[yr]:async(r,n)=>{const i=Me(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);Tt(o.mode),await Ee(()=>o.create(na(i),t(n)))},[Er]:async(r,n)=>{const i=Me(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),Tt(o.handle.mode),!o.handle.remove)throw Ne(Er);await Ee(()=>o.handle.remove(t(n)))},[Ln]:async(r,n)=>{const i=Me(r);return ia(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!G(o)||o.kind!=="file")throw sa()})},[wr]:async(r,n)=>{const i=Me(r),o=oa(await Ee(()=>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 E("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Cn]:async(r,n)=>{const i=Me(r,["content"]);typeof i.content!="string"&&Te("content 必须是字符串");const o=e.registry.resolveFile(i.target);Tt(o.mode),await Ee(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[Ir]:async(r,n)=>{const i=Me(r),o=await Ee(()=>e.registry.resolveFile(i.target).read(t(n)));return oa(o)},[Rn]:async(r,n)=>{const i=Me(r,["content"]),o=e.registry.resolveFile(i.target);Tt(o.mode),await Ee(()=>o.write(Jm(i.content),t(n)))},[Ar]:async(r,n)=>{const i=Me(r),o=await Ee(()=>e.registry.resolveFile(i.target).stat(t(n)));return Zm(o)}},directory:{[Pn]:async(r,n)=>{const i=Me(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);Tt(o.mode),await Ee(()=>o.create(na(i),t(n)))},[Mr]:async(r,n)=>{const i=Me(r,["recursive"]);if(G(i.target)&&i.target.relativePath===".")throw E("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),Tt(o.handle.mode),!o.handle.remove)throw Ne(Mr);await Ee(()=>o.handle.remove({recursive:i.recursive===void 0?!1:Kn(i.recursive,"recursive")},t(n)))},[kn]:async(r,n)=>{const i=Me(r);return ia(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!G(o)||o.kind!=="directory")throw sa()})},[xn]:async(r,n)=>{const i=Me(r,["limit"]),o=Km(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await Ee(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function qm(e){if(e===void 0)return{mode:"read",multiple:!1};G(e)||Te("pickFiles 参数必须是对象"),gi(e,["mode","accept","multiple"]);const t=vd(e.mode,"read"),r=e.multiple===void 0?!1:Kn(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)))&&Te("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function $m(e){return e===void 0?{mode:"read"}:(G(e)||Te("pickDirectory 参数必须是对象"),gi(e,["mode"]),{mode:vd(e.mode,"read")})}function Wm(e){return G(e)||Te("saveFile 参数必须是对象"),gi(e,["suggestedName"]),{suggestedName:xr(e.suggestedName,"suggestedName")}}function Me(e,t=[]){return(!G(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Te("文件操作参数必须包含 target"),gi(e,["target",...t]),e}function na(e){return{recursive:e.recursive===void 0?!1:Kn(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Kn(e.exclusive,"exclusive")}}function vd(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&Te("mode 必须是 read 或 readwrite"),e)}function Kn(e,t){return typeof e!="boolean"&&Te(`${t} 必须是布尔值`),e}function Km(e){if(e===void 0)return ra;if((!Number.isSafeInteger(e)||e<=0)&&Te("limit 必须是正整数"),e>ra)throw E("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function gi(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&Te(`不支持字段: ${r.join(", ")}`)}function Tt(e){if(e!=="readwrite")throw E("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Ri(e){if(!e.trustedUserGesture)throw E("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Pi(e){if(!e)throw Ne("files.external");return e}async function ia(e){try{return await e(),!0}catch(t){if(Qm.has(Jo(t)??""))return!1;throw Sr(t)}}async function Ee(e){try{return await e()}catch(t){throw Sr(t)}}function Jm(e){return e instanceof Uint8Array||Te("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Te("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function oa(e){if(!(e instanceof Uint8Array))throw E("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function sa(){return E("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Zm(e){if(!G(e)||e.kind!=="file"||!Xm(e.size))throw E("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!eg(e[t]))throw E("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 Xm(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function eg(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Te(e){throw E("INVALID_PARAMS",e)}const tg=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),ki={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function rg(e){if(e instanceof ue)return E("REQUEST_UNSUPPORTED",ki.REQUEST_UNSUPPORTED);const t=Ld(e);return t!==void 0&&tg.has(t)?E(t,ki[t]??"媒体操作失败"):E("MEDIA_PREPARE_FAILED",ki.MEDIA_PREPARE_FAILED)}function Ld(e){try{if(!G(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const ng=["source","mediaType","maxCount"],rn=Object.freeze({source:"album",mediaType:"all",maxCount:1});function ig(e){if(e===void 0)return rn;if(!hl(e))throw E("INVALID_PARAMS",sg(e));return og(e)}function og(e){return Object.freeze({source:e.source??rn.source,mediaType:e.mediaType??rn.mediaType,maxCount:e.maxCount??rn.maxCount})}function sg(e){if(!G(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!ng.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 ag=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),cg={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class dg{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=ug(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>fg(s,i[a]));if(!ml(o))throw He("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(hg).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=Ld(n);throw i!==void 0&&ag.has(i)?n:He("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function aa(e,t){if(e.signal.aborted)throw E("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw E("REQUEST_CANCELLED","media.pick 已取消")}function ug(e,t){if(!Array.isArray(e))throw He("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw He("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw He("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw He("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw He("Host 返回了稀疏媒体结果");lg(e[n],n)}return e}function lg(e,t){if(!G(e))throw He(`第 ${t+1} 项不是对象`);if(!Hc({...e,file:cg}))throw He(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!G(e.file))throw He(`第 ${t+1} 项缺少文件句柄`)}function fg(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 hg(e){return"handleId"in e.ref?e.ref.handleId:void 0}function He(e){return E("MEDIA_PREPARE_FAILED",e)}function mg(e){const t=e.media?new dg(e.registry,e.media,e.operationContext):void 0;return{handlers:{[Nr]:async(n,i)=>{const o=ig(n);pg(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw Ne(Nr);const c=ve(e.operationContext,i.signal);aa(e.operationContext,i.signal);const d=await gg(s,o,c,e.operationContext,i.signal);aa(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function gg(e,t,r,n,i){try{return await K(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?E("REQUEST_CANCELLED","media.pick 已取消"):rg(o)}}function pg(e){if(!e.trustedUserGesture)throw E("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const qr=4294967296;function yg(e){const t=new Eg;return t.write(e),t.finish()}class Eg{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<qr?(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=wg(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<qr)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/qr),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/qr)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function wg(e){const t=new Uint8Array(Ig(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 Ig(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 Cd(e){Do(e);const t=yg(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 Do(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)Do(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");Do(s,t+1,r)}r.delete(e)}const Ag=["pc","console","mobile"],Mg=["game","wiki"];function Jn(e){throw{code:"INVALID_PARAMS",message:e}}function Ng(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xe(e,t){return typeof e!="string"||!e.trim()?Jn(t):e.trim()}function ca(e,t,r){return typeof e!="string"||!t.includes(e)?Jn(r):e}function Dg(e){const t={target:"game_detail",appId:Xe(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:ca(e.gameType,Ag,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=ca(e.page,Mg,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Xe(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Xe(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Sg(e){return{target:"user_detail",userId:Xe(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Tg(e){const t={target:"post_detail",linkId:Xe(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Xe(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Xe(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function _g(e){const t={target:"mini_program",miniProgramId:Xe(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function bg(e){return Ng(e)?e.target==="game_detail"?Dg(e):e.target==="user_detail"?Sg(e):e.target==="post_detail"?Tg(e):e.target==="mini_program"?_g(e):Jn("navigation.openAppPage target 不支持"):Jn("navigation.openAppPage options 必须是对象")}function Og(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 vg(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Lg(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 Cg(e){const t=e;return t.target==="game_detail"?Og(t):t.target==="user_detail"?vg(t):Lg(t)}const Rg="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",Pg="data-hb-sdk-fullscreen-exit",kg=3e3,xg=2e3,da="var(--white-70a,rgba(255,255,255,.7))",ua="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function jg(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(Pg,""),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 ${da}`,`box-shadow:${ua}`,"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=Rg,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let o=!0,s=!1,a=!1,c,d;function u(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function f(){o||(t.style.width=u())}function l(){d?.cancel(),d=void 0}function h(T=xg){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")},T)}function w(){l(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=da,t.style.boxShadow=ua,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),h()}async function A(){if(!(s||a)){if(!o){w();return}a=!0,clearTimeout(c),l();try{await e()}catch{}finally{a=!1,s||w()}}}return t.addEventListener("click",A),window.addEventListener("resize",f),document.body.append(t),!r&&t.animate&&(d=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),h(kg),{dispose(){s=!0,clearTimeout(c),l(),t.removeEventListener("click",A),window.removeEventListener("resize",f),t.remove()}}}const Rd=1e4;function Pd(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()},Rd);return{signal:r.signal,async run(s){try{return await K(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 xi(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Xt(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function Ug(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(w){if(!w.hideCapsule){c();return}a??=jg(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",c,{once:!0});function u(w,A){if(n===w){if(n=void 0,clearTimeout(w.timer),e.operationContext.signal.removeEventListener("abort",f),"error"in A)w.controller.abort();else if(i={options:w.options,result:A.result},o=w.options,d(w.options),e.onApplied?.(w.options),A.result.supported&&!xi(s,w.options)){s={...w.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:w.source})}catch{}}for(const T of w.subscribers)T.dispose(),"error"in A?T.reject(A.error):T.resolve(A.result);w.subscribers.clear()}}function f(){n&&u(n,{error:Xt()})}function l(w,A){return new Promise((T,M)=>{const b=()=>{w.subscribers.delete(S),S.dispose(),M(Xt()),w.subscribers.size===0&&u(w,{error:Xt()})},S={resolve:T,reject:M,dispose:()=>A?.removeEventListener("abort",b)};w.subscribers.add(S),A?.addEventListener("abort",b,{once:!0}),A?.aborted&&b()})}const h={async runDisplayRequest(w,A,T){const M=++t,b=Pd(A,e.operationContext.signal);try{return await b.run(async()=>{if(await T(b.signal),b.signal.aborted)throw Xt();if(la(w),M<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=M,h.apply(w,b.signal)})}finally{b.dispose()}},async apply(w,A,T="api"){if(W(e.operationContext.signal),A?.aborted)throw Xt();const M=la(w),b=n?.options??o,S={mode:M.orientation??b.mode,hideCapsule:M.fullscreen??b.hideCapsule};S.mode==="landscape"&&(S.hideCapsule=!0);const R=e.presentation.applyOrientation;if(!R)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&xi(n.options,S))return l(n,A);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&xi(i.options,S))return i.result;i=void 0;const B={options:S,source:T,controller:new AbortController,subscribers:new Set};n=B;const U=l(B,A);return e.operationContext.signal.addEventListener("abort",f,{once:!0}),A||(B.timer=setTimeout(()=>{u(B,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Rd)),K(()=>R.call(e.presentation,S,{...e.operationContext,signal:B.controller.signal}),B.controller.signal).then(p=>u(B,{result:p??{supported:!0}}),p=>u(B,{error:p})),U},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return h}function kd(e){throw{code:"INVALID_PARAMS",message:e}}function fa(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&kd(`${t} 不支持参数`)}function zg(e){return{[Bn]:async t=>{W(e.operationContext.signal),fa(t,"navigation.close"),await K(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Gn]:async t=>{W(e.operationContext.signal),fa(t,"navigation.reload"),await K(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[Qn]:async(t,r)=>{const n=ve(e.operationContext,r?.signal);W(n.signal);const i=bg(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Cd(i.extra)}catch{kd("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=Pd(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}W(n.signal),await K(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await K(()=>e.presentation.openAppPage(Cg(i),n),n.signal)}}}const ha={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function Hg(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw Ne("network.upload");const o=ve(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw E("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(l){throw s(),Sr(l)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw E("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw E("FILE_TOO_LARGE","文件超过大小限制");let d=0,u=!1;const f=l=>{u||o.signal.aborted||!Number.isSafeInteger(l)||l<d||l>c.size||(d=l,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:l,...h}=e,w=await n.upload(a,{...h,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:f});if(u=!0,!Number.isSafeInteger(w.uploadedBytes)||w.uploadedBytes<d||w.uploadedBytes>c.size)throw E("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(w.status>=200&&w.status<300&&w.uploadedBytes!==c.size)throw E("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:w.uploadedBytes,total:c.size,lengthComputable:!0}),w}catch(l){u=!0;const h=Jo(l);throw h&&ha[h]?E(h,ha[h]):o.signal.aborted?E("UPLOAD_CANCELLED","上传已取消"):h?.startsWith("FILE_")||h?.startsWith("DIRECTORY_")?Sr(l):E("UPLOAD_NETWORK_FAILED","上传网络失败")}}const rs="withCredentials",Fg=new Set(["url","method","params","data","headers","timeout",rs]),Vg=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",rs]),Bg=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),ma=3e4,So=2*1024*1024,Gg=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,xd=/[\u0000-\u0008\u000A-\u001F\u007F]/,Qg=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Yg="network.request 不支持 multipart/form-data,请使用专用上传能力";function qg(e){const t=$g(e.runtimePermissions),r=cp(e.allowedHttpOrigins);return{[_n]:async(n,i)=>{const o=Kg(n,{permission:t,allowedHttpOrigins:r}),s=await Hg(o,i,e),{uploadedBytes:a,...c}=s;return pa(c)},[Tn]:async(n,i)=>{const o=Jg(n,{permission:t,allowedHttpOrigins:r});return Id(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Sn]:async(n,i)=>{const o=ve(e.operationContext,i?.signal);W(o.signal);const s=Wg(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await K(()=>e.network.request(s,o),o.signal)}catch(c){throw up(c)?c:lp(c,"REQUEST_UNSUPPORTED")?Y("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):Y("REQUEST_FAILED","网络请求失败")}return pa(a)}}}function $g(e){const t=Oe(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Wg(e,t){const r=Vt(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!Fg.has(c));if(n.length>0)throw Y("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);jd(r,"network.request");const i=ns(r,t,"network.request"),o=Xg(r.method),s=r.data;s!==void 0&&rp(s),ip(i.headers,s);const a=op(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 Kg(e,t){const r=Vt(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 Y("INVALID_PARAMS","network.upload 包含不支持的字段");const i=ns(r,t,"network.upload");if(i.official)throw Y("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw Y("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!Ut(r.from))throw Y("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Y("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw Y("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw Y("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 Y("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(u=>u.toLowerCase()==="content-type"))throw Y("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=ga(r.fieldName),c=r.fields===void 0?void 0:Vt(r.fields,"fields 必须是字符串字典");for(const[u,f]of Object.entries(c??{}))if(ga(u),typeof f!="string"||u===a)throw Y("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw Y("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||xd.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw Y("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>So)throw Y("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:Xo(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function ga(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw Y("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function Jg(e,t){const r=Vt(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!Vg.has(c));if(n.length>0)throw Y("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);jd(r,"network.download");const i=ns(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw Y("INVALID_PARAMS","network.download timeout 必须是有限正数");Im(i.headers);const o=Ut(r.to),s=Uc(r.to);if(!o&&!s)throw Y("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw Y("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw Y("INVALID_PARAMS","suggestedName 必须是字符串");a=Xo(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw Y("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Y("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 ns(e,t,r){const n=Zg(e.url,t.allowedHttpOrigins,r),i=df(n);if(i&&!t.permission.useOfficialDomain)throw Y("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(cf(n.pathname,i))throw Y("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Vt(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:ep(e.headers,r),timeout:tp(e.timeout,r)}}function Zg(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw Y("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw Y("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Y("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw Y("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw Y("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Xg(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw Y("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!Bg.has(t))throw Y("INVALID_PARAMS","network.request method 不合法");return t}function ep(e,t="network.request"){const r=Vt(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!Gg.test(s)||typeof o!="string"||xd.test(o))throw Y("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(uf(s))throw Y("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function jd(e,t){const r=e[rs];if(r!==void 0&&typeof r!="boolean")throw Y("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function tp(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw Y("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>ma)throw Y("INVALID_PARAMS",`${t} timeout 不能超过 ${ma}ms`);return e}}function rp(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw Y("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(np(e)>So)throw Y("INVALID_PARAMS",`network.request data 不能超过 ${So} 字节`)}function np(e){if(typeof e=="string")return ji(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return ji(e.toString());try{const t=JSON.stringify(e);return t?ji(t):0}catch{throw Y("INVALID_PARAMS","network.request data 必须可序列化")}}function ip(e,t){const r=Ud(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 Y("INVALID_PARAMS",Yg)}function op(e,t,r){if(t===void 0)return;const n=Ud(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)||ap(t))?"form":sp(t)?"json":void 0}function Ud(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function sp(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function ap(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function cp(e){const t=new Set;for(const r of e??[])try{const n=new URL(r);n.protocol==="http:"&&!n.username&&!n.password&&n.pathname==="/"&&!n.search&&!n.hash&&dp(n.hostname)&&t.add(n.origin)}catch{}return t}function dp(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 pa(e){return Object.keys(e.headers).some(ya)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!ya(t)))}:e}function ya(e){const t=e.trim().toLowerCase();return Qg.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function up(e){return e instanceof Error&&e.name==="AbortError"}function lp(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Vt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Y("INVALID_PARAMS",t);return e}function ji(e){return new TextEncoder().encode(e).length}function Y(e,t){return{code:e,message:t}}function fp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hp(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 mp(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=hp(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function gp(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 zd(e,t){if(e==null)return{};if(!fp(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=mp(e.topicIds),n=gp(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 pp(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function yp(e){try{if(pp(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function fe(e){throw{code:"INVALID_PARAMS",message:e}}function jr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function To(e,t){return typeof e!="string"||!e.trim()?fe(t):e}function Ep(e,t){const r=To(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?fe(t):r}catch{return fe(t)}}function wp(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Hd(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 Ip(e,t){if(!jr(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&&!wp(r))return fe("share.showShareMenu channel 不合法");const n=Fd(e.extra,"share.showShareMenu");return{title:To(e.title,"share.showShareMenu title 必须是非空字符串"),description:To(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Hd(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:Ep(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Fd(e,t){if(e!==void 0)try{return Cd(e)}catch{return fe(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function Vd(e,t){return e.invalidMessage&&await K(()=>yp(t.environment),t.operationContext.signal)?fe(e.invalidMessage):e.post}function Ea(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Ap(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Ea(t.windowWidth,0),height:Ea(t.windowHeight,0)}}function _o(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?fe(t):r}function wa(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?fe(t):r}function Mp(e){return jr(e)?{left:_o(e.left,"share.screenshot rect.left 必须是非负数字"),top:_o(e.top,"share.screenshot rect.top 必须是非负数字"),width:wa(e.width,"share.screenshot rect.width 必须是正数"),height:wa(e.height,"share.screenshot rect.height 必须是正数")}:fe("share.screenshot rect 必须是对象")}function Np(e,t){if(e!=null&&!jr(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?Ap(t):Mp(r.rect),...r.delay===void 0?{}:{delay:_o(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function Dp(e,t){W(t.operationContext.signal);const r=Ip(e,t);let n=zd(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await Vd(n,t);return K(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function Sp(e,t){if(W(t.operationContext.signal),e!==void 0&&!jr(e))return fe("share.copyLink 参数必须是对象");const r=Fd(e?.extra,"share.copyLink"),n=Hd(t,"share.copyLink",r);return await K(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Tp(e,t,r){W(t.operationContext.signal);const n=zd(jr(e)?e.post:void 0,{method:"share.screenshot"}),i=await Vd(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=_p(),{watermarkTheme:a,...c}=r;let d=!1,u,f;try{d=!0,await K(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),u=await t.prepareScreenshot?.(r.rect,t.operationContext.signal,a),f={status:"fulfilled",value:await K(()=>t.presentation.captureAndShare({...c,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(h){f={status:"rejected",error:h}}finally{u?.()}const l=d?await bp(t.presentation,s,t.operationContext.signal):void 0;if(f.status==="rejected")throw f.error;if(l)throw l;return f.value}function _p(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function bp(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await K(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function Op(e){let t=Promise.resolve();return{[In]:(r,n)=>Sp(r,e),[An]:(r,n)=>Dp(r,e),[Mn]:async(r,n)=>{const i=ve(e.operationContext,n.signal);W(i.signal);const o=Np(r,e.presentation),s=t.then(()=>Tp(r,{...e,operationContext:i},o));return t=s.then(()=>{},()=>{}),K(()=>s,i.signal)}}}const Ia=new WeakMap;function Bd(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return Ul(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${$c(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Gd(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=Ia.get(t);f||(f=new Map,Ia.set(t,f));const l=f.get(u)??Promise.resolve(),h=async()=>(W(c.signal,{preserveReason:!0}),d(u)),w=l.catch(()=>{}).then(()=>e.lock?e.lock(u,h):h());f.set(u,w);try{return await w}finally{f.get(u)===w&&f.delete(u)}},o=async(c,d,u=!1)=>{const f=It(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(w=>w.key.startsWith(f)&&w.value!=="").map(w=>w.key.slice(f.length)))];const l=await e.storage.getRaw(Vr(c),d);if((l===void 0||l==="")&&!u)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let h;try{h=l?JSON.parse(l):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(h)||h.length>Es||h.some(w=>typeof w!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(w)))throw new Error("本地数据索引异常");return[...new Set(h)]},s=async(c,d)=>{if(e.diagnostics){const l=It(c,"");return(await e.diagnostics.listRaw(d)).filter(h=>h.key.startsWith(l)&&h.value!=="").map(h=>({...h,key:h.key.slice(l.length)}))}const u=[],f=await o(c,d);for(let l=0;l<f.length;l+=16){W(d.signal,{preserveReason:!0});const h=await Promise.all(f.slice(l,l+16).map(async w=>{const A=await e.storage.getRaw(It(c,w),d);return A!==void 0&&A!==""?{area:"local",key:w,value:A}:void 0}));for(const w of h)w&&u.push(w)}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(It(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>=Es)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const h=[...new Set([...l,c])];await e.storage.setRaw(Vr(f),JSON.stringify(h),u)}W(u.signal,{preserveReason:!0}),await e.storage.setRaw(It(f,c),d,u),W(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(Vr(d),JSON.stringify(u),c);for(let f=0;f<u.length;f+=16){W(c.signal,{preserveReason:!0});const h=(await Promise.allSettled(u.slice(f,f+16).map(w=>e.storage.setRaw(It(d,w),"",c)))).find(w=>w.status==="rejected");if(h)throw h.reason}W(c.signal,{preserveReason:!0}),await e.storage.setRaw(Vr(d),"[]",c)})}}}function vp(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 Lp=128,Cp=/^[A-Za-z0-9_-]+$/;function Rp(e){const t=e.scopedStorage??Gd({storage:e.storage,resolveScope:()=>Bd({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[gr]:async n=>{W(e.operationContext.signal);const i=Aa(n,gr,e.storageLimits?.maxKeyLength),o=await K(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:Ma(o)}},[pr]:async n=>{W(e.operationContext.signal);const i=Qd(n,"storage.setStorage 参数必须是对象"),o=Aa(i,pr,e.storageLimits?.maxKeyLength),s=Pp(i.data,e.storageLimits?.maxValueBytes);await K(()=>t.set(o,s,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(W(e.operationContext.signal),(await K(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?lt("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:Ma(o),serializedValue:o,bytes:Yd(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function Aa(e,t,r=Lp){const i=Qd(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw lt("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!Cp.test(i))throw lt("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function Pp(e,t){let r;try{r=JSON.stringify(e)}catch{throw lt("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw lt("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Yd(r)>t)throw lt("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Ma(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Qd(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw lt("INVALID_PARAMS",t);return e}function Yd(e){return new TextEncoder().encode(e).length}function lt(e,t){return{code:e,message:t}}const Na=120;function We(e){throw{code:"INVALID_PARAMS",message:e}}function is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qd(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&We(`${r} 不支持字段: ${n.join(", ")}`)}function kp(e){if(!is(e))return We("ui.showToast 参数必须是对象");if(qd(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return We("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Na)return We(`ui.showToast message 不能超过 ${Na} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return We("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function xp(e){return e===void 0?{dismissible:!1}:is(e)?(qd(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?We("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):We("ui.showLoading 参数必须是对象")}function jp(e){e!==void 0&&(!is(e)||Object.keys(e).length)&&We("ui.hideLoading 不支持参数")}function Up(e){return{[jn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.showToast(kp(t),e.operationContext),e.operationContext.signal)},[Un]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.showLoading(xp(t),e.operationContext),e.operationContext.signal)},[zn]:async t=>{W(e.operationContext.signal),jp(t),await K(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const zp={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return le(e,"当前用户首页资料接口响应异常")}},Hp=3e4;function Fp(e,t,r={}){const n=r.ttlMs??Hp,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function d(){let f;try{f=await mi(e,zp,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(l){throw t.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):l instanceof ue?E("REQUEST_UNSUPPORTED",l.message):l instanceof kr?E("INVALID_RESPONSE","user home_v2 响应不合法"):l instanceof Ft?E("REQUEST_FAILED","user home_v2 请求失败"):l instanceof Ht?i&&(l.status===403||l.status===429)?E("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:l.status,...l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs}}):E("REQUEST_FAILED",l.message):Bp(l)?l:E("REQUEST_FAILED","user home_v2 请求失败")}return Vp(f,"user home_v2")}function u(f){const l=Date.now();if(a?.userId===f&&a.expiresAt>l)return Promise.resolve(a.value);if(c?.userId===f&&c.generation===s)return c.promise;const h=s,w=d().then(A=>(s===h&&(a={userId:f,value:A,expiresAt:Date.now()+n}),A)).finally(()=>{c?.promise===w&&(c=void 0)});return c={userId:f,generation:h,promise:w},w}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function Vp(e,t){if(!G(e))throw E("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 E(n,r)}if(!G(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Bp(e){return G(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Gp={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 le(e,"Steam 游戏库接口响应异常")}};function Qp(e,t=go){const r=ff({version:"2",validate:qp}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):go,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 Da(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 Yp(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 qp(e){if(!G(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Sa(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Ct();for(const t of e.gameList){if(!G(t)||!bo(t.appid)||!bo(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Ct();for(const r of["image","portraitImage","icon"])$p(t,r);for(const r of["playtimeForever","playtime2Weeks"])Sa(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Ct()}return e}function bo(e){return typeof e=="number"&&Number.isFinite(e)}function Sa(e,t){if(e[t]!==void 0&&!bo(e[t]))throw Ct()}function $p(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Ct()}function Ct(){return E("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const $d=20,Wp=100,Kp=128,Wd=0,Kd="weeks",Jp=100,Zp=new Set(["weeks","all","achieved"]);function Xp(){return{nickname:"",avatar:""}}function ey(e){const t=Fp(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??Jc(),i=Qp(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(g,I){const y=JSON.stringify([g,I]);return(!o||o.key!==y)&&(o={key:y,scope:n.createScope(I,n.createScope(g))}),o.scope}function d(){const g=o;o=void 0,g&&n.invalidateScope(g.scope).catch(()=>{}),s.clear()}const u=cd({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??sd))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let l=0,h=!1;const w=e.account.onChange(()=>{l+=1,t.clear(),u.invalidate(),d()}),A=e.authorization.onEvent((g,I)=>{g==="user_info_authorization_change"&&Object.values(I).some(y=>y==="denied")&&(l+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(h)return;const y=await e.account.getCurrentUserId(e.operationContext);typeof y=="string"&&y.trim()&&await n.invalidateScope(c(M(),y.trim()))}).catch(()=>{}))});function T(){if(h||e.operationContext.signal.aborted)throw E("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function M(){const g=e.identity.get()?.miniProgramId?.trim();if(!g)throw E("INVALID_STATE","用户能力缺少 canonical 小程序身份");return g}async function b(){T(),await a,T();let g;try{g=await e.account.getCurrentUserId(e.operationContext)}catch(I){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):ba(I)?I:E("REQUEST_FAILED","读取小黑盒账号失败")}return typeof g=="string"&&g.trim()?g.trim():void 0}async function S(g,I){const y=await b();if(l!==I||y!==g)throw E("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function R(g,I,y=e.operationContext.signal){try{return await mi(e.network,g,I,{...e.operationContext,signal:y,credentials:"heybox-session",...f?{gate:f}:{}})}catch(_){throw e.operationContext.signal.aborted?E("RUNTIME_DESTROYED","小程序 Runtime 已终止"):_ instanceof ue?E("REQUEST_UNSUPPORTED",_.message):_ instanceof kr?E("INVALID_RESPONSE","用户接口响应不合法"):_ instanceof Ft?E("REQUEST_FAILED","用户请求失败"):_ instanceof Ht?r&&(_.status===403||_.status===429)?E("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:_.status,..._.retryAfterMs===void 0?{}:{retryAfterMs:_.retryAfterMs}}):E("REQUEST_FAILED",_.message):ba(_)?_:E("REQUEST_FAILED","用户请求失败")}}async function B(){M();const g=l,I=await b();if(!I)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[y,_]=await Promise.all([e.authorization.getOrCreateLocalIdentity(I),U(I).catch(()=>Xp())]);return await S(I,g),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:y.appUserId,profile:_,...y.steamId?{steam_id:y.steamId}:{}}}}function U(g){return u.read(g,()=>R(ad,void 0).then(I=>{const y=Ta(I,"账号基础信息");if(y.display_username!==void 0&&typeof y.display_username!="string")throw E("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(y.display_avatar!==void 0&&typeof y.display_avatar!="string")throw E("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:y.display_username??"",avatar:y.display_avatar??""}}))}async function p(g){const I=ty(g),y=M(),_=l,m=await b();if(!m)return d(),{isLogin:!1,isBound:!1,data:null};const D=await t.get(m);await S(m,_);const v=Jd(D.steam_id_info);if(Object.keys(v).length===0)return await n.invalidateScope(c(y,m)).catch(()=>{}),await S(m,_),s.delete(JSON.stringify([y,m])),{isLogin:!0,isBound:!1,data:null};const k=JSON.stringify([y,m]),x=c(y,m),L=Da({...I,steamId:void 0},v),N=Zd(v.personal_infomation_open??v.personal_information_open),O=JSON.stringify([L??null,N??null]),C=s.get(k);C&&C.identity!==O&&(await n.invalidateScope(x).catch(()=>{}),await S(m,_));const P={identity:O,scope:n.createScope(O,x)};s.set(k,P);const z=Da(I,v),H=z?i.persistent:i.unresolved,F=n.createScope(z??"unresolved",P.scope),Q=async()=>{if(await S(m,_),M()!==y||s.get(k)?.identity!==O)throw E("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},J=await H.read({scope:F,key:Yp({miniProgramId:y,userId:m,effectiveSteamId:z,personalInformationOpen:N,query:I}),signal:e.operationContext.signal,load:async $=>{const X=await R(Gp,{userId:m,...I,personalInformationOpen:N},$);return await Q(),sy(Ta(X,"Steam 游戏库"),I)}}).catch(async $=>{throw await Q(),$});return await Q(),{isLogin:!0,isBound:!0,data:J}}return{getInfo:B,getSteamGameList:p,async invalidateSteamGameListCache(){const g=M(),I=l,y=await b();if(!y)return;const _=c(g,y);await Promise.all([i.persistent.invalidateScope(_),i.unresolved.invalidateScope(_)]),t.clear(),s.delete(JSON.stringify([g,y])),await S(y,I)},dispose(){h||(h=!0,l+=1,w(),A(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function ty(e){if(e==null)return{limit:$d,offset:Wd,sort:Kd,includeHidden:!1};if(!G(e))throw Ke("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Ke(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:ry(e.limit),offset:ny(e.offset),sort:iy(e.sort),includeHidden:oy(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>Kp)throw Ke("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ke("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Jp))}return r}function ry(e){if(e===void 0)return $d;if(!Number.isInteger(e)||Number(e)<1)throw Ke("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Wp)}function ny(e){if(e===void 0)return Wd;if(!Number.isInteger(e)||Number(e)<0)throw Ke("user.getSteamGameList offset 必须是非负整数");return Number(e)}function iy(e){if(e===void 0)return Kd;if(typeof e!="string"||!Zp.has(e))throw Ke("user.getSteamGameList sort 不支持");return e}function oy(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ke("user.getSteamGameList includeHidden 必须是 boolean");return e}function sy(e,t){if(!Array.isArray(e.game_list))throw E("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(ay).filter(a=>a!==void 0),n=Zn(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=Zd(e.is_me);return s!==void 0&&(o.isMe=s),o}function ay(e){const t=Jd(e),r=Zn(t.appid),n=Zn(t.steam_appid)??r,i=os(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};Ui(o,"image",t.image),typeof t.vertical_head_image=="string"&&Ui(o,"portraitImage",t.vertical_head_image),Ui(o,"icon",t.appicon??t.icon),_a(o,"playtimeForever",t.playtime_forever),_a(o,"playtime2Weeks",t.playtime_2weeks);const s=cy(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function Ta(e,t){if(!G(e))throw E("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 E(n,r)}if(!G(e.result))throw E("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Jd(e){return G(e)?e:{}}function os(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function cy(e){return Array.isArray(e)?e.map(os).filter(Boolean):[]}function Zn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function Zd(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function Ui(e,t,r){const n=os(r);n&&Object.assign(e,{[t]:n})}function _a(e,t,r){const n=Zn(r);n!==void 0&&Object.assign(e,{[t]:n})}function Ke(e){return E("INVALID_PARAMS",e)}function ba(e){return G(e)&&typeof e.code=="string"&&typeof e.message=="string"}function dy(e){return{[yn]:async t=>(Oa(t,"user.getInfo"),e.user.getInfo()),[En]:async(t,r)=>{Oa(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[wn]:async t=>e.user.getSteamGameList(t)}}function Oa(e,t){if(e!==void 0)throw E("INVALID_PARAMS",`${t} 不接收入参`)}function va(e){throw{code:"INVALID_PARAMS",message:e}}function er(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Xd(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function $r(e,t,r){return Math.min(Xd(e,t),r)}async function uy(e){try{return Xd(await e.getNavigationBarHeight(),0)}catch{return 0}}function ly(e,t,r,n){const i=$r(e.safeArea?.left,0,t),o=Math.max(i,$r(e.safeArea?.right,t,t)),s=$r(e.safeArea?.top,n,r),a=Math.max(s,$r(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function La(e){const t=e.getViewportMetrics(),r=er(t.windowWidth,0),n=er(t.windowHeight,0),i=await uy(e);return{pixelRatio:er(t.pixelRatio,1),screenWidth:er(t.screenWidth,r),screenHeight:er(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:ly(t,r,n,i),screenTop:i}}function fy(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;La(r.presentation).then(l=>{if(n||r.operationContext.signal.aborted||f!==i)return;const h=JSON.stringify(l);h!==o&&(o=h,r.onViewportChange?.(l))}).catch(()=>{})},c=Ug({...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:{[ht]:async(f,l)=>c.apply(f,l?.signal),[Nn]:async()=>(W(r.operationContext.signal),La(r.presentation)),[Dn]:async f=>{if(W(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return va("viewport.setNavigationBarStyle 参数必须是对象");const l=f.foregroundStyle;if(l!=="light"&&l!=="dark")return va("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await K(()=>r.presentation.setNavigationBarStyle(l,e.operationContext),r.operationContext.signal)}},runDisplayRequest:c.runDisplayRequest,applyOrientation:(f,l)=>c.apply({orientation:f.mode,fullscreen:f.hideCapsule},l),notifyChange:()=>{o=void 0,a()},dispose:d}}const hy=new Map(Ze.map(e=>[e.method,e]));function nn(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function my(e){const t=_l(e);return r=>t(r.requirement,r.method)}function gy(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 py(e){const t=my(e.runtimePermissions),r=Oe(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??yy,c=e.onTrace?a():0,d=e.onTrace?`cap_${++n}`:"";try{if(e.terminalSignal.aborted)throw nn("RUNTIME_DESTROYED","小程序 Runtime 已终止");Hl(i,e.effectiveCapabilities);const u=hy.get(i);if(!u)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const f=t(u),l=!f.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,o)===!0,h=!f.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,o)===!0;if(!f.allowed&&!l&&!h)throw nn(f.code,f.message,f.data);const w=e.handlers[i];if(!w)throw new Error(`Capability method ${i} 缺少 handler`);const A=async b=>{for(const S of e.policies??[]){const R=await S.evaluate({method:i,payload:o,capability:u});if(e.terminalSignal.aborted||b.aborted)throw Pa();if(!R.allowed)throw nn(R.code,R.message,R.data)}if(e.terminalSignal.aborted||b.aborted)throw Pa()},M=await gy(async()=>{if(i===ht){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,A)}return await A(e.terminalSignal),w(o,s)},void 0,s,e.terminalSignal);return Ca(e.onTrace,Ra(d,i,o,c,M),a),M}catch(u){throw Ca(e.onTrace,Ra(d,i,o,c,{status:"error",error:u}),a),u}}}}function yy(){return typeof performance>"u"?Date.now():performance.now()}function Ca(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 Ra(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:Ey(i.error)}:{},...wy(t,r,i)}}function Ey(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function wy(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"&&eu(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 eu(e){return typeof e=="object"&&e!==null}function Pa(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Iy(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=bf(e.requestPolicy);let n;if(e.files)try{n=Ef(e.files,t)}catch{}const i=Jc({store:n}),o=e.onRequestPolicyReport??(r.debugReport?Ay:void 0),s=r.enabled?Df({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Zo(e.files,e.miniProgramDetail),c=Ym({registry:a,picker:e.picker,operationContext:t}),d=eh({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode,authorizationContext:e.authorizationContext,identityTtlMs:r.identityTtlMs,requestGate:s,requestPolicyEnabled:r.enabled});let u,f,l,h,w,A=()=>{},T=()=>{};try{u=fy({operationContext:t,presentation:e.hostPresentation,onDisplayChange:g=>e.eventSink.postEvent("display_change",g),onViewportChange:g=>e.eventSink.postEvent("viewport_change",g)}),l=ey({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}),A=d.onEvent((g,I)=>e.eventSink.postEvent(g,I)),T=e.hostCompanion?.onSessionEvent?.(g=>{const I=Hm(g);!e.terminalSignal.aborted&&I&&e.eventSink.postEvent(I.type,I.payload)})??(()=>{}),h=kh({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled}),w=Sm({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 M=Rp({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});f=mg({registry:a,media:e.media,operationContext:t});const b=[{name:"gameSaves",handlers:w.handlers},{name:"auth",handlers:ch({authorization:d})},{name:"user",handlers:dy({user:l,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:Op({prepareScreenshot:e.prepareScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:u.handlers},{name:"storage",handlers:M.handlers},{name:"network",handlers:qg({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[mn]:async()=>{throw nn("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:Up({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Gm({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:zg({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:g=>u.applyOrientation({mode:"portrait",hideCapsule:!1},g)}:{}})},{name:"cloud",handlers:h.handlers},{name:"companion",handlers:km({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],S=My(b);let R=!1;const B=()=>{R||(R=!0,e.terminalSignal.removeEventListener("abort",B),u?.dispose(),f?.dispose(),h?.dispose(),w?.dispose(),A(),T(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?B():e.terminalSignal.addEventListener("abort",B,{once:!0});const U=new Set(["file.readText","file.readBytes","file.stat"]),p=(g,I)=>U.has(g)&&eu(I)&&a.isCompanionAttachmentRef(I.target);return{modules:b,handlers:S,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:p,allowsGameSaveAccess:w.allowsRead,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...M.diagnostics?{storageDiagnostics:M.diagnostics}:{},dispose:B}}catch(M){throw u?.dispose(),f?.dispose(),h?.dispose(),w?.dispose(),A(),T(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),M}}function Ay(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function My(e){const t=new Map(Ze.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=Ze.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Ze.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Ny="heybox-mini-dev:";function ka(e){try{return Dy(new URL(e))}catch{return!1}}function Dy(e){return e.protocol===Ny}function Sy(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Ty(e)}function Ty(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 _y=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function by(e,t){const r=[],n=Oy(e.environmentInfo,r),i=on(n?.appVersion,"host.appVersion",r),o=Ly(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:vy(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:on(t.miniProgramId),version:on(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function Oy(e,t){if(e!=null){if(tu(e))return e;t.push("environmentInfo")}}function vy(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function Ly(e,t){if(e==null)return{name:"unknown",version:null};if(!tu(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=_y.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:on(e.version,"operatingSystem.version",t)}}function on(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function tu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Cy="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",Ry="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",Py="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",ky="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function xy(e,t,r,n,i="dark"){W(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?Py:Cy,l.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const h=e.createElement("div");h.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${c};border-radius:11px;padding:0 7px 0 6px;`;const w=e.createElement("img");w.src=a?ky:Ry,w.style.cssText="width:12px;height:12px;flex-shrink:0;";const A=e.createElement("span");A.textContent=t?.trim()||"小程序工坊",A.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const T=e.createElement("div");T.textContent="小黑盒工坊小程序",T.style.cssText=`margin-top:6px;color:${a?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,h.append(w,A),f.append(l,h),u.append(f,T),s.append(u),e.body.append(s);const M=()=>{s.remove(),n.removeEventListener("abort",M)};n.addEventListener("abort",M,{once:!0});try{return await K(()=>Promise.all([l.decode(),w.decode()]),n),await K(()=>new Promise(b=>{let S=o.requestAnimationFrame(()=>{S=o.requestAnimationFrame(()=>{n.removeEventListener("abort",R),b()})});const R=()=>o.cancelAnimationFrame(S);n.addEventListener("abort",R,{once:!0})}),n),M}catch(b){throw M(),b}}const jy=1,ru="allow-scripts allow-same-origin",Uy="",zy="no-referrer";function Hy(e=ru){return!e.split(/\s+/).includes("allow-same-origin")}function xa(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Fy=new Set(["javascript:","data:","blob:","file:"]),ja="xiaoheihe.cn";function Vy(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(Fy.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!qy(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function By(e,t){const r=new URL(e);return r.searchParams.set(ol,t),r.toString()}function Gy(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Qy(r)??Yy(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Qy(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Yy(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function Ua(e){const t=new URL(e);return ss(t)?"loopback":as(t)?"lan":"production"}function qy(e,t,r){return $y(e)||ss(e)||as(e)&&Ky(t,r)}function $y(e){return e.protocol==="https:"&&Xy(e.hostname)}function ss(e){return e.protocol==="http:"&&Wy(e.hostname)}function Wy(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function as(e){return e.protocol==="http:"&&Jy(e.hostname)}function Ky(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return ss(r)||as(r)}catch{return!1}}function Jy(e){const t=Zy(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Zy(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 Xy(e){return e===ja||e.endsWith(`.${ja}`)}const eE=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"]),tE=new Set(["url","inline","eval","unknown"]),rE=/^\/(?:\:segment(?:\/\:segment)*)?$/,nE=/^[a-f0-9]{64}$/,iE=255,oE=160,sE=256;function aE(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!eE.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>sE||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!tE.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=cE(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>oE||!rE.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!nE.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 cE(e){if(e!==void 0&&!(typeof e!="string"||e.length>iE))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const dE=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function uE(e){if(!e?.minimumSdkVersion)throw ee("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=ct(e.minimumSdkVersion),r=e.sdkVersion?ct(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=ct("0.6.0");if(!r){if(sn(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(sn(r,t)<0)throw ee("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:sn(r,ct("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function lE(e,t){if(typeof t!="string"||!ct(t))throw ee("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw ee("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function nu(e,t){const r=ct(e),n=ct(t);if(!(!r||!n))return sn(r,n)}function ct(e){const t=dE.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 sn(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 pi=["android","ios","ohos","windows","macos","linux"],fE="0.9.0",hE=Object.freeze(["android","ios","ohos","windows","macos"]),iu="该小程序暂不支持当前平台",mE="PLATFORM_UNSUPPORTED";function gE(e){return typeof e=="string"&&pi.includes(e)}function pE(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 yE(e){const t=e.manifest;if(!ME(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Ha(e.sdkVersion)??Ha(t.sdkVersion);return IE(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:wE()}const r=ou(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function EE(e){const t=pE(e.operatingSystemName);if(!t)return Ot("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Ot("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:pi,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=yE({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Ot("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):za(t,s)}if(r.effectivePlatforms===void 0)return Ot("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=ou(r.effectivePlatforms);if("reason"in n)return Ot("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=AE(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return za(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function za(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Ot("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Ot(e,t={}){return{status:"denied",reason:e,message:iu,...t}}function wE(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:hE,platformsDeclared:!1,policy:"legacy_mobile_default"}}function ou(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(!gE(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(pi.filter(r=>t.has(r)))}}function IE(e){if(typeof e!="string"||!e.trim())return!1;const t=nu(e.trim(),fE);return t!==void 0&&t>=0}function Ha(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function AE(e){return e==="explicit"||e==="legacy_mobile_default"}function ME(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const NE=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 DE(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:SE(i.pathname),sanitizedPathnameHash:TE(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function SE(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function TE(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 T=0;T<16;T+=1)o[T]=s.getUint32(a+T*4,!1);for(let T=16;T<64;T+=1){const M=o[T-15],b=o[T-2],S=ke(M,7)^ke(M,18)^M>>>3,R=ke(b,17)^ke(b,19)^b>>>10;o[T]=o[T-16]+S+o[T-7]+R>>>0}let[c,d,u,f,l,h,w,A]=i;for(let T=0;T<64;T+=1){const M=A+(ke(l,6)^ke(l,11)^ke(l,25))+(l&h^~l&w)+NE[T]+o[T]>>>0,b=(ke(c,2)^ke(c,13)^ke(c,22))+(c&d^c&u^d&u);A=w,w=h,h=l,l=f+M>>>0,f=u,u=d,d=c,c=M+b>>>0}[c,d,u,f,l,h,w,A].forEach((T,M)=>{i[M]=i[M]+T>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ke(e,t){return e>>>t|e<<32-t}const _E=1e4,bE=1e4,zi=2e3,OE=2,vE="open-with-native-credential-policy",su="安全提示",au="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class LE{nonce=xa();runtimeId=xa();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=Kc(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??_E,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics;return t?{storage:t}:{}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??ee("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??ee("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(HE(),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=bl(t.runtimePermissions),this.runtimeFeatures=t.runtimeFeatures?Object.freeze({...t.runtimeFeatures}):void 0,this.miniProgramPresentation=t.miniProgramPresentation,this.locationBasePath=t.locationBasePath,this.anonymousStorageScope=t.anonymousStorageScope??this.options.anonymousStorageScope;const r=t.allowedHttpOrigins??this.options.allowedHttpOrigins;this.allowedHttpOrigins=r?Object.freeze([...r]):void 0,this.bindCanonicalIdentity(t.canonicalIdentity),this.sdkVersionDecision=uE(t.sdkVersionPolicy);const n=by(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=EE({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw BE(this.platformGateDecision);if(this.miniProgramDetail=GE(t),this.effectiveCapabilities=Wc(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),kE(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(jE(i)),this.launchUrl=i,this.miniProgramSrc=By(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=Yo(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:ht,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ge(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[ht])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=Iy({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||(nu(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):xy(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=py({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}:{}};Ge(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new Pl({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 PE(t)?t:cu(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 Vy(t,r,{allowPrivateNetwork:ka(r)||Fa(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??zE)({message:au,title:su,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Ua(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!ka(r)&&!Fa(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{Va(),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(()=>Va())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Uy),this.iframe.setAttribute("referrerpolicy",zy),this.iframe.setAttribute("sandbox",ru)}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(),Ge(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(),Ge(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{lE(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>=OE)){this.failRuntime(ee("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Hr,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:Hr})}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(Hr,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Hr})}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?bE: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===al){this.handleCspViolation(t.payload);return}if(t.method!==sl)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"||!Gy(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=aE(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){Ge(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=DE(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:jy,launchUrlType:Ua(t),networkPolicy:vE})}failRuntime(t){const r=CE(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),Ge(this.options.onError,RE(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,Ge(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ge(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 CE(e){const t=Yo(e);return Xn(e)&&"cause"in e&&cu(t,e.cause),t}function cu(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function RE(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function PE(e){return Xn(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Xn(e){return!!e&&typeof e=="object"}function Ge(e,t){try{e?.(t)}catch{}}function kE(e,t,r){try{e?.(t,r)}catch{}}function Fa(e){try{const t=new URL(e);return t.protocol==="http:"&&Sy(t.hostname)}catch{return!1}}function xE(e){try{return new URL(e).origin}catch{return}}function jE(e){return Hy()?"*":xE(e)}function UE(e){return`${su}
2
2
 
3
3
  ${au}
4
4
 
5
- URL: ${e}`}function zE(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(UE(e.url))}function Va(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function HE(){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:Pc,knownMethodCount:Ze.length,supportsFileCreate:Ze.some(i=>i.method===yr),system:FE(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:_t(e?.hardwareConcurrency),maxTouchPoints:_t(e?.maxTouchPoints),screen:{width:_t(t?.width),height:_t(t?.height)},viewport:{width:_t(r?.innerWidth),height:_t(r?.innerHeight),devicePixelRatio:VE(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function FE(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 _t(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function VE(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function BE(e){return ee(mE,iu,{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 GE(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 QE(e){if(!Xn(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!Xn(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 CE(e)}function YE(e={}){return async(t,r,n)=>{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");const i=e.indexedDB??globalThis.indexedDB,o=e.crypto??globalThis.crypto;if(!i||!o?.getRandomValues)throw new Error("Host 缺少持久化账号标识能力");const s=await new Promise((a,c)=>{const d=i.open("heybox-mini-program-private-account-v1",1);let u=!1;const f=()=>n.signal.removeEventListener("abort",h),l=w=>{u||(u=!0,f(),c(w))},h=()=>l(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{u?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>l(d.error),d.onblocked=()=>l(new Error("账号存储被阻塞")),d.onsuccess=()=>{u?d.result.close():(u=!0,f(),a(d.result))},n.signal.addEventListener("abort",h,{once:!0}),n.signal.aborted&&h()});try{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");return await new Promise((a,c)=>{const d=s.transaction("accounts","readwrite"),u=d.objectStore("accounts"),f=JSON.stringify([t,r]);let l;const h=()=>{try{d.abort()}catch{}w(),c(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",h,{once:!0});const w=()=>n.signal.removeEventListener("abort",h);d.oncomplete=()=>{w(),a(l)},d.onabort=d.onerror=()=>{w(),c(d.error??new Error("账号存储事务失败"))};const A=u.get(f);A.onsuccess=()=>{try{if(typeof A.result=="string"&&/^ak_[0-9a-f]{64}$/.test(A.result))l=A.result;else{const T=o.getRandomValues(new Uint8Array(32));l=`ak_${Array.from(T,M=>M.toString(16).padStart(2,"0")).join("")}`,u.put(l,f)}}catch{d.abort()}}})}finally{s.close()}}}const qE=/^(?: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,$E=new Set(["origin","referer","user-agent"]);function WE(e,t){return Bl({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=KE(r),a=await e.authenticatedRequest(s,o);return XE(a)})}).network}function KE(e){const t=JE(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function JE(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!ZE(t)))}function ZE(e){const t=e.trim().toLowerCase();return $E.has(t)}function XE(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:ew(e.headers)??{}}}function ew(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!tw(t)))}function tw(e){const t=e.trim().toLowerCase();return qE.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function rw(e,t,r){const n=aw(e.presentation,t);return{account:ow(e,t,r),network:WE(e,t),...e.storage===void 0?{}:{storage:sw(e,t)},...e.storage===void 0?{}:nw(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function nw(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 iw(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 ow(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??YE();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 sw(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 aw(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)=>tf(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 cw(){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 Wr(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 Wr(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(Wr(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 Wr(f.reason);return u}finally{for(const{listener:u,source:f}of c)f.removeEventListener("abort",u)}}}}function Wr(e){return new DOMException("Web Host operation aborted","AbortError")}async function dw(e){const t=cw(),r=new Set;let n=!1;const i=l=>{if(n||t.signal.aborted)return Hi(l),()=>{};let h=!0;const w=()=>{h&&(h=!1,r.delete(w),Hi(l))};return r.add(w),w},o=()=>s(e.signal.reason),s=l=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(l);for(const h of[...r])h();e.onDispose&&Hi(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=rw(e,t,i);a.storage?.getRaw&&a.storage.setRaw&&(a.scopedStorage=Gd({storage:a.storage,diagnostics:a.storageDiagnostics,coordinationKey:e.storage.storage,lock:vp,resolveScope:async()=>Bd((await f()).configuration)}));const c=Kc(a,{hostCapabilities:e.hostCapabilities}),d=iw(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:uw(e.authPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function Hi(e){try{e()}catch{}}function uw(e,t){return{confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var bt={},Fi,Ba;function lw(){return Ba||(Ba=1,Fi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Fi}var Vi={},Qe={},Ga;function pt(){if(Ga)return Qe;Ga=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 Qe.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},Qe.getSymbolTotalCodewords=function(n){return t[n]},Qe.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Qe.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Qe.isKanjiModeEnabled=function(){return typeof e<"u"},Qe.toSJIS=function(n){return e(n)},Qe}var Bi={},Qa;function cs(){return Qa||(Qa=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}}})(Bi)),Bi}var Gi,Ya;function fw(){if(Ya)return Gi;Ya=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++}},Gi=e,Gi}var Qi,qa;function hw(){if(qa)return Qi;qa=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]},Qi=e,Qi}var Yi={},$a;function mw(){return $a||($a=1,(function(e){const t=pt().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}})(Yi)),Yi}var qi={},Wa;function gw(){if(Wa)return qi;Wa=1;const e=pt().getSymbolSize,t=7;return qi.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},qi}var $i={},Ka;function pw(){return Ka||(Ka=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,d=null,u=null;for(let f=0;f<o;f++){a=c=0,d=u=null;for(let l=0;l<o;l++){let h=i.get(f,l);h===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=h,a=1),h=i.get(l,f),h===u?c++:(c>=5&&(s+=t.N1+(c-5)),u=h,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const d=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(d===4||d===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let d=0;d<o;d++){a=c=0;for(let u=0;u<o;u++)a=a<<1&2047|i.get(d,u),u>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(u,d),u>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let d=0;d<s;d++){o(d),e.applyMask(d,i);const u=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(d,i),u<c&&(c=u,a=d)}return a}})($i)),$i}var Kr={},Ja;function du(){if(Ja)return Kr;Ja=1;const e=cs(),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 Kr.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}},Kr.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}},Kr}var Wi={},tr={},Za;function yw(){if(Za)return tr;Za=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]})(),tr.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},tr.exp=function(n){return e[n]},tr.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},tr}var Xa;function Ew(){return Xa||(Xa=1,(function(e){const t=yw();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}})(Wi)),Wi}var Ki,ec;function ww(){if(ec)return Ki;ec=1;const e=Ew();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},Ki=t,Ki}var Ji={},Zi={},Xi={},tc;function uu(){return tc||(tc=1,Xi.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Xi}var xe={},rc;function lu(){if(rc)return xe;rc=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
5
+ URL: ${e}`}function zE(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(UE(e.url))}function Va(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function HE(){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:Pc,knownMethodCount:Ze.length,supportsFileCreate:Ze.some(i=>i.method===yr),system:FE(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:_t(e?.hardwareConcurrency),maxTouchPoints:_t(e?.maxTouchPoints),screen:{width:_t(t?.width),height:_t(t?.height)},viewport:{width:_t(r?.innerWidth),height:_t(r?.innerHeight),devicePixelRatio:VE(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function FE(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 _t(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function VE(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function BE(e){return ee(mE,iu,{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 GE(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 QE(e){if(!Xn(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!Xn(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 LE(e)}function YE(e={}){return async(t,r,n)=>{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");const i=e.indexedDB??globalThis.indexedDB,o=e.crypto??globalThis.crypto;if(!i||!o?.getRandomValues)throw new Error("Host 缺少持久化账号标识能力");const s=await new Promise((a,c)=>{const d=i.open("heybox-mini-program-private-account-v1",1);let u=!1;const f=()=>n.signal.removeEventListener("abort",h),l=w=>{u||(u=!0,f(),c(w))},h=()=>l(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{u?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>l(d.error),d.onblocked=()=>l(new Error("账号存储被阻塞")),d.onsuccess=()=>{u?d.result.close():(u=!0,f(),a(d.result))},n.signal.addEventListener("abort",h,{once:!0}),n.signal.aborted&&h()});try{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");return await new Promise((a,c)=>{const d=s.transaction("accounts","readwrite"),u=d.objectStore("accounts"),f=JSON.stringify([t,r]);let l;const h=()=>{try{d.abort()}catch{}w(),c(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",h,{once:!0});const w=()=>n.signal.removeEventListener("abort",h);d.oncomplete=()=>{w(),a(l)},d.onabort=d.onerror=()=>{w(),c(d.error??new Error("账号存储事务失败"))};const A=u.get(f);A.onsuccess=()=>{try{if(typeof A.result=="string"&&/^ak_[0-9a-f]{64}$/.test(A.result))l=A.result;else{const T=o.getRandomValues(new Uint8Array(32));l=`ak_${Array.from(T,M=>M.toString(16).padStart(2,"0")).join("")}`,u.put(l,f)}}catch{d.abort()}}})}finally{s.close()}}}const qE=/^(?: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,$E=new Set(["origin","referer","user-agent"]);function WE(e,t){return Bl({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=KE(r),a=await e.authenticatedRequest(s,o);return XE(a)})}).network}function KE(e){const t=JE(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function JE(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!ZE(t)))}function ZE(e){const t=e.trim().toLowerCase();return $E.has(t)}function XE(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:ew(e.headers)??{}}}function ew(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!tw(t)))}function tw(e){const t=e.trim().toLowerCase();return qE.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function rw(e,t,r){const n=aw(e.presentation,t);return{account:ow(e,t,r),network:WE(e,t),...e.storage===void 0?{}:{storage:sw(e,t)},...e.storage===void 0?{}:nw(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function nw(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 iw(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 ow(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??YE();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 sw(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 aw(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)=>tf(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 cw(){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 Wr(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 Wr(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(Wr(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 Wr(f.reason);return u}finally{for(const{listener:u,source:f}of c)f.removeEventListener("abort",u)}}}}function Wr(e){return new DOMException("Web Host operation aborted","AbortError")}async function dw(e){const t=cw(),r=new Set;let n=!1;const i=l=>{if(n||t.signal.aborted)return Hi(l),()=>{};let h=!0;const w=()=>{h&&(h=!1,r.delete(w),Hi(l))};return r.add(w),w},o=()=>s(e.signal.reason),s=l=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(l);for(const h of[...r])h();e.onDispose&&Hi(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=rw(e,t,i);a.storage?.getRaw&&a.storage.setRaw&&(a.scopedStorage=Gd({storage:a.storage,diagnostics:a.storageDiagnostics,coordinationKey:e.storage.storage,lock:vp,resolveScope:async()=>Bd((await f()).configuration)}));const c=Kc(a,{hostCapabilities:e.hostCapabilities}),d=iw(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:uw(e.authPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function Hi(e){try{e()}catch{}}function uw(e,t){return{confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var bt={},Fi,Ba;function lw(){return Ba||(Ba=1,Fi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Fi}var Vi={},Qe={},Ga;function pt(){if(Ga)return Qe;Ga=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 Qe.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},Qe.getSymbolTotalCodewords=function(n){return t[n]},Qe.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Qe.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Qe.isKanjiModeEnabled=function(){return typeof e<"u"},Qe.toSJIS=function(n){return e(n)},Qe}var Bi={},Qa;function cs(){return Qa||(Qa=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}}})(Bi)),Bi}var Gi,Ya;function fw(){if(Ya)return Gi;Ya=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++}},Gi=e,Gi}var Qi,qa;function hw(){if(qa)return Qi;qa=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]},Qi=e,Qi}var Yi={},$a;function mw(){return $a||($a=1,(function(e){const t=pt().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}})(Yi)),Yi}var qi={},Wa;function gw(){if(Wa)return qi;Wa=1;const e=pt().getSymbolSize,t=7;return qi.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},qi}var $i={},Ka;function pw(){return Ka||(Ka=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,d=null,u=null;for(let f=0;f<o;f++){a=c=0,d=u=null;for(let l=0;l<o;l++){let h=i.get(f,l);h===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=h,a=1),h=i.get(l,f),h===u?c++:(c>=5&&(s+=t.N1+(c-5)),u=h,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const d=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(d===4||d===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let d=0;d<o;d++){a=c=0;for(let u=0;u<o;u++)a=a<<1&2047|i.get(d,u),u>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(u,d),u>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let d=0;d<s;d++){o(d),e.applyMask(d,i);const u=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(d,i),u<c&&(c=u,a=d)}return a}})($i)),$i}var Kr={},Ja;function du(){if(Ja)return Kr;Ja=1;const e=cs(),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 Kr.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}},Kr.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}},Kr}var Wi={},tr={},Za;function yw(){if(Za)return tr;Za=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]})(),tr.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},tr.exp=function(n){return e[n]},tr.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},tr}var Xa;function Ew(){return Xa||(Xa=1,(function(e){const t=yw();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}})(Wi)),Wi}var Ki,ec;function ww(){if(ec)return Ki;ec=1;const e=Ew();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},Ki=t,Ki}var Ji={},Zi={},Xi={},tc;function uu(){return tc||(tc=1,Xi.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Xi}var xe={},rc;function lu(){if(rc)return xe;rc=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
6
  ]))+`;xe.KANJI=new RegExp(r,"g"),xe.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),xe.BYTE=new RegExp(n,"g"),xe.NUMERIC=new RegExp(e,"g"),xe.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return xe.testKanji=function(c){return i.test(c)},xe.testNumeric=function(c){return o.test(c)},xe.testAlphanumeric=function(c){return s.test(c)},xe}var nc;function yt(){return nc||(nc=1,(function(e){const t=uu(),r=lu();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}}})(Zi)),Zi}var ic;function Iw(){return ic||(ic=1,(function(e){const t=pt(),r=du(),n=cs(),i=yt(),o=uu(),s=7973,a=t.getBCHDigit(s);function c(l,h,w){for(let A=1;A<=40;A++)if(h<=e.getCapacity(A,w,l))return A}function d(l,h){return i.getCharCountIndicator(l,h)+4}function u(l,h){let w=0;return l.forEach(function(A){const T=d(A.mode,h);w+=T+A.getBitsLength()}),w}function f(l,h){for(let w=1;w<=40;w++)if(u(l,w)<=e.getCapacity(w,h,i.MIXED))return w}e.from=function(h,w){return o.isValid(h)?parseInt(h,10):w},e.getCapacity=function(h,w,A){if(!o.isValid(h))throw new Error("Invalid QR Code version");typeof A>"u"&&(A=i.BYTE);const T=t.getSymbolTotalCodewords(h),M=r.getTotalCodewordsCount(h,w),b=(T-M)*8;if(A===i.MIXED)return b;const S=b-d(A,h);switch(A){case i.NUMERIC:return Math.floor(S/10*3);case i.ALPHANUMERIC:return Math.floor(S/11*2);case i.KANJI:return Math.floor(S/13);case i.BYTE:default:return Math.floor(S/8)}},e.getBestVersionForData=function(h,w){let A;const T=n.from(w,n.M);if(Array.isArray(h)){if(h.length>1)return f(h,T);if(h.length===0)return 1;A=h[0]}else A=h;return c(A.mode,A.getLength(),T)},e.getEncodedBits=function(h){if(!o.isValid(h)||h<7)throw new Error("Invalid QR Code version");let w=h<<12;for(;t.getBCHDigit(w)-a>=0;)w^=s<<t.getBCHDigit(w)-a;return h<<12|w}})(Ji)),Ji}var eo={},oc;function Aw(){if(oc)return eo;oc=1;const e=pt(),t=1335,r=21522,n=e.getBCHDigit(t);return eo.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},eo}var to={},ro,sc;function Mw(){if(sc)return ro;sc=1;const e=yt();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))},ro=t,ro}var no,ac;function Nw(){if(ac)return no;ac=1;const e=yt(),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)},no=r,no}var io,cc;function Dw(){if(cc)return io;cc=1;const e=yt();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)},io=t,io}var oo,dc;function Sw(){if(dc)return oo;dc=1;const e=yt(),t=pt();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)}},oo=r,oo}var so={exports:{}},uc;function Tw(){return uc||(uc=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,d,u,f,l,h,w,A,T;!a.empty();){c=a.pop(),d=c.value,f=c.cost,l=r[d]||{};for(u in l)l.hasOwnProperty(u)&&(h=l[u],w=f+h,A=s[u],T=typeof s[u]>"u",(T||A>w)&&(s[u]=w,a.push(u,w),o[u]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var M=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(M)}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})(so)),so.exports}var lc;function _w(){return lc||(lc=1,(function(e){const t=yt(),r=Mw(),n=Nw(),i=Dw(),o=Sw(),s=lu(),a=pt(),c=Tw();function d(M){return unescape(encodeURIComponent(M)).length}function u(M,b,S){const R=[];let B;for(;(B=M.exec(S))!==null;)R.push({data:B[0],index:B.index,mode:b,length:B[0].length});return R}function f(M){const b=u(s.NUMERIC,t.NUMERIC,M),S=u(s.ALPHANUMERIC,t.ALPHANUMERIC,M);let R,B;return a.isKanjiModeEnabled()?(R=u(s.BYTE,t.BYTE,M),B=u(s.KANJI,t.KANJI,M)):(R=u(s.BYTE_KANJI,t.BYTE,M),B=[]),b.concat(S,R,B).sort(function(p,m){return p.index-m.index}).map(function(p){return{data:p.data,mode:p.mode,length:p.length}})}function l(M,b){switch(b){case t.NUMERIC:return r.getBitsLength(M);case t.ALPHANUMERIC:return n.getBitsLength(M);case t.KANJI:return o.getBitsLength(M);case t.BYTE:return i.getBitsLength(M)}}function h(M){return M.reduce(function(b,S){const R=b.length-1>=0?b[b.length-1]:null;return R&&R.mode===S.mode?(b[b.length-1].data+=S.data,b):(b.push(S),b)},[])}function w(M){const b=[];for(let S=0;S<M.length;S++){const R=M[S];switch(R.mode){case t.NUMERIC:b.push([R,{data:R.data,mode:t.ALPHANUMERIC,length:R.length},{data:R.data,mode:t.BYTE,length:R.length}]);break;case t.ALPHANUMERIC:b.push([R,{data:R.data,mode:t.BYTE,length:R.length}]);break;case t.KANJI:b.push([R,{data:R.data,mode:t.BYTE,length:d(R.data)}]);break;case t.BYTE:b.push([{data:R.data,mode:t.BYTE,length:d(R.data)}])}}return b}function A(M,b){const S={},R={start:{}};let B=["start"];for(let U=0;U<M.length;U++){const p=M[U],m=[];for(let I=0;I<p.length;I++){const y=p[I],_=""+U+I;m.push(_),S[_]={node:y,lastCount:0},R[_]={};for(let g=0;g<B.length;g++){const D=B[g];S[D]&&S[D].node.mode===y.mode?(R[D][_]=l(S[D].lastCount+y.length,y.mode)-l(S[D].lastCount,y.mode),S[D].lastCount+=y.length):(S[D]&&(S[D].lastCount=y.length),R[D][_]=l(y.length,y.mode)+4+t.getCharCountIndicator(y.mode,b))}}B=m}for(let U=0;U<B.length;U++)R[B[U]].end=0;return{map:R,table:S}}function T(M,b){let S;const R=t.getBestModeForData(M);if(S=t.from(b,R),S!==t.BYTE&&S.bit<R.bit)throw new Error('"'+M+'" cannot be encoded with mode '+t.toString(S)+`.
8
- Suggested mode is: `+t.toString(R));switch(S===t.KANJI&&!a.isKanjiModeEnabled()&&(S=t.BYTE),S){case t.NUMERIC:return new r(M);case t.ALPHANUMERIC:return new n(M);case t.KANJI:return new o(M);case t.BYTE:return new i(M)}}e.fromArray=function(b){return b.reduce(function(S,R){return typeof R=="string"?S.push(T(R,null)):R.data&&S.push(T(R.data,R.mode)),S},[])},e.fromString=function(b,S){const R=f(b,a.isKanjiModeEnabled()),B=w(R),U=A(B,S),p=c.find_path(U.map,"start","end"),m=[];for(let I=1;I<p.length-1;I++)m.push(U.table[p[I]].node);return e.fromArray(h(m))},e.rawSplit=function(b){return e.fromArray(f(b,a.isKanjiModeEnabled()))}})(to)),to}var fc;function bw(){if(fc)return Vi;fc=1;const e=pt(),t=cs(),r=fw(),n=hw(),i=mw(),o=gw(),s=pw(),a=du(),c=ww(),d=Iw(),u=Aw(),f=yt(),l=_w();function h(U,p){const m=U.size,I=o.getPositions(p);for(let y=0;y<I.length;y++){const _=I[y][0],g=I[y][1];for(let D=-1;D<=7;D++)if(!(_+D<=-1||m<=_+D))for(let v=-1;v<=7;v++)g+v<=-1||m<=g+v||(D>=0&&D<=6&&(v===0||v===6)||v>=0&&v<=6&&(D===0||D===6)||D>=2&&D<=4&&v>=2&&v<=4?U.set(_+D,g+v,!0,!0):U.set(_+D,g+v,!1,!0))}}function w(U){const p=U.size;for(let m=8;m<p-8;m++){const I=m%2===0;U.set(m,6,I,!0),U.set(6,m,I,!0)}}function A(U,p){const m=i.getPositions(p);for(let I=0;I<m.length;I++){const y=m[I][0],_=m[I][1];for(let g=-2;g<=2;g++)for(let D=-2;D<=2;D++)g===-2||g===2||D===-2||D===2||g===0&&D===0?U.set(y+g,_+D,!0,!0):U.set(y+g,_+D,!1,!0)}}function T(U,p){const m=U.size,I=d.getEncodedBits(p);let y,_,g;for(let D=0;D<18;D++)y=Math.floor(D/3),_=D%3+m-8-3,g=(I>>D&1)===1,U.set(y,_,g,!0),U.set(_,y,g,!0)}function M(U,p,m){const I=U.size,y=u.getEncodedBits(p,m);let _,g;for(_=0;_<15;_++)g=(y>>_&1)===1,_<6?U.set(_,8,g,!0):_<8?U.set(_+1,8,g,!0):U.set(I-15+_,8,g,!0),_<8?U.set(8,I-_-1,g,!0):_<9?U.set(8,15-_-1+1,g,!0):U.set(8,15-_-1,g,!0);U.set(I-8,8,1,!0)}function b(U,p){const m=U.size;let I=-1,y=m-1,_=7,g=0;for(let D=m-1;D>0;D-=2)for(D===6&&D--;;){for(let v=0;v<2;v++)if(!U.isReserved(y,D-v)){let k=!1;g<p.length&&(k=(p[g]>>>_&1)===1),U.set(y,D-v,k),_--,_===-1&&(g++,_=7)}if(y+=I,y<0||m<=y){y-=I,I=-I;break}}}function S(U,p,m){const I=new r;m.forEach(function(v){I.put(v.mode.bit,4),I.put(v.getLength(),f.getCharCountIndicator(v.mode,U)),v.write(I)});const y=e.getSymbolTotalCodewords(U),_=a.getTotalCodewordsCount(U,p),g=(y-_)*8;for(I.getLengthInBits()+4<=g&&I.put(0,4);I.getLengthInBits()%8!==0;)I.putBit(0);const D=(g-I.getLengthInBits())/8;for(let v=0;v<D;v++)I.put(v%2?17:236,8);return R(I,U,p)}function R(U,p,m){const I=e.getSymbolTotalCodewords(p),y=a.getTotalCodewordsCount(p,m),_=I-y,g=a.getBlocksCount(p,m),D=I%g,v=g-D,k=Math.floor(I/g),x=Math.floor(_/g),C=x+1,N=k-x,O=new c(N);let L=0;const P=new Array(g),z=new Array(g);let H=0;const F=new Uint8Array(U.buffer);for(let q=0;q<g;q++){const ce=q<v?x:C;P[q]=F.slice(L,L+ce),z[q]=O.encode(P[q]),L+=ce,H=Math.max(H,ce)}const Q=new Uint8Array(I);let J=0,$,X;for($=0;$<H;$++)for(X=0;X<g;X++)$<P[X].length&&(Q[J++]=P[X][$]);for($=0;$<N;$++)for(X=0;X<g;X++)Q[J++]=z[X][$];return Q}function B(U,p,m,I){let y;if(Array.isArray(U))y=l.fromArray(U);else if(typeof U=="string"){let k=p;if(!k){const x=l.rawSplit(U);k=d.getBestVersionForData(x,m)}y=l.fromString(U,k||40)}else throw new Error("Invalid data");const _=d.getBestVersionForData(y,m);if(!_)throw new Error("The amount of data is too big to be stored in a QR Code");if(!p)p=_;else if(p<_)throw new Error(`
7
+ Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},oo=r,oo}var so={exports:{}},uc;function Tw(){return uc||(uc=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,d,u,f,l,h,w,A,T;!a.empty();){c=a.pop(),d=c.value,f=c.cost,l=r[d]||{};for(u in l)l.hasOwnProperty(u)&&(h=l[u],w=f+h,A=s[u],T=typeof s[u]>"u",(T||A>w)&&(s[u]=w,a.push(u,w),o[u]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var M=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(M)}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})(so)),so.exports}var lc;function _w(){return lc||(lc=1,(function(e){const t=yt(),r=Mw(),n=Nw(),i=Dw(),o=Sw(),s=lu(),a=pt(),c=Tw();function d(M){return unescape(encodeURIComponent(M)).length}function u(M,b,S){const R=[];let B;for(;(B=M.exec(S))!==null;)R.push({data:B[0],index:B.index,mode:b,length:B[0].length});return R}function f(M){const b=u(s.NUMERIC,t.NUMERIC,M),S=u(s.ALPHANUMERIC,t.ALPHANUMERIC,M);let R,B;return a.isKanjiModeEnabled()?(R=u(s.BYTE,t.BYTE,M),B=u(s.KANJI,t.KANJI,M)):(R=u(s.BYTE_KANJI,t.BYTE,M),B=[]),b.concat(S,R,B).sort(function(p,g){return p.index-g.index}).map(function(p){return{data:p.data,mode:p.mode,length:p.length}})}function l(M,b){switch(b){case t.NUMERIC:return r.getBitsLength(M);case t.ALPHANUMERIC:return n.getBitsLength(M);case t.KANJI:return o.getBitsLength(M);case t.BYTE:return i.getBitsLength(M)}}function h(M){return M.reduce(function(b,S){const R=b.length-1>=0?b[b.length-1]:null;return R&&R.mode===S.mode?(b[b.length-1].data+=S.data,b):(b.push(S),b)},[])}function w(M){const b=[];for(let S=0;S<M.length;S++){const R=M[S];switch(R.mode){case t.NUMERIC:b.push([R,{data:R.data,mode:t.ALPHANUMERIC,length:R.length},{data:R.data,mode:t.BYTE,length:R.length}]);break;case t.ALPHANUMERIC:b.push([R,{data:R.data,mode:t.BYTE,length:R.length}]);break;case t.KANJI:b.push([R,{data:R.data,mode:t.BYTE,length:d(R.data)}]);break;case t.BYTE:b.push([{data:R.data,mode:t.BYTE,length:d(R.data)}])}}return b}function A(M,b){const S={},R={start:{}};let B=["start"];for(let U=0;U<M.length;U++){const p=M[U],g=[];for(let I=0;I<p.length;I++){const y=p[I],_=""+U+I;g.push(_),S[_]={node:y,lastCount:0},R[_]={};for(let m=0;m<B.length;m++){const D=B[m];S[D]&&S[D].node.mode===y.mode?(R[D][_]=l(S[D].lastCount+y.length,y.mode)-l(S[D].lastCount,y.mode),S[D].lastCount+=y.length):(S[D]&&(S[D].lastCount=y.length),R[D][_]=l(y.length,y.mode)+4+t.getCharCountIndicator(y.mode,b))}}B=g}for(let U=0;U<B.length;U++)R[B[U]].end=0;return{map:R,table:S}}function T(M,b){let S;const R=t.getBestModeForData(M);if(S=t.from(b,R),S!==t.BYTE&&S.bit<R.bit)throw new Error('"'+M+'" cannot be encoded with mode '+t.toString(S)+`.
8
+ Suggested mode is: `+t.toString(R));switch(S===t.KANJI&&!a.isKanjiModeEnabled()&&(S=t.BYTE),S){case t.NUMERIC:return new r(M);case t.ALPHANUMERIC:return new n(M);case t.KANJI:return new o(M);case t.BYTE:return new i(M)}}e.fromArray=function(b){return b.reduce(function(S,R){return typeof R=="string"?S.push(T(R,null)):R.data&&S.push(T(R.data,R.mode)),S},[])},e.fromString=function(b,S){const R=f(b,a.isKanjiModeEnabled()),B=w(R),U=A(B,S),p=c.find_path(U.map,"start","end"),g=[];for(let I=1;I<p.length-1;I++)g.push(U.table[p[I]].node);return e.fromArray(h(g))},e.rawSplit=function(b){return e.fromArray(f(b,a.isKanjiModeEnabled()))}})(to)),to}var fc;function bw(){if(fc)return Vi;fc=1;const e=pt(),t=cs(),r=fw(),n=hw(),i=mw(),o=gw(),s=pw(),a=du(),c=ww(),d=Iw(),u=Aw(),f=yt(),l=_w();function h(U,p){const g=U.size,I=o.getPositions(p);for(let y=0;y<I.length;y++){const _=I[y][0],m=I[y][1];for(let D=-1;D<=7;D++)if(!(_+D<=-1||g<=_+D))for(let v=-1;v<=7;v++)m+v<=-1||g<=m+v||(D>=0&&D<=6&&(v===0||v===6)||v>=0&&v<=6&&(D===0||D===6)||D>=2&&D<=4&&v>=2&&v<=4?U.set(_+D,m+v,!0,!0):U.set(_+D,m+v,!1,!0))}}function w(U){const p=U.size;for(let g=8;g<p-8;g++){const I=g%2===0;U.set(g,6,I,!0),U.set(6,g,I,!0)}}function A(U,p){const g=i.getPositions(p);for(let I=0;I<g.length;I++){const y=g[I][0],_=g[I][1];for(let m=-2;m<=2;m++)for(let D=-2;D<=2;D++)m===-2||m===2||D===-2||D===2||m===0&&D===0?U.set(y+m,_+D,!0,!0):U.set(y+m,_+D,!1,!0)}}function T(U,p){const g=U.size,I=d.getEncodedBits(p);let y,_,m;for(let D=0;D<18;D++)y=Math.floor(D/3),_=D%3+g-8-3,m=(I>>D&1)===1,U.set(y,_,m,!0),U.set(_,y,m,!0)}function M(U,p,g){const I=U.size,y=u.getEncodedBits(p,g);let _,m;for(_=0;_<15;_++)m=(y>>_&1)===1,_<6?U.set(_,8,m,!0):_<8?U.set(_+1,8,m,!0):U.set(I-15+_,8,m,!0),_<8?U.set(8,I-_-1,m,!0):_<9?U.set(8,15-_-1+1,m,!0):U.set(8,15-_-1,m,!0);U.set(I-8,8,1,!0)}function b(U,p){const g=U.size;let I=-1,y=g-1,_=7,m=0;for(let D=g-1;D>0;D-=2)for(D===6&&D--;;){for(let v=0;v<2;v++)if(!U.isReserved(y,D-v)){let k=!1;m<p.length&&(k=(p[m]>>>_&1)===1),U.set(y,D-v,k),_--,_===-1&&(m++,_=7)}if(y+=I,y<0||g<=y){y-=I,I=-I;break}}}function S(U,p,g){const I=new r;g.forEach(function(v){I.put(v.mode.bit,4),I.put(v.getLength(),f.getCharCountIndicator(v.mode,U)),v.write(I)});const y=e.getSymbolTotalCodewords(U),_=a.getTotalCodewordsCount(U,p),m=(y-_)*8;for(I.getLengthInBits()+4<=m&&I.put(0,4);I.getLengthInBits()%8!==0;)I.putBit(0);const D=(m-I.getLengthInBits())/8;for(let v=0;v<D;v++)I.put(v%2?17:236,8);return R(I,U,p)}function R(U,p,g){const I=e.getSymbolTotalCodewords(p),y=a.getTotalCodewordsCount(p,g),_=I-y,m=a.getBlocksCount(p,g),D=I%m,v=m-D,k=Math.floor(I/m),x=Math.floor(_/m),L=x+1,N=k-x,O=new c(N);let C=0;const P=new Array(m),z=new Array(m);let H=0;const F=new Uint8Array(U.buffer);for(let q=0;q<m;q++){const ce=q<v?x:L;P[q]=F.slice(C,C+ce),z[q]=O.encode(P[q]),C+=ce,H=Math.max(H,ce)}const Q=new Uint8Array(I);let J=0,$,X;for($=0;$<H;$++)for(X=0;X<m;X++)$<P[X].length&&(Q[J++]=P[X][$]);for($=0;$<N;$++)for(X=0;X<m;X++)Q[J++]=z[X][$];return Q}function B(U,p,g,I){let y;if(Array.isArray(U))y=l.fromArray(U);else if(typeof U=="string"){let k=p;if(!k){const x=l.rawSplit(U);k=d.getBestVersionForData(x,g)}y=l.fromString(U,k||40)}else throw new Error("Invalid data");const _=d.getBestVersionForData(y,g);if(!_)throw new Error("The amount of data is too big to be stored in a QR Code");if(!p)p=_;else if(p<_)throw new Error(`
9
9
  The chosen QR Code version cannot contain this amount of data.
10
10
  Minimum version required to store current data is: `+_+`.
11
- `);const g=S(p,m,y),D=e.getSymbolSize(p),v=new n(D);return h(v,p),w(v),A(v,p),M(v,m,0),p>=7&&T(v,p),b(v,g),isNaN(I)&&(I=s.getBestMask(v,M.bind(null,v,m))),s.applyMask(I,v),M(v,m,I),{modules:v,version:p,errorCorrectionLevel:m,maskPattern:I,segments:y}}return Vi.create=function(p,m){if(typeof p>"u"||p==="")throw new Error("No input text");let I=t.M,y,_;return typeof m<"u"&&(I=t.from(m.errorCorrectionLevel,t.M),y=d.from(m.version),_=s.from(m.maskPattern),m.toSJISFunc&&e.setToSJISFunction(m.toSJISFunc)),B(p,y,I,_)},Vi}var ao={},co={},hc;function fu(){return hc||(hc=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),d=Math.floor((s+o.margin*2)*c),u=o.margin*c,f=[o.color.light,o.color.dark];for(let l=0;l<d;l++)for(let h=0;h<d;h++){let w=(l*d+h)*4,A=o.color.light;if(l>=u&&h>=u&&l<d-u&&h<d-u){const T=Math.floor((l-u)/c),M=Math.floor((h-u)/c);A=f[a[T*s+M]?1:0]}n[w++]=A.r,n[w++]=A.g,n[w++]=A.b,n[w]=A.a}}})(co)),co}var mc;function Ow(){return mc||(mc=1,(function(e){const t=fu();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)}})(ao)),ao}var uo={},gc;function vw(){if(gc)return uo;gc=1;const e=fu();function t(i,o){const s=i.a/255,a=o+'="'+i.hex+'"';return s<1?a+" "+o+'-opacity="'+s.toFixed(2).slice(1)+'"':a}function r(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function n(i,o,s){let a="",c=0,d=!1,u=0;for(let f=0;f<i.length;f++){const l=Math.floor(f%o),h=Math.floor(f/o);!l&&!d&&(d=!0),i[f]?(u++,f>0&&l>0&&i[f-1]||(a+=d?r("M",l+s,.5+h+s):r("m",c,0),c=0,d=!1),l+1<o&&i[f+1]||(a+=r("h",u),u=0)):c++}return a}return uo.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,u=o.modules.data,f=d+c.margin*2,l=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(c.color.dark,"stroke")+' d="'+n(u,d,c.margin)+'"/>',w='viewBox="0 0 '+f+" "+f+'"',T='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+w+' shape-rendering="crispEdges">'+l+h+`</svg>
12
- `;return typeof a=="function"&&a(null,T),T},uo}var pc;function Cw(){if(pc)return bt;pc=1;const e=lw(),t=bw(),r=Ow(),n=vw();function i(o,s,a,c,d){const u=[].slice.call(arguments,1),f=u.length,l=typeof u[f-1]=="function";if(!l&&!e())throw new Error("Callback required as last argument");if(l){if(f<2)throw new Error("Too few arguments provided");f===2?(d=a,a=s,s=c=void 0):f===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=s,s=c=void 0):f===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(h,w){try{const A=t.create(a,c);h(o(A,s,c))}catch(A){w(A)}})}try{const h=t.create(a,c);d(null,o(h,s,c))}catch(h){d(h)}}return bt.create=t.create,bt.toCanvas=i.bind(null,r.render),bt.toDataURL=i.bind(null,r.renderToDataURL),bt.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),bt}var Lw=Cw();const Rw="/__hb_sdk__/dev-context";function yc(e,t){return br(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId: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:br(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 dr(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Bc(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:Sl({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 Pw(e){if(!br(e)||!Ec(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!br(t)||!Ec(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const kw={networkRequest:{status:"disabled",useOfficialDomain:!1}};function yi(e){const t=Oe(e.localDevGrant?Qo({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}}:Uw()}function xw(e,t,r){return r?.localDevGrant?Qo({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:hu(e,t,t.networkRequest.useOfficialDomain)}function jw(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=yi({...e,localDevGrant:void 0});return hu(e.runtimePermissions,t,!1)}function Uw(){return{networkRequest:{...kw.networkRequest}}}function hu(e,t,r){const n=Oe(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of Dr){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=br(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 br(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Ec(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function zw(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 Hw(e){return zw({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 Fw(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 Vw={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};function Bw(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=`
11
+ `);const m=S(p,g,y),D=e.getSymbolSize(p),v=new n(D);return h(v,p),w(v),A(v,p),M(v,g,0),p>=7&&T(v,p),b(v,m),isNaN(I)&&(I=s.getBestMask(v,M.bind(null,v,g))),s.applyMask(I,v),M(v,g,I),{modules:v,version:p,errorCorrectionLevel:g,maskPattern:I,segments:y}}return Vi.create=function(p,g){if(typeof p>"u"||p==="")throw new Error("No input text");let I=t.M,y,_;return typeof g<"u"&&(I=t.from(g.errorCorrectionLevel,t.M),y=d.from(g.version),_=s.from(g.maskPattern),g.toSJISFunc&&e.setToSJISFunction(g.toSJISFunc)),B(p,y,I,_)},Vi}var ao={},co={},hc;function fu(){return hc||(hc=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),d=Math.floor((s+o.margin*2)*c),u=o.margin*c,f=[o.color.light,o.color.dark];for(let l=0;l<d;l++)for(let h=0;h<d;h++){let w=(l*d+h)*4,A=o.color.light;if(l>=u&&h>=u&&l<d-u&&h<d-u){const T=Math.floor((l-u)/c),M=Math.floor((h-u)/c);A=f[a[T*s+M]?1:0]}n[w++]=A.r,n[w++]=A.g,n[w++]=A.b,n[w]=A.a}}})(co)),co}var mc;function Ow(){return mc||(mc=1,(function(e){const t=fu();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)}})(ao)),ao}var uo={},gc;function vw(){if(gc)return uo;gc=1;const e=fu();function t(i,o){const s=i.a/255,a=o+'="'+i.hex+'"';return s<1?a+" "+o+'-opacity="'+s.toFixed(2).slice(1)+'"':a}function r(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function n(i,o,s){let a="",c=0,d=!1,u=0;for(let f=0;f<i.length;f++){const l=Math.floor(f%o),h=Math.floor(f/o);!l&&!d&&(d=!0),i[f]?(u++,f>0&&l>0&&i[f-1]||(a+=d?r("M",l+s,.5+h+s):r("m",c,0),c=0,d=!1),l+1<o&&i[f+1]||(a+=r("h",u),u=0)):c++}return a}return uo.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,u=o.modules.data,f=d+c.margin*2,l=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(c.color.dark,"stroke")+' d="'+n(u,d,c.margin)+'"/>',w='viewBox="0 0 '+f+" "+f+'"',T='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+w+' shape-rendering="crispEdges">'+l+h+`</svg>
12
+ `;return typeof a=="function"&&a(null,T),T},uo}var pc;function Lw(){if(pc)return bt;pc=1;const e=lw(),t=bw(),r=Ow(),n=vw();function i(o,s,a,c,d){const u=[].slice.call(arguments,1),f=u.length,l=typeof u[f-1]=="function";if(!l&&!e())throw new Error("Callback required as last argument");if(l){if(f<2)throw new Error("Too few arguments provided");f===2?(d=a,a=s,s=c=void 0):f===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=s,s=c=void 0):f===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(h,w){try{const A=t.create(a,c);h(o(A,s,c))}catch(A){w(A)}})}try{const h=t.create(a,c);d(null,o(h,s,c))}catch(h){d(h)}}return bt.create=t.create,bt.toCanvas=i.bind(null,r.render),bt.toDataURL=i.bind(null,r.renderToDataURL),bt.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),bt}var Cw=Lw();const Rw="/__hb_sdk__/dev-context";function yc(e,t){return br(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId: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:br(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 dr(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Bc(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:Sl({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 Pw(e){if(!br(e)||!Ec(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!br(t)||!Ec(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const kw={networkRequest:{status:"disabled",useOfficialDomain:!1}};function yi(e){const t=Oe(e.localDevGrant?Qo({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}}:Uw()}function xw(e,t,r){return r?.localDevGrant?Qo({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:hu(e,t,t.networkRequest.useOfficialDomain)}function jw(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=yi({...e,localDevGrant:void 0});return hu(e.runtimePermissions,t,!1)}function Uw(){return{networkRequest:{...kw.networkRequest}}}function hu(e,t,r){const n=Oe(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of Dr){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=br(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 br(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Ec(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function zw(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 Hw(e){return zw({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 Fw(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 Vw={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};function Bw(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=`
13
13
  <div class="hb-sdk-auth-dialog__panel">
14
14
  <h2>授权请求</h2>
15
15
  <p class="hb-sdk-auth-dialog__app">${lo(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
@@ -92,11 +92,11 @@ Minimum version required to store current data is: `+_+`.
92
92
  `,document.head.appendChild(e)}const Kw=44;function Jw(e){const t=()=>e.isCapsuleHidden?.()?0:Kw;return{...e.applyDisplay?{applyOrientation:async(r,n)=>(await e.applyDisplay(r,n.signal),{supported:!0})}:{},...e.onViewportChange?{onViewportChange:e.onViewportChange}:{},close:async()=>{await e.close()},reload:async()=>{await e.reload()},getViewportMetrics:()=>{const r=e.getDeviceMetrics?.();return r?{windowWidth:r.screenWidth,windowHeight:r.screenHeight,screenWidth:r.screenWidth,screenHeight:r.screenHeight,pixelRatio:r.pixelRatio,safeArea:{top:r.safeAreaInsets.top+t(),right:r.screenWidth-r.safeAreaInsets.right,bottom:r.screenHeight-r.safeAreaInsets.bottom,left:r.safeAreaInsets.left}}:{windowWidth:window.innerWidth,windowHeight:window.innerHeight,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}},getNavigationBarHeight:()=>{const r=e.getDeviceMetrics?.().statusBarHeight;return r===void 0?0:r+t()},setNavigationBarStyle:r=>{document.documentElement.dataset.navigationBarStyle=r,e.onNavigationBarStyleChange?.(r)},setClipboard:async({text:r})=>{await navigator.clipboard.writeText(r)},showToast:async({message:r,status:n})=>{e.pushLog("host.message",{message:r,status:n}),await Hu({message:r,status:n})},showLoading:zu,hideLoading:Uu,vibrate:ju,openAppPage:Qw,openWindow:Yw,showShareMenu:qw,captureAndShare:$w,setScreenshotChromeHidden:xu}}const Ac=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],Jr=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Mc={"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 Zw{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]:[...Ac];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:Mc[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:Jr[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:Jr[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),Jr.forEach((u,f)=>{const l=this.schedule(()=>{if(c.timers.delete(l),!c.cancelled){d.status={state:"preparing",progress:u};try{c.listeners.forEach(h=>h(u))}catch(h){c.cancelled=!0;for(const w of c.timers)this.clearSchedule(w);d.operation=void 0,d.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",n,{message:h instanceof Error?h.message:String(h)}),c.reject(h);return}if(this.diagnostic("prepare.progress",n,{phase:u.phase}),f===Jr.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(ul,{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:Mc[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
93
93
  `),this.queueOutput(o,"stderr",1,`fake:diagnostic
94
94
  `)},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
95
- `);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(cl,{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(dl,{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(!Ac.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 Xw=Object.freeze({[ri]:!0,[ni]:!0,[ii]:!0,[oi]:!0,[si]:!0,[ai]:!0,[ci]:!0,[di]:!0,[ui]:!0,[li]:!0,[fi]:!0,[hi]:!0,[Ir]:!0,[wr]:!0,[Ar]:!0});function eI(e){return new Zw(e)}function he(e,t){return Object.assign(new Error(t),{code:e})}const tI=/^[A-Za-z0-9_-]{22}$/,rI="https://api.xiaoheihe.cn/open_inapp/";function nI(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(!tI.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 iI(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`${rI}#${r}`}function oI(e){const t=Oe(e.runtimePermissions),r=Qo({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=Oe(e.publishedRuntimePermissions),o=Oe(r.runtimePermissions);for(const s of Vc){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 dt(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 sI="__hb_sdk_mini_dev__",aI="hb-sdk:mini-dev-console",cI="__hb_sdk_mini_dev_console_installed__",Nc=cI;function dI(e,t=console){lI(t,e,t)}const uI=["log","debug","info","warn","error"];function lI(e,t,r){if(!r||r[Nc]===!0)return!1;let n=!1;for(const i of uI){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[Nc]=!0),n}const Oo=1,Dc=64*1024,fI=64,hI=/^[A-Za-z0-9_-]{22}$/;class we extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function mI(e,t=!1){const r=pI(e,t);switch(vo(r,"Server message"),yI(r),r.type){case"grant":return ur(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),lr(r.connectionEpoch,"connectionEpoch"),ut(r.nextClientSequence,"nextClientSequence"),ut(r.nextServerSequence,"nextServerSequence"),Sc(r.snapshot),r;case"event":return ur(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),lr(r.connectionEpoch,"connectionEpoch"),ut(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&rt("event must be account.changed or status.changed"),Sc(r.snapshot),r;case"heartbeat":return ur(r,["version","type","connectionEpoch","sequence"],"heartbeat"),lr(r.connectionEpoch,"connectionEpoch"),ut(r.sequence,"sequence"),r;default:return rt("Unknown server message type")}}function gI(e){const t=e.connectionEpoch;lr(t,"connectionEpoch"),ut(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(lr(n.connectionEpoch,"connectionEpoch"),ut(n.sequence,"sequence"),n.connectionEpoch!==t)throw new we("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new we("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new we("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function pI(e,t){if(t)throw new we("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new we("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Dc)throw new we("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Dc)throw new we("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return EI(e),JSON.parse(e)}catch(r){throw r instanceof we?r:new we("INVALID_JSON","Channel frame must contain strict JSON")}}function Sc(e){vo(e,"snapshot"),ur(e,["account","permissions"],"snapshot"),vo(e.account,"snapshot.account"),ur(e.account,["revision"],"snapshot.account"),ut(e.account.revision,"snapshot.account.revision"),Pw(e.permissions)||rt("snapshot.permissions is invalid")}function yI(e){e.version!==Oo&&rt("version must be 1")}function vo(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&rt(`${t} must be a plain JSON object`)}function ur(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)))&&rt(`${r} fields are invalid`)}function ut(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&rt(`${t} must be a non-negative safe integer`)}function lr(e,t){(typeof e!="string"||!hI.test(e))&&rt(`${t} must be a 22-character base64url value`)}function rt(e){throw new we("INVALID_MESSAGE",e)}function EI(e){new wI(e).scan()}class wI{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>=fI)throw new we("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 we("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 Tc=[1e3,2e3,4e3,8e3,15e3];function II(e){const t=new Set,r=e.webSocketFactory??(y=>new WebSocket(y)),n=e.randomValues??(y=>crypto.getRandomValues(y)),i=e.timers??{clearTimeout:y=>window.clearTimeout(y),setTimeout:(y,_)=>window.setTimeout(y,_)},o=e.onlineTarget??(typeof window>"u"?void 0:window),s=e.visibilityTarget??(typeof document>"u"?void 0:document),a=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let c,d,u,f=!1,l=0,h,w=!1,A=!1;const T=new Set,M=(y,_)=>{if(!(!e.onDiagnostic||T.has(y))){T.add(y);try{e.onDiagnostic({phase:y,..._?{code:_}:{}})}catch{}}},b=(y,_,g=!1)=>{if(u&&y.account.revision<u.account.revision)return;const D=u&&JSON.stringify(y)===JSON.stringify(u);if(u=y,!(D&&!g))for(const v of t)v(y,_)},S=()=>{if(f||h!==void 0||c)return;const y=Tc[Math.min(l,Tc.length-1)];l+=1,h=i.setTimeout(()=>{h=void 0,I()},y)},R=()=>{f||!w||c||(h!==void 0&&(i.clearTimeout(h),h=void 0),I())},B=()=>{a()&&R()},U=()=>{s&&!s.hidden&&R()},p=()=>{A||(A=!0,o?.addEventListener("online",B),s?.addEventListener("visibilitychange",U))},m=()=>{A&&(A=!1,o?.removeEventListener("online",B),s?.removeEventListener("visibilitychange",U))},I=()=>{if(f||c)return;w=!0,p(),h!==void 0&&(i.clearTimeout(h),h=void 0);let y,_;try{y=r(e.url)}catch{M("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),S();return}try{_=MI(n)}catch{M("entropy","NONCE_GENERATION_FAILED");try{y?.close(1011,"channel initialization failed")}catch{}S();return}c=y;let g,D,v;const k=()=>{y.removeEventListener("open",C),y.removeEventListener("message",N),y.removeEventListener("close",O),y.removeEventListener("error",L),d===k&&(d=void 0)},x=()=>{if(c===y){c=void 0,k();try{y.close(1008,"invalid channel state")}catch{}S()}},C=()=>{if(!(f||c!==y))try{y.send(JSON.stringify({version:Oo,type:"hello",csrfToken:e.csrfToken,clientNonce:_}))}catch{M("send","HELLO_SEND_FAILED"),x()}},N=P=>{if(f||c!==y)return;if(typeof P.data!="string"){M("parse","TEXT_FRAME_REQUIRED"),x();return}let z;try{z=mI(P.data)}catch(H){M("parse",H instanceof we?H.code:"INVALID_MESSAGE"),x();return}if(z.type==="grant"){if(v){M("sequence","DUPLICATE_GRANT"),x();return}g=z.connectionEpoch,D=z.nextClientSequence,v=gI({connectionEpoch:g,nextSequence:z.nextServerSequence}),l=0,T.clear(),b(z.snapshot,{type:"grant"});return}if(!v||!g||D===void 0){M("sequence","MESSAGE_BEFORE_GRANT"),x();return}try{v.accept(z)}catch{M("sequence","INVALID_SEQUENCE"),x();return}if(z.type==="heartbeat"){try{y.send(JSON.stringify({version:Oo,type:"heartbeat.ack",connectionEpoch:g,sequence:D}))}catch{M("send","HEARTBEAT_ACK_SEND_FAILED"),x()}D=D===Number.MAX_SAFE_INTEGER?void 0:D+1;return}b(z.snapshot,{type:"event",event:z.event},!0)},O=()=>{c===y&&(M("close","SOCKET_CLOSED"),c=void 0,k(),S())},L=()=>{M("open","SOCKET_ERROR"),x()};y.addEventListener("open",C),y.addEventListener("message",N),y.addEventListener("close",O),y.addEventListener("error",L),d=k};return{connect:I,subscribeUpdates(y){return t.add(y),()=>t.delete(y)},dispose(){if(f)return;f=!0,w=!1,m(),h!==void 0&&i.clearTimeout(h),h=void 0;const y=c;c=void 0,d?.(),y?.close(1e3,"client disposed"),t.clear()}}}function AI(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 MI(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=AI(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}try{dI((e,t)=>{Rr(`console.${e}`,{source:"host",message:t.map(r=>wu(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const NI="/__hb_sdk_bootstrap__",DI="/__hb_sdk__/mobile-launch-redirect",SI="/__hb_sdk__/network",TI="/session/status",_I="/session/request",bI="/session/events",OI=320,vI=1e3,CI=1e3,LI=15e3,_c="dark",mu=new URL(location.href).searchParams,gu=mu.get("mini_url"),Et=mu.get("ui_preview")==="1",re={device:rr("#device"),get mobileLanSelect(){return rr("#mobile-lan-select")},get mobileQrImage(){return rr("#mobile-qr-image")},get mobileQrStatus(){return rr("#mobile-qr-status")},storageSnapshot:rr("#storage-snapshot")};if(!gu&&!Et)throw re.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const pu=gu??"about:blank",se=await ls();Z.openPlatformBaseUrl=se.openPlatformBaseUrl;Z.devReadiness=se.devReadiness;Z.miniProgramSupportsDesktop=se.miniProgramSupportsDesktop;Z.desktopLaunch.workspaceCardsEnabled=se.workspaceCardsEnabled;let Ye=se.lanAddresses,an=se.defaultLanAddressId,vt=se.mobileLaunchRedirect,ds=se.nativeAppLaunchUnavailableReason,fr=se.devSessionId,Co=se.miniProgramManifestAccessToken,cn=se.workspaceCardsEnabled,dn=se,us=Ai(se),_e=se.devContext,Rt=se.browserDevContext,ge=dr(Rt);ti();let Gt=yi(ge),ne=!1,wi=0;const Ii=new AbortController;let Fe=0,Pt,Or,un=0,et,Lo,Ro,qe=0,tt=!1,ln,Po,fo=!1;const hr=Wu({apply:Ku,waitForLayout:async e=>{await Ju(),await Zu(e),await Xu(e)}});let ko,xo,bc=Date.now(),sr=!1,Oc=Promise.resolve(),mr=-1,vr=!1,ft,jo,Uo,fn,at;const ei=new Set,zo=eI({onDiagnostic:({action:e,alias:t,detail:r})=>De(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Qt=Hw({applyStatus:e=>Du(e,!0),fetchStatus:e=>Nu(Cu(Ii.signal,e)),getCanonicalRevision:()=>mr,onError:iA,reconcile:()=>GI(wi)}),Ho=Fw({connectEvents:Su,invalidate:()=>Qt.invalidate(),isDisposed:()=>ne,maxDelayMs:LI,minDelayMs:CI,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let ho=0,ar="",mo=!1,Fo;await Vo(!1);bu();vu(Ou(se));Et&&xI();Mi();Et||await Eu();await Ur("initial");Et||(Su(),VI());RI();qI();function yu(){!Et&&!ne&&(Fo=window.setTimeout(()=>{Eu().finally(yu)},1e3))}yu();async function Eu(){if(!(mo||ne)){mo=!0;try{const e=await fetch(`/__hb_sdk__/device-logs?after=${ho}&limit=500`,{signal:AbortSignal.any([Ii.signal,AbortSignal.timeout(5e3)])});if(!e.ok)return;const t=await e.json();if(ne)return;if(ar&&t.epoch!==ar){ho=0,ar=t.epoch;return}ar=t.epoch,Z.logDevices=t.devices,t.gap&&Rr("console.warn",{message:"部分设备日志已超出服务器缓冲,存在日志缺口"});for(const r of t.items){const n=Fu(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,vc(n)}ho=t.nextCursor}catch{}finally{mo=!1}}}function RI(){window.addEventListener("beforeunload",oA),window.addEventListener("hb-sdk:restart-runtime",Au),window.addEventListener("hb-sdk:refresh-storage",Mi),window.addEventListener("hb-sdk:qr-open-change",Iu),window.addEventListener("message",PI),ko=Vu(()=>document.querySelector("#host-fullscreen-exit-mount")),xo=Bu(()=>Z.devicePresetId,()=>hr.notifyViewportChange(),{flush:"post"})}function PI(e){const t=e.data;if(e.source===null||!Ie(t)||t.type!==aI||!Ie(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)||Rr(`console.${r.level}`,{source:"app",message:r.args.map(n=>wu(n)).join(" ")},r.timestamp,r.level==="log"||r.level==="debug"?"log":r.level)}function wu(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
95
+ `);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(cl,{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(dl,{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(!Ac.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 Xw=Object.freeze({[ri]:!0,[ni]:!0,[ii]:!0,[oi]:!0,[si]:!0,[ai]:!0,[ci]:!0,[di]:!0,[ui]:!0,[li]:!0,[fi]:!0,[hi]:!0,[Ir]:!0,[wr]:!0,[Ar]:!0});function eI(e){return new Zw(e)}function he(e,t){return Object.assign(new Error(t),{code:e})}const tI=/^[A-Za-z0-9_-]{22}$/,rI="https://api.xiaoheihe.cn/open_inapp/";function nI(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(!tI.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 iI(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`${rI}#${r}`}function oI(e){const t=Oe(e.runtimePermissions),r=Qo({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=Oe(e.publishedRuntimePermissions),o=Oe(r.runtimePermissions);for(const s of Vc){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 dt(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 sI="__hb_sdk_mini_dev__",aI="hb-sdk:mini-dev-console",cI="__hb_sdk_mini_dev_console_installed__",Nc=cI;function dI(e,t=console){lI(t,e,t)}const uI=["log","debug","info","warn","error"];function lI(e,t,r){if(!r||r[Nc]===!0)return!1;let n=!1;for(const i of uI){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[Nc]=!0),n}const Oo=1,Dc=64*1024,fI=64,hI=/^[A-Za-z0-9_-]{22}$/;class we extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function mI(e,t=!1){const r=pI(e,t);switch(vo(r,"Server message"),yI(r),r.type){case"grant":return ur(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),lr(r.connectionEpoch,"connectionEpoch"),ut(r.nextClientSequence,"nextClientSequence"),ut(r.nextServerSequence,"nextServerSequence"),Sc(r.snapshot),r;case"event":return ur(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),lr(r.connectionEpoch,"connectionEpoch"),ut(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&rt("event must be account.changed or status.changed"),Sc(r.snapshot),r;case"heartbeat":return ur(r,["version","type","connectionEpoch","sequence"],"heartbeat"),lr(r.connectionEpoch,"connectionEpoch"),ut(r.sequence,"sequence"),r;default:return rt("Unknown server message type")}}function gI(e){const t=e.connectionEpoch;lr(t,"connectionEpoch"),ut(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(lr(n.connectionEpoch,"connectionEpoch"),ut(n.sequence,"sequence"),n.connectionEpoch!==t)throw new we("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new we("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new we("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function pI(e,t){if(t)throw new we("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new we("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Dc)throw new we("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Dc)throw new we("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return EI(e),JSON.parse(e)}catch(r){throw r instanceof we?r:new we("INVALID_JSON","Channel frame must contain strict JSON")}}function Sc(e){vo(e,"snapshot"),ur(e,["account","permissions"],"snapshot"),vo(e.account,"snapshot.account"),ur(e.account,["revision"],"snapshot.account"),ut(e.account.revision,"snapshot.account.revision"),Pw(e.permissions)||rt("snapshot.permissions is invalid")}function yI(e){e.version!==Oo&&rt("version must be 1")}function vo(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&rt(`${t} must be a plain JSON object`)}function ur(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)))&&rt(`${r} fields are invalid`)}function ut(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&rt(`${t} must be a non-negative safe integer`)}function lr(e,t){(typeof e!="string"||!hI.test(e))&&rt(`${t} must be a 22-character base64url value`)}function rt(e){throw new we("INVALID_MESSAGE",e)}function EI(e){new wI(e).scan()}class wI{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>=fI)throw new we("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 we("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 Tc=[1e3,2e3,4e3,8e3,15e3];function II(e){const t=new Set,r=e.webSocketFactory??(y=>new WebSocket(y)),n=e.randomValues??(y=>crypto.getRandomValues(y)),i=e.timers??{clearTimeout:y=>window.clearTimeout(y),setTimeout:(y,_)=>window.setTimeout(y,_)},o=e.onlineTarget??(typeof window>"u"?void 0:window),s=e.visibilityTarget??(typeof document>"u"?void 0:document),a=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let c,d,u,f=!1,l=0,h,w=!1,A=!1;const T=new Set,M=(y,_)=>{if(!(!e.onDiagnostic||T.has(y))){T.add(y);try{e.onDiagnostic({phase:y,..._?{code:_}:{}})}catch{}}},b=(y,_,m=!1)=>{if(u&&y.account.revision<u.account.revision)return;const D=u&&JSON.stringify(y)===JSON.stringify(u);if(u=y,!(D&&!m))for(const v of t)v(y,_)},S=()=>{if(f||h!==void 0||c)return;const y=Tc[Math.min(l,Tc.length-1)];l+=1,h=i.setTimeout(()=>{h=void 0,I()},y)},R=()=>{f||!w||c||(h!==void 0&&(i.clearTimeout(h),h=void 0),I())},B=()=>{a()&&R()},U=()=>{s&&!s.hidden&&R()},p=()=>{A||(A=!0,o?.addEventListener("online",B),s?.addEventListener("visibilitychange",U))},g=()=>{A&&(A=!1,o?.removeEventListener("online",B),s?.removeEventListener("visibilitychange",U))},I=()=>{if(f||c)return;w=!0,p(),h!==void 0&&(i.clearTimeout(h),h=void 0);let y,_;try{y=r(e.url)}catch{M("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),S();return}try{_=MI(n)}catch{M("entropy","NONCE_GENERATION_FAILED");try{y?.close(1011,"channel initialization failed")}catch{}S();return}c=y;let m,D,v;const k=()=>{y.removeEventListener("open",L),y.removeEventListener("message",N),y.removeEventListener("close",O),y.removeEventListener("error",C),d===k&&(d=void 0)},x=()=>{if(c===y){c=void 0,k();try{y.close(1008,"invalid channel state")}catch{}S()}},L=()=>{if(!(f||c!==y))try{y.send(JSON.stringify({version:Oo,type:"hello",csrfToken:e.csrfToken,clientNonce:_}))}catch{M("send","HELLO_SEND_FAILED"),x()}},N=P=>{if(f||c!==y)return;if(typeof P.data!="string"){M("parse","TEXT_FRAME_REQUIRED"),x();return}let z;try{z=mI(P.data)}catch(H){M("parse",H instanceof we?H.code:"INVALID_MESSAGE"),x();return}if(z.type==="grant"){if(v){M("sequence","DUPLICATE_GRANT"),x();return}m=z.connectionEpoch,D=z.nextClientSequence,v=gI({connectionEpoch:m,nextSequence:z.nextServerSequence}),l=0,T.clear(),b(z.snapshot,{type:"grant"});return}if(!v||!m||D===void 0){M("sequence","MESSAGE_BEFORE_GRANT"),x();return}try{v.accept(z)}catch{M("sequence","INVALID_SEQUENCE"),x();return}if(z.type==="heartbeat"){try{y.send(JSON.stringify({version:Oo,type:"heartbeat.ack",connectionEpoch:m,sequence:D}))}catch{M("send","HEARTBEAT_ACK_SEND_FAILED"),x()}D=D===Number.MAX_SAFE_INTEGER?void 0:D+1;return}b(z.snapshot,{type:"event",event:z.event},!0)},O=()=>{c===y&&(M("close","SOCKET_CLOSED"),c=void 0,k(),S())},C=()=>{M("open","SOCKET_ERROR"),x()};y.addEventListener("open",L),y.addEventListener("message",N),y.addEventListener("close",O),y.addEventListener("error",C),d=k};return{connect:I,subscribeUpdates(y){return t.add(y),()=>t.delete(y)},dispose(){if(f)return;f=!0,w=!1,g(),h!==void 0&&i.clearTimeout(h),h=void 0;const y=c;c=void 0,d?.(),y?.close(1e3,"client disposed"),t.clear()}}}function AI(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 MI(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=AI(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}try{dI((e,t)=>{Rr(`console.${e}`,{source:"host",message:t.map(r=>wu(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const NI="/__hb_sdk_bootstrap__",DI="/__hb_sdk__/mobile-launch-redirect",SI="/__hb_sdk__/network",TI="/session/status",_I="/session/request",bI="/session/events",OI=320,vI=1e3,LI=1e3,CI=15e3,_c="dark",mu=new URL(location.href).searchParams,gu=mu.get("mini_url"),Et=mu.get("ui_preview")==="1",re={device:rr("#device"),get mobileLanSelect(){return rr("#mobile-lan-select")},get mobileQrImage(){return rr("#mobile-qr-image")},get mobileQrStatus(){return rr("#mobile-qr-status")},storageSnapshot:rr("#storage-snapshot")};if(!gu&&!Et)throw re.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const pu=gu??"about:blank",se=await ls();Z.openPlatformBaseUrl=se.openPlatformBaseUrl;Z.devReadiness=se.devReadiness;Z.miniProgramSupportsDesktop=se.miniProgramSupportsDesktop;Z.desktopLaunch.workspaceCardsEnabled=se.workspaceCardsEnabled;let Ye=se.lanAddresses,an=se.defaultLanAddressId,vt=se.mobileLaunchRedirect,ds=se.nativeAppLaunchUnavailableReason,fr=se.devSessionId,Lo=se.miniProgramManifestAccessToken,cn=se.workspaceCardsEnabled,dn=se,us=Ai(se),_e=se.devContext,Rt=se.browserDevContext,ge=dr(Rt);ti();let Gt=yi(ge),ie=!1,wi=0;const Ii=new AbortController;let Fe=0,Pt,Or,un=0,et,Co,Ro,qe=0,tt=!1,ln,Po,fo=!1;const hr=Wu({apply:Ku,waitForLayout:async e=>{await Ju(),await Zu(e),await Xu(e)}});let ko,xo,bc=Date.now(),sr=!1,Oc=Promise.resolve(),mr=-1,vr=!1,ft,jo,Uo,fn,at;const ei=new Set,zo=eI({onDiagnostic:({action:e,alias:t,detail:r})=>De(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Qt=Hw({applyStatus:e=>Du(e,!0),fetchStatus:e=>Nu(Lu(Ii.signal,e)),getCanonicalRevision:()=>mr,onError:iA,reconcile:()=>GI(wi)}),Ho=Fw({connectEvents:Su,invalidate:()=>Qt.invalidate(),isDisposed:()=>ie,maxDelayMs:CI,minDelayMs:LI,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let ho=0,ar="",mo=!1,Fo;await Vo(!1);bu();vu(Ou(se));Et&&xI();Mi();Et||await Eu();await Ur("initial");Et||(Su(),VI());RI();qI();function yu(){!Et&&!ie&&(Fo=window.setTimeout(()=>{Eu().finally(yu)},1e3))}yu();async function Eu(){if(!(mo||ie)){mo=!0;try{const e=await fetch(`/__hb_sdk__/device-logs?after=${ho}&limit=500`,{signal:AbortSignal.any([Ii.signal,AbortSignal.timeout(5e3)])});if(!e.ok)return;const t=await e.json();if(ie)return;if(ar&&t.epoch!==ar){ho=0,ar=t.epoch;return}ar=t.epoch,Z.logDevices=t.devices,t.gap&&Rr("console.warn",{message:"部分设备日志已超出服务器缓冲,存在日志缺口"});for(const r of t.items){const n=Fu(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,vc(n)}ho=t.nextCursor}catch{}finally{mo=!1}}}function RI(){window.addEventListener("beforeunload",oA),window.addEventListener("hb-sdk:restart-runtime",Au),window.addEventListener("hb-sdk:refresh-storage",Mi),window.addEventListener("hb-sdk:qr-open-change",Iu),window.addEventListener("message",PI),ko=Vu(()=>document.querySelector("#host-fullscreen-exit-mount")),xo=Bu(()=>Z.devicePresetId,()=>hr.notifyViewportChange(),{flush:"post"})}function PI(e){const t=e.data;if(e.source===null||!Ie(t)||t.type!==aI||!Ie(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)||Rr(`console.${r.level}`,{source:"app",message:r.args.map(n=>wu(n)).join(" ")},r.timestamp,r.level==="log"||r.level==="debug"?"log":r.level)}function wu(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
96
96
  `).slice(0,4).join(`
97
- `):"")||`${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 Iu(e){const t=e.detail?.open===!0;t!==tt&&(tt=t,qe+=1,Ni(),t&&(re.mobileLanSelect.addEventListener("change",kI),Tu(),zr()))}function kI(){tt&&zr()}function Au(){Cr("manual restart")}function Cr(e){ne||Pt!==void 0||(De("runtime.restart",{boundary:Fe+1}),Pt=window.setTimeout(()=>{Pt=void 0,ne||Ur(e)},0))}async function Ur(e){if(sr)return;const t=++Fe;if(Or=void 0,Lr(e),Mu(),Z.runtimeStatus="loading",Pu(Gt),re.device.replaceChildren(),Et){re.device.innerHTML=`
97
+ `):"")||`${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 Iu(e){const t=e.detail?.open===!0;t!==tt&&(tt=t,qe+=1,Ni(),t&&(re.mobileLanSelect.addEventListener("change",kI),Tu(),zr()))}function kI(){tt&&zr()}function Au(){Lr("manual restart")}function Lr(e){ie||Pt!==void 0||(De("runtime.restart",{boundary:Fe+1}),Pt=window.setTimeout(()=>{Pt=void 0,ie||Ur(e)},0))}async function Ur(e){if(sr)return;const t=++Fe;if(Or=void 0,Cr(e),Mu(),Z.runtimeStatus="loading",Pu(Gt),re.device.replaceChildren(),Et){re.device.innerHTML=`
98
98
  <div class="browser-mock-preview">
99
99
  <span class="browser-mock-preview__icon">UI</span>
100
100
  <strong>Browser Mock</strong>
101
101
  <small>mp_preview</small>
102
- </div>`,Z.runtimeStatus="idle";return}const r=document.createElement("iframe");r.dataset.testid="device-iframe",r.title="小程序预览",r.allow="clipboard-read; clipboard-write",r.name=sI,re.device.appendChild(r);const n=new AbortController;Lo=n;let i=!1;try{const o=await dw(jI(n.signal,t));if(ne||t!==Fe){o.dispose();return}Ro=o.dispose,o.ports.companion=zo.port,o.ports.media=Gu({getMode:()=>Z.mediaSimulation,signal:n.signal});const s=QE({iframe:r,ports:o.ports,environment:o.environment,hostCapabilities:{...o.hostCapabilities,"media.pick":!0,...Xw},authPresentation:o.authPresentation,companionPresentation:zo.presentation,resolveLaunchConfiguration:async()=>(await o.resolveLaunch()).configuration,dispose:o.dispose,onReady:()=>{Z.runtimeStatus="ready",De("runtime.ready",{generation:t})},onTrace:a=>HI(t,a),onError:()=>{i=!0,Z.runtimeStatus="error"},onCapabilityTrace:a=>{ar||De(a.method,a),a.method==="storage.setStorage"&&a.outcome==="success"&&Mi()}});et=s,await s.start()}catch(o){if(ne||t!==Fe||n.signal.aborted)return;Z.runtimeStatus="error",i||De("runtime.start.failed",Qu(o))}}function xI(){De("runtime.ready",{generation:1}),Rr("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info"),De("user.getInfo",{durationMs:34,outcome:"success"}),De("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function jI(e,t){const r=ge,n=fr,i=xw(r.runtimePermissions,Gt,r);return{signal:e,account:{async getCurrentUserId(){return(await Vo(!1,e)).user_id},async ensureAuthenticated({signal:o}){await Vo(!1,o)},onChange(o){return ei.add(o),()=>ei.delete(o)}},authenticatedRequest:FI,storage:{area:"local",storage:localStorage},presentation:Jw({close:async()=>{Lc(),et?.destroy(),hr.reset(),Mu(),Z.runtimeStatus="closed"},reload:()=>{!ne&&t===Fe&&(Or=t)},onNavigationBarStyleChange:Cc,pushLog:De,getDeviceMetrics:()=>el.value,applyDisplay:(o,s)=>hr.applyDisplay(o,s),isCapsuleHidden:()=>Z.display.capsuleHidden,onViewportChange:o=>hr.onViewportChange(o)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:o=>{document.title=o}},resolveLaunch:async()=>({configuration:Gw({launchUrl:pu,runtimePermissions:i,...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:Yu.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:o=>Bw(o)},protocol:UI()}}function UI(){return{async invoke(e){De("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:zI(e)})}}}function zI(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 Ie(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function Mu(){document.documentElement.dataset.navigationBarStyle=_c,Cc(_c)}function HI(e,t){const r=qu(t,e);r&&vc(r),!(t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||Or!==e||e!==Fe)&&(Or=void 0,Cr("navigation.reload"))}async function FI(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 fs(n?SI:_I,{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&&Qt.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function Vo(e,t){const r=wi,n=await Nu(Cu(Ii.signal,t));return Lu(r)?Du(n,e).status:Bo()}async function Nu(e){return await(await fetch(TI,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Du(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<mr)return{changed:!1,status:Bo()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?de(e.nickname):void 0,i=e.authenticated?de(e.avatar):void 0,o=e.revision!==mr||e.authenticated!==vr||r!==ft||n!==jo||i!==Uo;return mr=e.revision,vr=e.authenticated,ft=r,jo=n,Uo=i,bu(),t&&o&&ei.forEach(s=>s(ft)),{changed:o,status:Bo()}}function Bo(){return{authenticated:vr,revision:mr,...vr&&ft?{user_id:ft}:{}}}function VI(){if(!(!se.csrfToken||ne))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",at=II({csrfToken:se.csrfToken,onDiagnostic:t=>De("channel.diagnostic",t),url:e.toString()}),at.subscribeUpdates((t,r)=>BI(t,r)),at.connect()}catch{at?.dispose(),at=void 0}}function BI(e,t){Qt.invalidate(e.account.revision),cA(Gt,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Ur("status changed"):(Gt=Pu(e.permissions),QI())}function Su(){if(fn?.close(),fn=void 0,!ft||ne)return;const e=new EventSource(bI);fn=e,e.addEventListener("account-invalidated",()=>{Qt.invalidate()}),e.addEventListener("account-revision",()=>{Qt.invalidate()}),e.onopen=()=>{Ho.reset()},e.onerror=()=>{e.close(),Ho.schedule()}}async function GI(e){Lu(e)&&await Ur("account revision changed")}function Lr(e){un+=1,Lc(),et&&zo.reset(),et?.destroy(),et=void 0,Lo?.abort(new DOMException(e,"AbortError")),Lo=void 0,Ro?.(),Ro=void 0,hr.reset()}async function QI(){ne||(await Ur("permission changed"),!ne&&await zr())}async function ls(){const e=await fetch(NI,{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(!Ie(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Ru(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new Yt;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:YI(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:yc(t.devContext,t.runtimePermissions),browserDevContext:yc(t.browserDevContext??t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(aA):[],loginAvailable:t.loginAvailable===!0,miniProgram:rA(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}}function YI(e){if(!Ie(e))return;const t=s=>{if(!(!Ie(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||!Ie(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=>Ie(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 fs(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),se.csrfToken&&r.set("x-hb-sdk-csrf",se.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function qI(){hs(),Et||(Po=window.setInterval(()=>{tA()},vI))}function Tu(e=re.mobileLanSelect.options.length>0?re.mobileLanSelect.value:void 0){re.mobileLanSelect.replaceChildren();for(const t of Ye){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,re.mobileLanSelect.appendChild(r)}e&&Ye.some(({id:t})=>t===e)?re.mobileLanSelect.value=e:an&&Ye.some(({id:t})=>t===an)?re.mobileLanSelect.value=an:Ye[0]&&(re.mobileLanSelect.value=Ye[0].id),re.mobileLanSelect.disabled=Ye.length===0}async function zr(){if(ne)return;const e=++qe;if(Ni(),_e.source!=="remote"||!_e.localDevLaunchToken||_e.expiresAt!==void 0&&_e.expiresAt<=Date.now()){re.mobileQrImage.removeAttribute("src"),re.mobileQrStatus.textContent=ds||"需要有效的本地调试启动票";return}const t=sA();if(!t?.mobileAppQrPayload){re.mobileQrImage.removeAttribute("src"),re.mobileQrStatus.textContent="未发现可用的局域网地址";return}re.mobileQrStatus.textContent="正在生成二维码...";try{const r=await ZI(t);if(e!==qe||ne)return;const n=await $I(r.address,r.expiresAt);if(e!==qe||ne)return;const i=await Lw.toDataURL(n.payload,{width:OI,margin:1});if(e!==qe||ne)return;re.mobileQrImage.src=i,re.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,eA(n.expiresAt,e)}catch(r){if(e!==qe||ne)return;if(r instanceof Yt){hn();return}re.mobileQrImage.removeAttribute("src"),re.mobileQrStatus.textContent=ms(r)}}async function $I(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await WI(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:iI(nI({host:e.address,port:location.port,token:n.token}))}}catch{throw new Yt}}async function WI(e,t){if(vt?.addressId===e.id)return vt;if(!vt)return;const r=await fs(DI,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:vt.token})});if(!r.ok)throw new Yt;const n=await r.json(),i=Ie(n)?Ru({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new Yt;return vt=i,dn={...dn,mobileLaunchRedirect:i},us=Ai(dn),i}async function KI(e){const t=await ls(),r=JI(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return _u(t),{...r,mobileAppQrPayload:n}}function JI(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function _u(e){const t=dt(ge);Z.devReadiness=e.devReadiness,Z.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,cn=e.workspaceCardsEnabled,dn=e,us=Ai(e),_e=e.devContext,Rt=e.browserDevContext,ge=dr(Rt),Gt=yi(ge),ti(),Ye=e.lanAddresses,an=e.defaultLanAddressId,vt=e.mobileLaunchRedirect,ds=e.nativeAppLaunchUnavailableReason,fr=e.devSessionId,Co=e.miniProgramManifestAccessToken,vu(Ou(e)),tt&&Tu(),hs(),t!==dt(ge)&&(Fe+=1,Lr("local permission context changed"),Cr("local permission context changed"))}function ti(){Z.localPermissions=oI(ge),Z.devContextWarning=ge.source==="anonymous"?"未连接线上上下文":ge.warning?"本地上下文受限,请检查 CLI 状态":""}function hs(){let e;try{e=$u(pu)}catch{}const t=_e.miniProgramId?.trim().toLowerCase();let r=ds?.trim()??"";!r&&(_e.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!_e.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&cn&&!fr&&(r="本地调试会话尚未就绪"),!r&&_e.expiresAt!==void 0&&_e.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),Rc({...e?{address:e}:{},...t?{miniProgramId:t}:{},...cn&&fr?{devSessionId:fr}:{},...Co?{miniProgramManifestToken:Co}:{},workspaceCardsEnabled:cn,ready:r==="",...r?{unavailableReason:r}:{}})}class Yt extends Error{}async function ZI(e){const t=Oc.then(()=>XI(e));return Oc=t.then(()=>{},()=>{}),t}async function XI(e){const t=new URL(e.appUrl),r=new URL(Rw,location.origin),n=await fs(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:jw(_e)})}),i=await n.json();if(!n.ok||!Ie(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await KI(e.id),expiresAt:i.expires_at}}function eA(e,t){ln=window.setTimeout(()=>{!ne&&tt&&t===qe&&zr()},Math.max(1e3,e-Date.now()-3e4))}async function tA(){if(!(fo||ne)){fo=!0;try{const e=await ls();bc=Date.now();const t=sr;sr=!1;const r=Ai(e);if(!t&&r===us&&dt(dr(e.browserDevContext))===dt(ge)){Rt=e.browserDevContext,ge=dr(Rt),ti();return}_u(e),t&&Cr("CLI dev session reconnected"),tt&&zr()}catch(e){e instanceof Yt&&hn();const t=dr(Rt);dt(t)!==dt(ge)&&(ge=t,Gt=yi(ge),ti(),Fe+=1,Lr("local permission context expired"),Cr("local permission context expired"),hs(),tt&&hn()),Date.now()-bc>=3e4&&!sr&&(sr=!0,Fe+=1,Lr("CLI dev session disconnected"),re.device.replaceChildren(),Z.runtimeStatus="closed",Z.localPermissions=[],Z.devContextWarning="调试会话已断开",Rc({ready:!1,unavailableReason:"调试会话已断开"}),Z.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},tt&&hn())}finally{fo=!1}}}function hn(){qe+=1,Ni(),re.mobileQrImage.removeAttribute("src"),re.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Ai(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:dt(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})}function bu(){if(!vr){Z.account={authenticated:!1,avatar:"",nickname:"未登录"};return}Z.account={authenticated:!0,avatar:Uo??"",nickname:jo||ft||"已登录"}}function Ou(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function vu(e){if(!!!e?.miniProgramId||!e){Z.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}Z.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function rA(e){if(e===null)return null;if(!Ie(e))return;const t=de(e.miniProgramId)??de(e.mini_program_id);if(t)return{miniProgramId:t,...de(e.name)?{name:de(e.name)}:{},...de(e.iconUrl)??de(e.icon_url)?{iconUrl:de(e.iconUrl)??de(e.icon_url)}:{},...de(e.status)?{status:de(e.status)}:{},...de(e.version)?{version:de(e.version)}:{},...de(e.developerName)??de(e.developer_name)?{developerName:de(e.developerName)??de(e.developer_name)}:{}}}function de(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function Mi(){const e=++un,t=et,r=t?.diagnostics.storage;if(!r){Z.storage=[],Z.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(ne||e!==un||t!==et)return;Z.storage=n.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),Z.storageError=""}catch(n){if(ne||e!==un||t!==et)return;Z.storage=[],Z.storageError=ms(n)}}function nA(e,t){De("host.message",{message:e,status:t})}function iA(e){ne||nA(ms(e),"error")}function De(e,t){Rr(e,t)}function oA(){Fo!==void 0&&window.clearTimeout(Fo),!ne&&(ne=!0,window.removeEventListener("hb-sdk:restart-runtime",Au),window.removeEventListener("hb-sdk:refresh-storage",Mi),window.removeEventListener("hb-sdk:qr-open-change",Iu),wi+=1,Ii.abort(new DOMException("Browser Dev Host disposed","AbortError")),Qt.dispose(),Fe+=1,Lr("Browser Dev Host disposed"),fn?.close(),at?.dispose(),at=void 0,Ho.dispose(),Or=void 0,Pt!==void 0&&window.clearTimeout(Pt),Pt=void 0,Ni(),Po!==void 0&&window.clearInterval(Po),ei.clear(),ko?.(),ko=void 0,xo?.(),xo=void 0)}function Ni(){ln!==void 0&&window.clearTimeout(ln),ln=void 0}function Cu(e,t){return t?AbortSignal.any([e,t]):e}function Lu(e){return!ne&&e===wi}function sA(){return Ye.find(({id:e})=>e===re.mobileLanSelect.value)}function aA(e){return Ie(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 Ru(e){if(!(!Ie(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 Pu(e){return{networkRequest:{...e.networkRequest}}}function cA(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function ms(e){return e instanceof Error&&e.message?e.message:"操作失败"}function Ie(e){return Object.prototype.toString.call(e)==="[object Object]"}function rr(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}
102
+ </div>`,Z.runtimeStatus="idle";return}const r=document.createElement("iframe");r.dataset.testid="device-iframe",r.title="小程序预览",r.allow="clipboard-read; clipboard-write",r.name=sI,re.device.appendChild(r);const n=new AbortController;Co=n;let i=!1;try{const o=await dw(jI(n.signal,t));if(ie||t!==Fe){o.dispose();return}Ro=o.dispose,o.ports.companion=zo.port,o.ports.media=Gu({getMode:()=>Z.mediaSimulation,signal:n.signal});const s=QE({iframe:r,ports:o.ports,environment:o.environment,hostCapabilities:{...o.hostCapabilities,"media.pick":!0,...Xw},authPresentation:o.authPresentation,companionPresentation:zo.presentation,resolveLaunchConfiguration:async()=>(await o.resolveLaunch()).configuration,dispose:o.dispose,onReady:()=>{Z.runtimeStatus="ready",De("runtime.ready",{generation:t})},onTrace:a=>HI(t,a),onError:()=>{i=!0,Z.runtimeStatus="error"},onCapabilityTrace:a=>{ar||De(a.method,a),a.method==="storage.setStorage"&&a.outcome==="success"&&Mi()}});et=s,await s.start()}catch(o){if(ie||t!==Fe||n.signal.aborted)return;Z.runtimeStatus="error",i||De("runtime.start.failed",Qu(o))}}function xI(){De("runtime.ready",{generation:1}),Rr("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info"),De("user.getInfo",{durationMs:34,outcome:"success"}),De("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function jI(e,t){const r=ge,n=fr,i=xw(r.runtimePermissions,Gt,r);return{signal:e,account:{async getCurrentUserId(){return(await Vo(!1,e)).user_id},async ensureAuthenticated({signal:o}){await Vo(!1,o)},onChange(o){return ei.add(o),()=>ei.delete(o)}},authenticatedRequest:FI,storage:{area:"local",storage:localStorage},presentation:Jw({close:async()=>{Cc(),et?.destroy(),hr.reset(),Mu(),Z.runtimeStatus="closed"},reload:()=>{!ie&&t===Fe&&(Or=t)},onNavigationBarStyleChange:Lc,pushLog:De,getDeviceMetrics:()=>el.value,applyDisplay:(o,s)=>hr.applyDisplay(o,s),isCapsuleHidden:()=>Z.display.capsuleHidden,onViewportChange:o=>hr.onViewportChange(o)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:o=>{document.title=o}},resolveLaunch:async()=>({configuration:Gw({launchUrl:pu,runtimePermissions:i,...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:Yu.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:o=>Bw(o)},protocol:UI()}}function UI(){return{async invoke(e){De("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:zI(e)})}}}function zI(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 Ie(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function Mu(){document.documentElement.dataset.navigationBarStyle=_c,Lc(_c)}function HI(e,t){const r=qu(t,e);r&&vc(r),!(t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||Or!==e||e!==Fe)&&(Or=void 0,Lr("navigation.reload"))}async function FI(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 fs(n?SI:_I,{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&&Qt.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function Vo(e,t){const r=wi,n=await Nu(Lu(Ii.signal,t));return Cu(r)?Du(n,e).status:Bo()}async function Nu(e){return await(await fetch(TI,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Du(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<mr)return{changed:!1,status:Bo()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?de(e.nickname):void 0,i=e.authenticated?de(e.avatar):void 0,o=e.revision!==mr||e.authenticated!==vr||r!==ft||n!==jo||i!==Uo;return mr=e.revision,vr=e.authenticated,ft=r,jo=n,Uo=i,bu(),t&&o&&ei.forEach(s=>s(ft)),{changed:o,status:Bo()}}function Bo(){return{authenticated:vr,revision:mr,...vr&&ft?{user_id:ft}:{}}}function VI(){if(!(!se.csrfToken||ie))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",at=II({csrfToken:se.csrfToken,onDiagnostic:t=>De("channel.diagnostic",t),url:e.toString()}),at.subscribeUpdates((t,r)=>BI(t,r)),at.connect()}catch{at?.dispose(),at=void 0}}function BI(e,t){Qt.invalidate(e.account.revision),cA(Gt,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Ur("status changed"):(Gt=Pu(e.permissions),QI())}function Su(){if(fn?.close(),fn=void 0,!ft||ie)return;const e=new EventSource(bI);fn=e,e.addEventListener("account-invalidated",()=>{Qt.invalidate()}),e.addEventListener("account-revision",()=>{Qt.invalidate()}),e.onopen=()=>{Ho.reset()},e.onerror=()=>{e.close(),Ho.schedule()}}async function GI(e){Cu(e)&&await Ur("account revision changed")}function Cr(e){un+=1,Cc(),et&&zo.reset(),et?.destroy(),et=void 0,Co?.abort(new DOMException(e,"AbortError")),Co=void 0,Ro?.(),Ro=void 0,hr.reset()}async function QI(){ie||(await Ur("permission changed"),!ie&&await zr())}async function ls(){const e=await fetch(NI,{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(!Ie(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Ru(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new Yt;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:YI(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:yc(t.devContext,t.runtimePermissions),browserDevContext:yc(t.browserDevContext??t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(aA):[],loginAvailable:t.loginAvailable===!0,miniProgram:rA(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}}function YI(e){if(!Ie(e))return;const t=s=>{if(!(!Ie(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||!Ie(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=>Ie(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 fs(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),se.csrfToken&&r.set("x-hb-sdk-csrf",se.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function qI(){hs(),Et||(Po=window.setInterval(()=>{tA()},vI))}function Tu(e=re.mobileLanSelect.options.length>0?re.mobileLanSelect.value:void 0){re.mobileLanSelect.replaceChildren();for(const t of Ye){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,re.mobileLanSelect.appendChild(r)}e&&Ye.some(({id:t})=>t===e)?re.mobileLanSelect.value=e:an&&Ye.some(({id:t})=>t===an)?re.mobileLanSelect.value=an:Ye[0]&&(re.mobileLanSelect.value=Ye[0].id),re.mobileLanSelect.disabled=Ye.length===0}async function zr(){if(ie)return;const e=++qe;if(Ni(),_e.source!=="remote"||!_e.localDevLaunchToken||_e.expiresAt!==void 0&&_e.expiresAt<=Date.now()){re.mobileQrImage.removeAttribute("src"),re.mobileQrStatus.textContent=ds||"需要有效的本地调试启动票";return}const t=sA();if(!t?.mobileAppQrPayload){re.mobileQrImage.removeAttribute("src"),re.mobileQrStatus.textContent="未发现可用的局域网地址";return}re.mobileQrStatus.textContent="正在生成二维码...";try{const r=await ZI(t);if(e!==qe||ie)return;const n=await $I(r.address,r.expiresAt);if(e!==qe||ie)return;const i=await Cw.toDataURL(n.payload,{width:OI,margin:1});if(e!==qe||ie)return;re.mobileQrImage.src=i,re.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,eA(n.expiresAt,e)}catch(r){if(e!==qe||ie)return;if(r instanceof Yt){hn();return}re.mobileQrImage.removeAttribute("src"),re.mobileQrStatus.textContent=ms(r)}}async function $I(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await WI(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:iI(nI({host:e.address,port:location.port,token:n.token}))}}catch{throw new Yt}}async function WI(e,t){if(vt?.addressId===e.id)return vt;if(!vt)return;const r=await fs(DI,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:vt.token})});if(!r.ok)throw new Yt;const n=await r.json(),i=Ie(n)?Ru({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new Yt;return vt=i,dn={...dn,mobileLaunchRedirect:i},us=Ai(dn),i}async function KI(e){const t=await ls(),r=JI(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return _u(t),{...r,mobileAppQrPayload:n}}function JI(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function _u(e){const t=dt(ge);Z.devReadiness=e.devReadiness,Z.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,cn=e.workspaceCardsEnabled,dn=e,us=Ai(e),_e=e.devContext,Rt=e.browserDevContext,ge=dr(Rt),Gt=yi(ge),ti(),Ye=e.lanAddresses,an=e.defaultLanAddressId,vt=e.mobileLaunchRedirect,ds=e.nativeAppLaunchUnavailableReason,fr=e.devSessionId,Lo=e.miniProgramManifestAccessToken,vu(Ou(e)),tt&&Tu(),hs(),t!==dt(ge)&&(Fe+=1,Cr("local permission context changed"),Lr("local permission context changed"))}function ti(){Z.localPermissions=oI(ge),Z.devContextWarning=ge.source==="anonymous"?"未连接线上上下文":ge.warning?"本地上下文受限,请检查 CLI 状态":""}function hs(){let e;try{e=$u(pu)}catch{}const t=_e.miniProgramId?.trim().toLowerCase();let r=ds?.trim()??"";!r&&(_e.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!_e.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&cn&&!fr&&(r="本地调试会话尚未就绪"),!r&&_e.expiresAt!==void 0&&_e.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),Rc({...e?{address:e}:{},...t?{miniProgramId:t}:{},...cn&&fr?{devSessionId:fr}:{},...Lo?{miniProgramManifestToken:Lo}:{},workspaceCardsEnabled:cn,ready:r==="",...r?{unavailableReason:r}:{}})}class Yt extends Error{}async function ZI(e){const t=Oc.then(()=>XI(e));return Oc=t.then(()=>{},()=>{}),t}async function XI(e){const t=new URL(e.appUrl),r=new URL(Rw,location.origin),n=await fs(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:jw(_e)})}),i=await n.json();if(!n.ok||!Ie(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await KI(e.id),expiresAt:i.expires_at}}function eA(e,t){ln=window.setTimeout(()=>{!ie&&tt&&t===qe&&zr()},Math.max(1e3,e-Date.now()-3e4))}async function tA(){if(!(fo||ie)){fo=!0;try{const e=await ls();bc=Date.now();const t=sr;sr=!1;const r=Ai(e);if(!t&&r===us&&dt(dr(e.browserDevContext))===dt(ge)){Rt=e.browserDevContext,ge=dr(Rt),ti();return}_u(e),t&&Lr("CLI dev session reconnected"),tt&&zr()}catch(e){e instanceof Yt&&hn();const t=dr(Rt);dt(t)!==dt(ge)&&(ge=t,Gt=yi(ge),ti(),Fe+=1,Cr("local permission context expired"),Lr("local permission context expired"),hs(),tt&&hn()),Date.now()-bc>=3e4&&!sr&&(sr=!0,Fe+=1,Cr("CLI dev session disconnected"),re.device.replaceChildren(),Z.runtimeStatus="closed",Z.localPermissions=[],Z.devContextWarning="调试会话已断开",Rc({ready:!1,unavailableReason:"调试会话已断开"}),Z.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},tt&&hn())}finally{fo=!1}}}function hn(){qe+=1,Ni(),re.mobileQrImage.removeAttribute("src"),re.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Ai(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:dt(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})}function bu(){if(!vr){Z.account={authenticated:!1,avatar:"",nickname:"未登录"};return}Z.account={authenticated:!0,avatar:Uo??"",nickname:jo||ft||"已登录"}}function Ou(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function vu(e){if(!!!e?.miniProgramId||!e){Z.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}Z.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function rA(e){if(e===null)return null;if(!Ie(e))return;const t=de(e.miniProgramId)??de(e.mini_program_id);if(t)return{miniProgramId:t,...de(e.name)?{name:de(e.name)}:{},...de(e.iconUrl)??de(e.icon_url)?{iconUrl:de(e.iconUrl)??de(e.icon_url)}:{},...de(e.status)?{status:de(e.status)}:{},...de(e.version)?{version:de(e.version)}:{},...de(e.developerName)??de(e.developer_name)?{developerName:de(e.developerName)??de(e.developer_name)}:{}}}function de(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function Mi(){const e=++un,t=et,r=t?.diagnostics.storage;if(!r){Z.storage=[],Z.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(ie||e!==un||t!==et)return;Z.storage=n.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),Z.storageError=""}catch(n){if(ie||e!==un||t!==et)return;Z.storage=[],Z.storageError=ms(n)}}function nA(e,t){De("host.message",{message:e,status:t})}function iA(e){ie||nA(ms(e),"error")}function De(e,t){Rr(e,t)}function oA(){Fo!==void 0&&window.clearTimeout(Fo),!ie&&(ie=!0,window.removeEventListener("hb-sdk:restart-runtime",Au),window.removeEventListener("hb-sdk:refresh-storage",Mi),window.removeEventListener("hb-sdk:qr-open-change",Iu),wi+=1,Ii.abort(new DOMException("Browser Dev Host disposed","AbortError")),Qt.dispose(),Fe+=1,Cr("Browser Dev Host disposed"),fn?.close(),at?.dispose(),at=void 0,Ho.dispose(),Or=void 0,Pt!==void 0&&window.clearTimeout(Pt),Pt=void 0,Ni(),Po!==void 0&&window.clearInterval(Po),ei.clear(),ko?.(),ko=void 0,xo?.(),xo=void 0)}function Ni(){ln!==void 0&&window.clearTimeout(ln),ln=void 0}function Lu(e,t){return t?AbortSignal.any([e,t]):e}function Cu(e){return!ie&&e===wi}function sA(){return Ye.find(({id:e})=>e===re.mobileLanSelect.value)}function aA(e){return Ie(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 Ru(e){if(!(!Ie(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 Pu(e){return{networkRequest:{...e.networkRequest}}}function cA(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function ms(e){return e instanceof Error&&e.message?e.message:"操作失败"}function Ie(e){return Object.prototype.toString.call(e)==="[object Object]"}function rr(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}