@heybox/hb-sdk 0.9.3-alpha.3 → 0.9.3-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +1 -0
- package/dist/cli-chunks/{build-y_whX0Y8.cjs → build-Pn4ywWZY.cjs} +5 -5
- package/dist/cli-chunks/{context-bAN3b1qz.cjs → context-BkqQrXwr.cjs} +2 -2
- package/dist/cli-chunks/{create-CX4Fi-5h.cjs → create-D9TJ0rH0.cjs} +1 -1
- package/dist/cli-chunks/{deploy-lock-C4we--2w.cjs → deploy-lock-CZljn-8b.cjs} +1 -1
- package/dist/cli-chunks/{dev-D0D36AzV.cjs → dev-B0OQJx4y.cjs} +8 -8
- package/dist/cli-chunks/{doctor-CczqIgQy.cjs → doctor-BjeCwL0b.cjs} +1 -1
- package/dist/cli-chunks/{games-CEdO2iXM.cjs → games-BrhVCrnm.cjs} +2 -2
- package/dist/cli-chunks/{index-DCUp4VzF.cjs → index-BvM5AsMO.cjs} +1 -1
- package/dist/cli-chunks/{index-Bmx3RIrn.cjs → index-D-8IXO0n.cjs} +17 -17
- package/dist/cli-chunks/{index.esm-Be_gxy9A.cjs → index.esm-B4XiZERF.cjs} +6 -6
- package/dist/cli-chunks/{login-Cjs4VcAt.cjs → login-Cl3VO6xC.cjs} +1 -1
- package/dist/cli-chunks/{project-vite-ClJEE8Ue.cjs → project-vite-CPDYMw5b.cjs} +1 -1
- package/dist/cli-chunks/{remote-KMLs8bfb.cjs → remote-BWQezxnR.cjs} +7 -7
- package/dist/cli-chunks/{runtime-gate-CCC4HuxH.cjs → runtime-gate-CNLagNgF.cjs} +2 -2
- package/dist/cli-chunks/{runtime-permission-env-Cbcp9CAl.cjs → runtime-permission-env-CJR-o3w0.cjs} +2 -2
- package/dist/cli-chunks/{skill-DK7DYt5L.cjs → skill-B8qbj4Tc.cjs} +2 -2
- package/dist/cli-chunks/{version-DMj52uR6.cjs → version-Bpd890Nm.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/{browser-dev-host-uQK7vlP1.js → browser-dev-host-OpkCfneE.js} +1 -1
- package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-lsHHaUF-.js → desktop-app-launch-lns4avol.js} +1 -1
- package/dist/devtools/browser-dev-host/assets/{index-DoR-TyvY.js → index-_0y5rm2x.js} +3 -3
- package/dist/devtools/browser-dev-host/index.html +2 -2
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/vite.cjs.js +1 -1
- package/dist/vite.esm.js +1 -1
- package/docs/runtime-host-migration.md +1 -1
- package/package.json +4 -4
- package/skill/skill.json +4 -4
- package/types/index.d.ts +22 -0
- package/types/protocol.d.ts +14 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{H as ts,ax as fu,aY as hu,M as mu,aH as gu,aI as pu,aj as Tr,b6 as q,aa as yu,ak as lc,aq as Eu,b0 as wu,am as Iu,d as Mu,aE as fc,a8 as Au,at as hc,r as Nu,az as mc,o as Du,aD as Su,a5 as Tu,a_ as bu,aZ as Ou,c as _u}from"./desktop-app-launch-lsHHaUF-.js";const sn="workspaceCards.requestRefresh",an="auth.getAccountState",cn="auth.login",dn="user.getInfo",un="user.revokeAuthorization",ln="user.getSteamGameList",fn="share.copyLink",hn="share.showShareMenu",mn="share.screenshot",at="viewport.setDisplay",gn="viewport.getWindowInfo",pn="viewport.setNavigationBarStyle",ur="storage.getStorage",lr="storage.setStorage",yn="network.request",En="network.download",wn="network.upload",In="files.pickFiles",Mn="files.pickDirectory",An="files.saveFile",fr="file.create",hr="file.remove",Nn="file.exists",mr="file.readText",Dn="file.writeText",gr="file.readBytes",Sn="file.writeBytes",pr="file.stat",Tn="directory.create",yr="directory.remove",bn="directory.exists",On="directory.list",_n="ui.showToast",vn="ui.showLoading",Ln="ui.hideLoading",Cn="device.vibrate",Rn="device.setClipboard",Pn="device.executeProtocol",kn="navigation.close",xn="navigation.reload",jn="navigation.openAppPage",je="cloud.leaderboard.submit",De="cloud.leaderboard.getList",Qe="cloud.leaderboard.getCurrentUserEntry",ct="cloud.leaderboard.deleteCurrentUserEntry",Re="cloud.leaderboard.getInfo",vt="cloud.storage.getStorage",Lt="cloud.storage.setStorage",Ct="cloud.storage.removeItem",dt="cloud.storage.getKeys",qn="companion.getInfo",$n="companion.getPreparationStatus",Wn="companion.prepare",Kn="companion.cancelPreparation",Jn="companion.getActiveSession",Zn="companion.launch",Xn="companion.session.write",ei="companion.session.closeStdin",ti="companion.session.terminate",ri="companion.session.ackOutput",ni="companion.openAttachment",ii="companion.showNotification",Ye=[{method:sn,module:"workspaceCards",capability:sn,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:an,module:"auth",capability:an,requirement:{kind:"none"},risk:"low"},{method:cn,module:"auth",capability:cn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:dn,module:"user",capability:dn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:un,module:"user",capability:un,requirement:{kind:"none"},risk:"high"},{method:ln,module:"user",capability:ln,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:fn,module:"share",capability:fn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:hn,module:"share",capability:hn,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:mn,module:"share",capability:mn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:gn,module:"viewport",capability:gn,requirement:{kind:"none"},risk:"low"},{method:pn,module:"viewport",capability:pn,requirement:{kind:"none"},risk:"low"},{method:at,module:"viewport",capability:at,requirement:{kind:"none"},risk:"low"},{method:ur,module:"storage",capability:ur,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:lr,module:"storage",capability:lr,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:yn,module:"network",capability:yn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:En,module:"network",capability:En,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:wn,module:"network",capability:wn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:In,module:"files",capability:In,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mn,module:"files",capability:Mn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:An,module:"files",capability:An,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:fr,module:"file",capability:fr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:hr,module:"file",capability:hr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Nn,module:"file",capability:Nn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:mr,module:"file",capability:mr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dn,module:"file",capability:Dn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:gr,module:"file",capability:gr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Sn,module:"file",capability:Sn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:pr,module:"file",capability:pr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Tn,module:"directory",capability:Tn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:yr,module:"directory",capability:yr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:bn,module:"directory",capability:bn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:On,module:"directory",capability:On,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_n,module:"ui",capability:_n,requirement:{kind:"none"},risk:"low"},{method:vn,module:"ui",capability:vn,requirement:{kind:"none"},risk:"low"},{method:Ln,module:"ui",capability:Ln,requirement:{kind:"none"},risk:"low"},{method:Cn,module:"device",capability:Cn,requirement:{kind:"none"},risk:"low"},{method:Rn,module:"device",capability:Rn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Pn,module:"device",capability:Pn,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:kn,module:"navigation",capability:kn,requirement:{kind:"none"},risk:"medium"},{method:xn,module:"navigation",capability:xn,requirement:{kind:"none"},risk:"medium"},{method:jn,module:"navigation",capability:jn,requirement:{kind:"none"},risk:"medium"},{method:je,module:"cloud",capability:je,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:De,module:"cloud",capability:De,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Qe,module:"cloud",capability:Qe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:ct,module:"cloud",capability:ct,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Re,module:"cloud",capability:Re,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:vt,module:"cloud",capability:vt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:Lt,module:"cloud",capability:Lt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Ct,module:"cloud",capability:Ct,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:dt,module:"cloud",capability:dt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[qn,$n,Wn,Kn,Jn,Zn,Xn,ei,ti,ri,ni,ii].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],et="heybox:miniprogram",gc=2,vu="hb_mini_bridge_nonce",pc="sdk.handshake",Pr="runtime.location.probe",Lu="sdk.location.report",Cu="sdk.csp.violation",yc="operation.progress",Ru="companion.session.output",Pu="companion.session.exit",ku="companion.session.ownershipLost";function xu(e){return!Je(e)||e.namespace!==et||e.version!==1&&e.version!==2||!fe(e.nonce)?!1:e.type==="handshake"?fe(e.id)&&e.method===pc&&e.error===void 0&&Hu(e.payload):e.type==="request"?fe(e.id)&&fe(e.method)&&e.error===void 0:e.type==="response"?fe(e.id)&&(e.method===void 0||fe(e.method))&&(e.error===void 0||Fu(e.error)):e.type==="event"?!fe(e.method)||e.error!==void 0?!1:e.method===yc?e.version===2&&fe(e.id)&&zu(e.payload):e.id===void 0||fe(e.id):e.type==="cancel"?e.version===2&&fe(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Co(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function Ec(e){return Je(e)?e.kind==="sandbox"?Ue(e,["kind"]):e.kind==="directory"&&fe(e.handleId)&&Ue(e,["kind","handleId"]):!1}function oi(e){return!Je(e)||e.kind!=="file"?!1:fe(e.handleId)?Ue(e,["kind","handleId"]):Ec(e.root)&&Co(e.relativePath)&&Ue(e,["kind","root","relativePath"])}function wc(e){return!Je(e)||e.kind!=="directory"?!1:fe(e.handleId)?Ue(e,["kind","handleId"]):Ec(e.root)&&(e.relativePath==="."||Co(e.relativePath))&&Ue(e,["kind","root","relativePath"])}function Ic(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function ju(e){return!Je(e)||!St(e.loaded)||typeof e.lengthComputable!="boolean"||!Ue(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?St(e.total)&&e.loaded<=e.total:e.total===void 0}function Uu(e){return Je(e)?e.phase==="downloading"?St(e.loaded)&&(e.total===void 0||St(e.total)&&e.loaded<=e.total)&&Ue(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:St(e.processed)&&St(e.total)&&e.processed<=e.total&&Ue(e,["phase","processed","total"]):!1}function zu(e){return ju(e)||Uu(e)}function Hu(e){return Je(e)&&fe(e.href)&&typeof e.userAgent=="string"&&fe(e.sdkVersion)}function Fu(e){return Je(e)&&fe(e.code)&&typeof e.message=="string"}function St(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function fe(e){return typeof e=="string"&&e.length>0}function Ue(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Er=["userInfo","steamLibrary","share","storage","cloud_storage","filesystem","clipboard","leaderboard","network","companion","appProtocol","workspaceCards"],Mc=[{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:"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(Er);const Vu=new Set(Er);function Bu(e){return Vu.has(e)}function Se(e){if(!kr(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(!kr(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),!!Bu(o)){if(o==="network"){const s=n.config;if(!kr(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&&(!kr(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 kr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const qr=["network","companion","appProtocol"];function Ac(e){if(!Gt(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>qr.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Gt(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(!Gt(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(!Gt(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Gt(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>qr.indexOf(n.key)-qr.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Gu(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Se(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of qr)!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 Ro(e){const t=Se(e.runtimePermissions),r=Ac(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of Er)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:Mc.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=Nc(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:Er.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function Nc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gt(e,t){return Nc(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Rt=["identity","profile","steam_account"],Qu=/^[a-z][a-z0-9-]{0,31}$/,Dc=["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"];Ye.map(e=>e.method);function Yu(e){const t=Se(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 qu(e){const t=Se(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 Z(e,t,r){return{code:e,message:t,data:r}}function Po(e){return $u(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?Z("RUNTIME_ERROR",e.message):Z("UNKNOWN_ERROR","小程序运行时异常",e)}function $u(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function Wu(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Ku=1e3;function Ju(e,t=Wu()){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<=Ku}const Zu="runtime.gate.probe",Sc=new Set(Ye.map(e=>e.method));class Xu{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=gc;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:et,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:et,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:et,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:et,version:2,nonce:this.nonce,type:"event",id:t,method:yc,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=Ju(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&&xu(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:et,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:pc,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===Zu){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,Z("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Sc.has(t.method)){this.postResponse(t,void 0,Z("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,Z("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=Po(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:et,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!el(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 el(e){return typeof e=="string"&&Sc.has(e)}const Tc="METHOD_FORBIDDEN";function Te(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Tc,t}class ae 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 tl=/^[A-Za-z0-9_-]{1,64}$/,rs=1e3;function bc(e){return tl.test(e)?e:nl(e)}function rl(e){return`id_${bc(e.trim())}`}function mt(e,t){return`hb_miniprogram_${e}_${t}`}function xr(e){return`hb_miniprogram_keys_${e}`}function nl(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 ns={[sn]:["workspaceCards.requestRefresh"],[an]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[cn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[dn]:["account.getCurrentUserId","account.onChange","network.request"],[un]:["account.getCurrentUserId","account.onChange","network.request"],[ln]:["account.getCurrentUserId","account.onChange","network.request"],[fn]:["presentation.setClipboard"],[hn]:["presentation.showShareMenu"],[mn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[at]:["presentation.applyOrientation"],[gn]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[pn]:["presentation.setNavigationBarStyle"],[ur]:["storage.getRaw"],[lr]:["storage.setRaw"],[yn]:["network.request"],[En]:["network.stream","files.transfer","files.access"],[wn]:["network.upload","files.access"],[In]:["files.external"],[Mn]:["files.external"],[An]:["files.save"],[fr]:["files.access"],[hr]:["files.removeFile"],[Nn]:["files.access"],[mr]:["files.access"],[Dn]:["files.access"],[gr]:["files.access"],[Sn]:["files.access"],[pr]:["files.access"],[Tn]:["files.access"],[yr]:["files.removeDirectory"],[bn]:["files.access"],[On]:["files.access"],[_n]:["presentation.showToast"],[vn]:["presentation.showLoading"],[Ln]:["presentation.hideLoading"],[Cn]:["presentation.vibrate"],[Rn]:["presentation.setClipboard"],[Pn]:["protocol.invoke"],[kn]:["presentation.close"],[xn]:["presentation.reload"],[jn]:["presentation.openAppPage"],[je]:["account.getCurrentUserId","account.onChange","network.request"],[De]:["account.onChange","network.request"],[Qe]:["account.getCurrentUserId","account.onChange","network.request"],[ct]:["account.getCurrentUserId","account.onChange","network.request"],[Re]:["account.onChange","network.request"],[vt]:["account.getCurrentUserId","account.onChange","network.request"],[Lt]:["account.getCurrentUserId","account.onChange","network.request"],[Ct]:["account.getCurrentUserId","account.onChange","network.request"],[dt]:["account.getCurrentUserId","account.onChange","network.request"],[qn]:["companion.getInfo"],[$n]:["companion.getPreparationStatus"],[Wn]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[Kn]:["companion.cancelPreparation"],[Jn]:["companion.getActiveSession"],[Zn]:["companion.getInfo","companion.launch"],[Xn]:["companion.session.write"],[ei]:["companion.session.closeStdin"],[ti]:["companion.session.terminate"],[ri]:["companion.session.ackOutput"],[ni]:["companion.openAttachment"],[ii]:["companion.showNotification"]};function il(e,t){if(t[e]!==!0)throw Te(e)}const ol=32*1024*1024,sl=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function al(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:ol},i);return cl(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function cl(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:dl(t,ll(e,"content-type"))}}function dl(e,t){ul(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new ae("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!sl.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function ul(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new ae(`Host network response 不支持 charset=${t}`)}function ll(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function x(e){return typeof e=="function"}function is(e){return(...t)=>{throw Te(e)}}function oe(e){return async(...t)=>{throw Te(e)}}const fl=(e,t)=>{},hl=()=>()=>{};function ml(e){const t={request:x(e.network?.request)?e.network.request.bind(e.network):oe("network.request")},r={...x(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:x(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):oe("account.getCurrentUserId"),ensureAuthenticated:x(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):oe("account.ensureAuthenticated"),onChange:x(e.account?.onChange)?e.account.onChange.bind(e.account):hl},n={getRaw:x(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):oe("storage.getRaw"),setRaw:x(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):oe("storage.setRaw")},i={...x(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...x(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:x(e.presentation?.close)?e.presentation.close.bind(e.presentation):oe("presentation.close"),reload:x(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):oe("presentation.reload"),openAppPage:x(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):oe("presentation.openAppPage"),openWindow:x(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):oe("presentation.openWindow"),getViewportMetrics:x(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):is("presentation.getViewportMetrics"),getNavigationBarHeight:x(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):is("presentation.getNavigationBarHeight"),setNavigationBarStyle:x(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):oe("presentation.setNavigationBarStyle"),showShareMenu:x(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):oe("presentation.showShareMenu"),setScreenshotChromeHidden:x(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):fl,captureAndShare:x(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):oe("presentation.captureAndShare"),showToast:x(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):oe("presentation.showToast"),showLoading:x(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):oe("presentation.showLoading"),hideLoading:x(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):oe("presentation.hideLoading"),vibrate:x(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):oe("presentation.vibrate"),setClipboard:x(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):oe("presentation.setClipboard")},o=x(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,x(e.companion?.[c])?e.companion[c].bind(e.companion):oe(`companion.${c}`)]));x(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const a={invoke:x(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):oe("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.transfer===void 0?{}:{transfer:e.transfer},...e.scopedStorage?{scopedStorage:e.scopedStorage}:{},...o?{storageDiagnostics:o}:{}}}function gl(e){const t=pl(e.files?.sandbox),r=x(e.picker?.pickFiles)&&x(e.picker?.pickDirectory),n=x(e.picker?.saveFile),i=t||r||n||x(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":x(e.account?.getAccountKey),"account.getCurrentUserId":x(e.account?.getCurrentUserId),"account.ensureAuthenticated":x(e.account?.ensureAuthenticated),"account.onChange":x(e.account?.onChange),"network.request":x(e.network?.request),"network.stream":x(e.transfer?.network.open)&&x(e.transfer?.network.release),"network.upload":x(e.transfer?.upload?.upload),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":x(o?.remove),"files.removeDirectory":x(e.files?.sandbox.remove),"files.transfer":x(e.transfer?.files.writeResource),"storage.getRaw":x(e.scopedStorage?.get)||x(e.storage?.getRaw),"storage.setRaw":x(e.scopedStorage?.set)||x(e.storage?.setRaw),"presentation.close":x(e.presentation?.close),"presentation.reload":x(e.presentation?.reload),"presentation.openAppPage":x(e.presentation?.openAppPage),"presentation.applyOrientation":x(e.presentation?.applyOrientation),"presentation.openWindow":x(e.presentation?.openWindow),"presentation.getViewportMetrics":x(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":x(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":x(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":x(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":x(e.presentation?.captureAndShare),"presentation.showToast":x(e.presentation?.showToast),"presentation.showLoading":x(e.presentation?.showLoading),"presentation.hideLoading":x(e.presentation?.hideLoading),"presentation.vibrate":x(e.presentation?.vibrate),"presentation.setClipboard":x(e.presentation?.setClipboard),"workspaceCards.requestRefresh":!1,"companion.getInfo":x(e.companion?.getInfo),"companion.getPreparationStatus":x(e.companion?.getPreparationStatus),"companion.prepare":x(e.companion?.prepare),"companion.cancelPreparation":x(e.companion?.cancelPreparation),"companion.getActiveSession":x(e.companion?.getActiveSession),"companion.launch":x(e.companion?.launch),"companion.session.write":x(e.companion?.write),"companion.session.closeStdin":x(e.companion?.closeStdin),"companion.session.terminate":x(e.companion?.terminate),"companion.session.ackOutput":x(e.companion?.ackOutput),"companion.openAttachment":x(e.companion?.openAttachment),"companion.showNotification":x(e.companion?.showNotification),"protocol.invoke":x(e.protocol?.invoke)}}function pl(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&x(t.file)&&x(t.directory)&&x(t.create)&&x(t.stat)&&x(t.list)}function os(e,t){return t?.[e]!==!1}function yl(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("companion.")}function Oc(e,t={}){const r={};for(const n of Object.keys(ns)){const o=ns[n].every(a=>e[a]),s=!yl(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=os(n,t.callerCapabilities)&&os(n,t.hostCapabilities)&&o&&s}return r}function _c(e={},t={}){const r=gl(e),n=Oc(r,t);return{ports:ml(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function ut(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):El(e.signal,t);return{...e,signal:r}}function El(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 wl(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 Il=4,Ml=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Al=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),Nl=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Dl=["/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 Sl(e,t){const r=Ol(e);return r===null||ss(r,Nl)?!0:t&&ss(r,Dl)}function Tl(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Ml.some(r=>t===r||t.endsWith(`.${r}`))}function bl(e){const t=e.trim().toLowerCase();return Al.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Ol(e){let t=e;for(let r=0;r<Il;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return as(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return as(t)}function ss(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function as(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function gt(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function cs(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function vc(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,o=new Map,s=new Set,a=new Set;let c=!1;function d(E,T){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:E,type:T})).catch(()=>{})}catch{}}function l(E){const T=r.get(E);if(!T)throw new Error("Unknown runtime cache scope");return T}function f(E,T){return E.flatMap((I,v)=>{const S=JSON.stringify(E.slice(0,v+1));return[JSON.stringify([S]),JSON.stringify([S,T])]})}function u(E,T){return JSON.stringify(f(E,T).map(I=>n.get(I)??0))}async function h(E,T){const I=l(E),v=JSON.stringify([JSON.stringify(I),...T?[T]:[]]),S=(n.get(v)??0)+1;n.set(v,S),i.add(v);for(const P of a)P(I,T);if(!e.store){i.delete(v),d(T??"*","invalidation");return}try{await e.store.invalidate(I,T)}catch(P){throw d(T??"*","storage_error"),P}n.get(v)===S&&i.delete(v),d(T??"*","invalidation")}function p(E){if(c)throw new Error("Runtime cache manager disposed");const T=o.get(E.namespace);if(T){if(T.sourceCodec!==E.codec||T.definition.codec.version!==E.codec.version||JSON.stringify(T.definition.policy)!==JSON.stringify(E.policy))throw new Error("Conflicting runtime cache namespace");return T.cache}if(!E.namespace||!E.codec.version)throw new Error("Invalid runtime cache definition");const I=Object.freeze({...E.policy}),v=Object.freeze({version:E.codec.version,encode:E.codec.encode.bind(E.codec),decode:E.codec.decode.bind(E.codec),validate:E.codec.validate.bind(E.codec),clone:E.codec.clone.bind(E.codec)}),S=E.namespace;for(const L of[I.ttlMs,I.memoryMaxEntries,I.diskMaxEntries,I.diskMaxBytes,I.maxEntryBytes])if(!Number.isFinite(L)||L<0)throw new Error("Invalid runtime cache policy");const P=new Map,V=new Map,R=new Map;let M=!1;function w(L,N,b){if(c||M||L.aborted||u(N,S)!==b)throw gt()}function D(L){return I.ttlMs>0&&I.persistence==="memory-and-disk"&&!!e.store&&!f(L,S).some(N=>i.has(N))}function y(L,N,b){const C=t();return L.envelopeVersion===1&&JSON.stringify(L.address)===JSON.stringify(N)&&cs(L.revisions,b)&&L.payload.byteLength<=I.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+I.ttlMs)>C}function O(L,N,b,C,k){if(!(I.ttlMs<=0||I.memoryMaxEntries<1)){for(const[U,z]of P)Math.min(z.entry.expiresAt,z.entry.cachedAt+I.ttlMs)<=t()&&P.delete(U);for(P.delete(L);P.size>=Math.floor(I.memoryMaxEntries);){const U=P.keys().next();if(U.done)break;P.delete(U.value)}P.set(L,{entry:N,value:b,epoch:C,persistent:k})}}async function m(L,N,b,C){const k={namespace:S,codecVersion:v.version,scopeIds:N,key:L.key},U=JSON.stringify(k);let z=[],F=D(N);if(F)try{z=await e.store.readRevisions(N,S)}catch{F=!1,d(S,"storage_error")}w(C.signal,N,b);async function G(){if(!F)return!0;try{return cs(z,await e.store.readRevisions(N,S))}catch{return F=!1,d(S,"storage_error"),!1}}const re=P.get(U);if(I.ttlMs>0&&re&&re.epoch===b&&y(re.entry,k,z)&&re.persistent===F&&await G())return w(C.signal,N,b),d(S,"memory_hit"),re.value;if(P.delete(U),F){let Y,ue;try{Y=await e.store.read(k,I.maxEntryBytes),Y&&y(Y,k,z)?ue=v.decode(Y.payload):Y=void 0}catch{Y=void 0,d(S,"storage_error")}if(w(C.signal,N,b),Y&&await G())return w(C.signal,N,b),O(U,Y,ue,b,!0),d(S,"disk_hit"),ue}d(S,"miss");const $=v.validate(await L.load(C.signal));w(C.signal,N,b);const J=v.clone($);if(!await G()&&F)throw gt();if(w(C.signal,N,b),I.ttlMs>0){const Y=t();let ue;try{ue=v.encode(J)}catch{return J}const Rr={envelopeVersion:1,address:k,revisions:F?z:[],cachedAt:Y,expiresAt:Y+I.ttlMs,payload:ue};if(F&&ue.byteLength<=I.maxEntryBytes){let Bt=!0,es=!1;try{Bt=await e.store.publish(Rr,I),es=Bt}catch{d(S,"storage_error")}if(w(C.signal,N,b),!Bt)throw gt();es&&d(S,"published")}w(C.signal,N,b),O(U,Rr,J,b,F)}return J}async function A(L){if(c||M||L.signal?.aborted)return Promise.reject(gt());const N=l(L.scope),b=u(N,S);let C;if(D(N)){const F=new AbortController;R.set(F,N);const G=()=>F.abort();L.signal?.addEventListener("abort",G,{once:!0});let re=()=>{};try{C=await Promise.race([e.store.readRevisions(N,S),new Promise(($,J)=>{const Y=()=>J(gt());F.signal.addEventListener("abort",Y,{once:!0}),re=()=>F.signal.removeEventListener("abort",Y)})])}catch{F.signal.aborted||d(S,"storage_error")}finally{re(),R.delete(F),L.signal?.removeEventListener("abort",G)}}w(L.signal??new AbortController().signal,N,b);const k=JSON.stringify([N,L.key,b,C]);let U=V.get(k);if(U?.controller.signal.aborted&&(U=void 0),!U){const F=new AbortController;U={ids:N,controller:F,waiters:0,promise:Promise.resolve(void 0)};const G=U;G.promise=m(L,N,b,F).finally(()=>{V.get(k)===G&&V.delete(k)}),V.set(k,G)}const z=U;return z.waiters+=1,new Promise((F,G)=>{let re=!1;function $(Y){re||(re=!0,L.signal?.removeEventListener("abort",J),z.controller.signal.removeEventListener("abort",J),z.waiters-=1,z.waiters===0&&z.controller.abort(),Y())}function J(){$(()=>G(gt()))}L.signal?.addEventListener("abort",J,{once:!0}),z.controller.signal.addEventListener("abort",J,{once:!0}),z.promise.then(Y=>$(()=>{try{w(L.signal??new AbortController().signal,N,b),F(v.clone(Y))}catch(ue){G(ue)}}),Y=>$(()=>G(Y)))})}function _(L,N){if(N&&N!==S)return;const b=C=>L.every((k,U)=>C[U]===k);for(const[C,k]of P)b(k.entry.address.scopeIds)&&P.delete(C);for(const[C,k]of V)b(k.ids)&&(k.controller.abort(),V.delete(C));for(const[C,k]of R)b(k)&&C.abort()}function j(){if(!M){M=!0,P.clear();for(const L of R.keys())L.abort();R.clear();for(const L of V.values())L.controller.abort();V.clear(),s.delete(j),a.delete(_),o.get(S)?.cache===H&&o.delete(S)}}const H={read:A,invalidateScope:L=>h(L,S),dispose:j};return s.add(j),a.add(_),o.set(S,{definition:{namespace:S,codec:v,policy:I},sourceCodec:E.codec,cache:H}),H}return{createScope(E,T){if(c||!E)throw new Error("Invalid runtime cache scope");const I=Object.freeze({});return r.set(I,[...T?l(T):[],E]),I},register:p,invalidateScope:E=>h(E),dispose(){if(!c){c=!0;for(const E of[...s])E();o.clear(),n.clear(),i.clear()}}}}function _l(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 vl=".hb-runtime-cache-v1",Ll=1e3,pi=64*1024,pt=1e3,Cl=2048,Qt=32*1024*1024,Rl=1024,$r=new TextEncoder,ds=new TextDecoder("utf-8",{fatal:!0});function Yt(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function jr(e){const t=await globalThis.crypto.subtle.digest("SHA-256",$r.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Oe(e,t){return JSON.stringify(e)===JSON.stringify(t)}function us(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function Pl(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function ls(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function kl(e,t){const r=e.sandbox.directory(vl),n=r.directory("revisions"),i=r.directory("entries");for(const m of[r,n,i,i.directory("capability-check")])ls(m,["directory","file","create","stat","list","remove"]),ls(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 l(m){d=m,o.abort(),t.signal.removeEventListener("abort",s)}function f(m){if(Pl(m))throw l(m),m}function u(){if(d)throw d;if(a.signal.aborted)throw Yt()}function h(m,A=a.signal){const _=c.then(()=>{if(A.aborted)throw d??Yt();return u(),m()},()=>{if(A.aborted)throw d??Yt();return u(),m()}).catch(N=>{throw f(N),N});if(c=_.catch(()=>{}),A.aborted)return Promise.reject(d??Yt());let j=()=>{};const H=new Promise((N,b)=>{const C=()=>b(d??Yt());A.addEventListener("abort",C,{once:!0}),j=()=>A.removeEventListener("abort",C)}),L=setTimeout(()=>{l(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},Ll);return Promise.race([_,H]).finally(()=>{clearTimeout(L),j()})}async function p(){u(),await n.create({recursive:!0,exclusive:!1},a),u(),await i.create({recursive:!0,exclusive:!1},a),u()}async function E(m,A){const _=n.file(`${await jr([m,A??null])}.revision`);await I(_);let j=!1;try{await _.create({recursive:!1,exclusive:!0},a),j=!0}catch(N){f(N),u()}if(j){const N=us();return await _.write($r.encode(N),a),u(),N}const H=await _.stat(a);if(H.size<1||H.size>128)throw new Error("缓存 revision 文件损坏");const L=ds.decode(await _.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(L))throw new Error("缓存 revision 文件损坏");return u(),L}async function T(m){const A=await m.list({limit:pt},a);if(A.length>=pt)throw new Error("缓存目录超过治理上限");return A}async function I(m){try{await m.stat(a);return}catch(_){if(!Ur(_))throw _}if((await T(n)).length>=pt-1)throw new Error("缓存 metadata 超过治理上限")}async function v(m,A){await p();const _=[];for(let j=0;j<m.length;j+=1){const H=m.slice(0,j+1);_.push(await E(H),await E(H,A))}return _}async function S(m){return r.directory(`entries/${await jr([m.namespace,m.codecVersion,m.scopeIds])}`)}async function P(m){return(await S(m)).file(`${await jr(m.key)}.cache`)}async function V(m,A){const _=await m.stat(a);if(_.size<5||_.size>A+pi+4)throw new Error("缓存条目超过大小限制");const j=await m.read(a);if(u(),j.length!==_.size)throw new Error("缓存条目读取不完整");const H=new DataView(j.buffer,j.byteOffset,j.byteLength).getUint32(0);if(H<1||H>pi||H+4>j.length)throw new Error("缓存信封损坏");const L=JSON.parse(ds.decode(j.subarray(4,H+4))),N=j.slice(H+4);if(L.envelopeVersion!==1||!L.address||!Array.isArray(L.address.scopeIds)||!L.address.scopeIds.every(b=>typeof b=="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(b=>typeof b=="string"&&b.length>0)||!Number.isSafeInteger(L.cachedAt)||!Number.isSafeInteger(L.expiresAt)||L.cachedAt<0||L.expiresAt<=L.cachedAt||L.payloadBytes!==N.length||N.length>A)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:L.address,revisions:L.revisions,cachedAt:L.cachedAt,expiresAt:L.expiresAt,payload:N}}async function R(m){if(!m.remove)throw new Error("Host 不支持缓存文件删除");await m.remove(a)}async function M(m){try{if((await m.file.stat(a)).size!==m.size)return!1;const A=await V(m.file,Qt);return!Oe(A.address,m.entry.address)||!Oe(A.revisions,m.entry.revisions)||A.cachedAt!==m.entry.cachedAt||A.expiresAt!==m.entry.expiresAt||!Oe(await w(A.payload),await w(m.entry.payload))?!1:(await R(m.file),!0)}catch(A){if(Ur(A))return!0;throw A}}async function w(m){const A=await globalThis.crypto.subtle.digest("SHA-256",m);return Array.from(new Uint8Array(A),_=>_.toString(16).padStart(2,"0")).join("")}async function D(){const m=await T(n);let A=0;for(const L of m)if(L.kind==="file"&&(A+=(await L.stat(a)).size,A>Qt))throw new Error("缓存扫描超过字节上限");const _=[];let j=0,H=A;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"||++j>Cl)throw new Error("缓存文件超过治理上限");const b=(await N.stat(a)).size;if(H+=b,H>Qt)throw new Error("缓存扫描超过字节上限");try{const C=await V(N,Qt);_.push({file:N,entry:C,size:(await N.stat(a)).size,bucketName:L.name})}catch(C){f(C),u(),Ur(C)||await R(N)}}}return{entries:_,metadataBytes:A}}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(A){f(A),u()}}function O(m){const{payload:A,..._}=m,j=$r.encode(JSON.stringify({..._,payloadBytes:A.length}));if(j.length>pi)throw new Error("缓存信封过大");const H=new Uint8Array(4+j.length+A.length);return new DataView(H.buffer).setUint32(0,j.length),H.set(j,4),H.set(A,j.length+4),H}return{readRevisions:(m,A)=>h(()=>v(m,A)),read:(m,A)=>h(async()=>{u();const _=await P(m);let j;try{j=await V(_,A)}catch(H){if(u(),Ur(H))return;throw H}if(!(!Oe(j.address,m)||j.expiresAt<=Date.now())&&Oe(j.revisions,await v(m.scopeIds,m.namespace)))return j}),publish:(m,A)=>h(async()=>{u();const{address:_}=m;if(!Oe(m.revisions,await v(_.scopeIds,_.namespace)))return!1;const j=O(m);if(m.payload.length>A.maxEntryBytes||j.length>A.diskMaxBytes||A.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await p();const H=await S(_),L=await P(_),N=await D(),b=[],C=new Map;for(const z of N.entries){if(z.bucketName===H.name&&z.file.name===L.name)continue;const F=JSON.stringify([z.entry.address.scopeIds,z.entry.address.namespace]);let G=C.get(F);if(G||(G=await v(z.entry.address.scopeIds,z.entry.address.namespace),C.set(F,G)),z.entry.expiresAt<=Date.now()||!Oe(z.entry.revisions,G)){if(!await M(z))throw new Error("缓存治理期间条目已变化")}else b.push(z)}b.sort((z,F)=>z.entry.cachedAt-F.entry.cachedAt);function k(){const z=b.filter(F=>F.bucketName===H.name);return b.length+1>Rl||j.length+N.metadataBytes+b.reduce((F,G)=>F+G.size,0)>Qt||z.length+1>Math.min(A.diskMaxEntries,pt-1)||j.length+z.reduce((F,G)=>F+G.size,0)>A.diskMaxBytes}for(;k();){const z=b.filter(re=>re.bucketName===H.name),G=z.length+1>Math.min(A.diskMaxEntries,pt-1)||j.length+z.reduce((re,$)=>re+$.size,0)>A.diskMaxBytes?z[0]:b[0];if(!G||!await M(G))throw new Error("缓存容量不足或条目已变化");b.splice(b.indexOf(G),1)}await y();const U=await T(i);if(!U.some(z=>z.name===H.name)&&U.length>=pt-1)throw new Error("缓存目录超过治理上限");if(await H.create({recursive:!0,exclusive:!1},a),!Oe(m.revisions,await v(_.scopeIds,_.namespace)))return!1;try{await L.create({recursive:!1,exclusive:!0},a)}catch(z){f(z),await L.stat(a)}return await L.write(j,a),u(),Oe(m.revisions,await v(_.scopeIds,_.namespace))}),invalidate:(m,A)=>h(async()=>{await p();const _=n.file(`${await jr([m,A??null])}.revision`);await I(_);try{await _.create({recursive:!1,exclusive:!0},a)}catch(j){f(j),await _.stat(a)}await _.write($r.encode(us()),a),u();try{const{entries:j}=await D();for(const H of j){if(A!==void 0&&H.entry.address.namespace!==A||!m.every((N,b)=>H.entry.address.scopeIds[b]===N))continue;const L=await v(H.entry.address.scopeIds,H.entry.address.namespace);Oe(H.entry.revisions,L)||await M(H)}await y()}catch(j){f(j),u()}})}}function Ur(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const xl="RATE_LIMITED_BY_RUNTIME",jl="RATE_LIMITED",Lc=20,Cc=40,Rc=150,Pc=20,kc=1e4,xc=45e3,jc=1,Ul=300*1e3,zl=64;function yt(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Hl(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Fl(e={}){const t=e.now??Date.now,r=Hl(e.coalesceWindowMs,Rc),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,yt(e.budget?.ratePerSecond,Lc)),burst:Math.max(1,Math.floor(yt(e.budget?.burst,Cc)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(yt(e.loopDetection?.maxCalls,Pc))),windowMs:Math.max(1,Math.floor(yt(e.loopDetection?.windowMs,kc)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(yt(e.circuitBreaker?.failureThreshold,jc))),openMs:Math.max(1,Math.floor(yt(e.circuitBreaker?.openMs,xc)))},s=new Map,a=new Map,c=new Set,d=new Map,l=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},f={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let u=!1;function h(M){try{e.onReport?.(M)}catch{}}function p(M,w){if(!i)return{exceeded:!1,count:0};const D=a.get(M)??[],y=w-i.windowMs;let O=0;for(;O<D.length&&D[O]<=y;)O+=1;O>0&&D.splice(0,O);const m=D.length>=i.maxCalls;return m||(D.push(w),D.length>i.maxCalls+1&&D.splice(0,D.length-(i.maxCalls+1))),a.set(M,D),{exceeded:m,count:D.length}}function E(M){if(!n)return!0;const w=Math.max(0,M-l.updatedAt)/1e3;return l.tokens=Math.min(n.burst,l.tokens+w*n.ratePerSecond),l.updatedAt=M,l.tokens<1?!1:(l.tokens-=1,!0)}function T(M){if(!n)return 0;const w=Math.max(0,M-l.updatedAt)/1e3,D=Math.min(n.burst,l.tokens+w*n.ratePerSecond);return Math.max(0,Math.ceil((1-D)/n.ratePerSecond*1e3))}function I(M,w,D,y,O){if(!o)return;const m=d.get(w),A=(m?.open?0:m?.failures??0)+1;if(A<o.failureThreshold){d.set(w,{open:!1,openedAt:0,openMs:0,failures:A});return}const _=Math.min(Math.max(o.openMs,y),Ul);d.set(w,{open:!0,openedAt:O,openMs:_,failures:A}),f.circuitOpened+=1,h({type:"circuit_opened",capability:M,endpointId:w,status:D,openMs:_,timestamp:O})}function v(M){const w=d.get(M);w&&!w.open&&d.delete(M)}function S(M){for(const[w,D]of s)!D.pending&&D.expiresAt<=M&&s.delete(w);for(;s.size>=zl;){const w=[...s].find(([,D])=>!D.pending);if(!w)break;s.delete(w[0])}}function P(M,w){if(M===void 0)return;const D=s.get(M);D?.promise===w&&(D.pending=!1)}function V(M,w){if(M===void 0)return;s.get(M)?.promise===w&&s.delete(M)}async function R(M){if(u)return M.load();const w=t();if(o){const m=d.get(M.endpointId);if(m?.open){const A=m.openedAt+m.openMs-w;if(A>0)throw f.circuitRejected+=1,h({type:"circuit_rejected",capability:M.capability,endpointId:M.endpointId,retryAfterMs:A,timestamp:w}),Gl("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:M.endpointId,retryAfterMs:A});d.delete(M.endpointId)}}const D=p(M.endpointId,w);D.exceeded&&i?c.has(M.endpointId)||(c.add(M.endpointId),h({type:"loop_detected",capability:M.capability,endpointId:M.endpointId,count:D.count,windowMs:i.windowMs,timestamp:w})):c.delete(M.endpointId);const y=r>0?M.coalesceKey:void 0;if(y!==void 0){const m=s.get(y);if(m&&(m.pending||m.expiresAt>w))return f.coalesced+=1,h({type:"coalesced",capability:M.capability,endpointId:M.endpointId,timestamp:w}),m.promise;m&&s.delete(y)}if(D.exceeded&&i)throw f.loopRejected+=1,fs("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:M.capability,endpointId:M.endpointId,count:D.count,windowMs:i.windowMs});if(!E(w)){f.budgetRejected+=1;const m=T(w);throw h({type:"budget_exhausted",capability:M.capability,endpointId:M.endpointId,retryAfterMs:m,timestamp:w}),fs("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:M.capability,endpointId:M.endpointId,retryAfterMs:m})}y!==void 0&&S(w);const O=M.load().then(m=>(P(y,O),v(M.endpointId),m),m=>{V(y,O);const A=Vl(m);throw A!==void 0&&I(M.capability,M.endpointId,A,Bl(m),w),m});return y!==void 0&&s.set(y,{endpointId:M.endpointId,promise:O,expiresAt:w+r,pending:!0}),O}return{execute:R,invalidateCoalescing(M){if(M===void 0){s.clear();return}for(const[w,D]of s)M.includes(D.endpointId)&&s.delete(w)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,M])=>M.open).map(([M])=>M)}},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function Vl(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 Bl(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 fs(e,t){return{code:xl,message:e,data:t}}function Gl(e,t){return{code:jl,message:e,data:t}}const Uc=3e4,zc=6e4,no=1440*60*1e3;function Ql(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??Uc)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??zc)):0,steamGameListTtlMs:t?Yl(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:Lc,burst:Cc},coalesceWindowMs:r?.coalesceWindowMs??Rc,loopDetection:r?.loopDetection??{maxCalls:Pc,windowMs:kc},circuitBreaker:r?.circuitBreaker??{failureThreshold:jc,openMs:xc}}}}function Yl(e){return e===void 0||!Number.isFinite(e)?no:Math.max(0,Math.floor(e))}function g(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function B(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ql(e){return typeof e=="object"&&e!==null}function de(e,t){const r=e.data;if(!ql(r)||typeof r.status!="string")throw new Error(t);return r}const Hc={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},$l={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 de(e,"工坊小程序详情加载失败")}};function br(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Wl(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Kl(e){const t=de(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=Wl(r.consent_challenge)),{...t,result:n}}const Jl={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=>({...br(e.runtimeContext),challenge:e.challenge}),parse:e=>de(e,"小程序授权取消接口响应异常")},Zl={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=>br(e.runtimeContext),parse:e=>de(e,"小程序授权撤销接口响应异常")},Xl={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=>br(e.runtimeContext),parse(e){const t=de(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}:{}}}}},ef={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=>({...br(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Kl(e)},tf={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=>({...br(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=de(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},rf=64;function Fc(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??rf)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(f){for(const[u,h]of i)h.expiresAt<=f&&i.delete(u)}function d(f,u,h){if(a||t<=0||h!==s)return;const p=n();for(c(p),i.delete(f);i.size>=r;){const E=i.keys().next();if(E.done)break;i.delete(E.value)}i.set(f,{expiresAt:p+t,value:u})}function l(f,u){if(a)return u();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 p=s,E=u().then(T=>(d(f,T,p),T)).finally(()=>{o.get(f)===E&&o.delete(f)});return o.set(f,E),E}return{read:l,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function nf(e,t){return t?e?"server":"local":"legacy"}function of(e,t){if(e==="local")throw g("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const sf=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],af=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),cf=/authorization|cookie|pkey|password|secret|token/i,Vc=/authorization|cookie|pkey|token|password|secret/i;function _e(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function df(e){for(const t of Object.keys(e))if(!af.has(t))throw new ae(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of sf)if(Object.prototype.hasOwnProperty.call(e,t)&&_e(e,t)!==void 0)throw new ae(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(_e(e,"bodyEncoding")!==void 0&&_e(e,"bodyEncoding")!=="json"&&_e(e,"bodyEncoding")!=="form")throw new ae("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(_e(e,"failurePresentation")!==void 0&&_e(e,"failurePresentation")!=="none")throw new ae("endpoint failurePresentation 必须为 none");if(_e(e,"auth")!==void 0&&_e(e,"auth")!=="none"&&_e(e,"auth")!=="optional"&&_e(e,"auth")!=="required")throw new ae("endpoint auth 必须为 none、optional 或 required")}function nr(e){if(Array.isArray(e))return e.map(nr);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))cf.test(n)||(r[n]=nr(i));return r}function hs(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Vc.test(r)||(t[r]=n);return t}function uf(e){if(!e)return;const t=Object.keys(e).find(r=>Vc.test(r));if(t)throw new ae(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Pt 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 ms=1440*60*1e3,lf=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function ff(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,ms):void 0}if(!lf.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,ms):void 0}function hf(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 Bc(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class kt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Bc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Or extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Bc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function mf(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:nr(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:hs(o),method:e.method,metadata:{endpointId:e.id},query:nr(n),timeout:e.timeout,url:r},data:nr(a.data),headers:hs(a.headers)||{},status:a.status,statusText:a.statusText}}async function si(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(df(t),typeof t.id!="string"||!t.id)throw new ae("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new ae("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new ae("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;uf(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 ae?h:new kt({endpointId:t.id,cause:h})}if(f.status<200||f.status>=300)throw new Pt({endpointId:t.id,status:f.status,retryAfterMs:ff(f.headers)});const u=mf(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(u,r)}catch(h){throw new Or({endpointId:t.id,cause:h})}return u.data},d=n.gate;if(!d)return c();const l=hf(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...l===void 0?{}:{coalesceKey:l},load:c})}const gf=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),pf=new Set(Rt),ko="steam_account",Gc=new Set(Rt.filter(e=>e!==ko)),yf=1e3;function Ef(e){const t=new Set,r=Fc({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??Uc))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??nf(e.networkEnabled===!0,c),l=e.requestPolicyEnabled!==!1,f=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function u(){if(!c&&!e.authorizationContext)return{};if(!e.authorizationContext)throw g("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let N;try{N=await e.authorizationContext.get(e.operationContext)}catch(C){throw oo(C)?yi(C.code,C.message,C):yi("REQUEST_FAILED","读取 Runtime auth context 失败",C)}if(N.steamAccount!==c||N.userDataMode!==d)throw g("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const b=N.token.trim();if(!b)throw g("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:b}}const h=e.account.onChange(N=>{if(p(),E("heybox_app_login_change",N?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),N&&e.account.getAccountKey){const b=i;V().then(C=>{!o&&i===b&&E("heybox_app_login_change",C)}).catch(()=>{})}});function p(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function E(N,b){N==="user_info_authorization_change"&&Df(b)&&r.invalidate();for(const C of t)try{C(N,b)}catch{}}function T(){const N=e.identity.get()?.miniProgramId?.trim();if(!N)throw g("INVALID_STATE","当前能力缺少 canonical 小程序身份");return N}function I(){if(o||e.operationContext.signal.aborted)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function v(){I();let N;try{N=await e.account.getCurrentUserId(e.operationContext)}catch(b){throw Es(b,e.operationContext.signal,"读取小黑盒账号失败")}return typeof N=="string"&&N.trim()?N.trim():void 0}async function S(N,b){const C=await v();if(i!==b||C!==N)throw g("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function P(N,b,C=T()){if(!e.account.getAccountKey)throw g("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let k;try{k=await e.account.getAccountKey(C,N,e.operationContext)}catch{throw I(),g("REQUEST_FAILED","读取本地账号标识失败")}if(await S(N,b),T()!==C)throw g("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof k!="string"||!k.trim())throw g("INVALID_RESPONSE","Host 返回了无效的账号标识");return k}async function V(){const N=T(),b=i,C=await v();if(I(),i!==b)throw g("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return C?{isHeyboxAppLoggedIn:!0,accountKey:await P(C,b,N)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function R(N){I();try{await e.account.ensureAuthenticated({trustedUserGesture:N,reason:"runtime_auth",signal:e.operationContext.signal})}catch(C){throw Es(C,e.operationContext.signal,"小黑盒登录失败")}const b=await v();if(!b)throw g("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return b}async function M(N,b,C=e.operationContext.signal){try{if(C.aborted)throw io();return await Nf(si(e.network,N,b,{...e.operationContext,credentials:"heybox-session",signal:C,...f?{gate:f}:{}}),C)}catch(k){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):k instanceof ae?g("REQUEST_UNSUPPORTED",k.message):k instanceof Or?g("INVALID_RESPONSE","授权接口响应不合法"):k instanceof kt?g("REQUEST_FAILED","授权请求失败"):k instanceof Pt?l&&(k.status===403||k.status===429)?g("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:k.status,...k.retryAfterMs===void 0?{}:{retryAfterMs:k.retryAfterMs}}):g("REQUEST_FAILED",k.message):oo(k)?k:g("REQUEST_FAILED","授权请求失败")}}async function w(N,b){await M(Jl,{runtimeContext:{miniProgramId:N,...await u()},challenge:b}).catch(()=>{})}function D(N){const b=async()=>{const k=ps(e.operationContext.signal);a=k;try{return await N(k.signal)}finally{a===k&&(a=void 0),k.abort()}},C=s.then(b,b);return s=C.then(()=>{},()=>{}),C}async function y(N,b,C,k,U){if(!C)throw await w(N,b.challenge),g("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await w(N,b.challenge),g("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return D(async z=>{await S(k,U);const F=await O(N,b.displayedScopes,z);await S(k,U);let G;try{G=await e.authPresentation.confirmAuthorization({miniProgramId:N,scopes:b.displayedScopes,...F,signal:z})}catch($){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await S(k,U),await w(N,b.challenge),yi("REQUEST_FAILED","授权确认界面执行失败",$))}if(await S(k,U),G.status!=="granted")throw await w(N,b.challenge),g("AUTHORIZATION_CANCELLED","用户取消授权");const re=Mf(G.grantedScopes,b.displayedScopes,c);if(!re.includes("identity"))throw await w(N,b.challenge),g("AUTHORIZATION_CANCELLED","用户拒绝授权");return re})}async function O(N,b,C){const k=ps(C),U=setTimeout(()=>k.abort(),yf);try{const z=Af(e.miniProgramPresentation),[F,G]=await Promise.all([z?Promise.resolve(z):m(N,k.signal),b.includes("profile")?A(k.signal):Promise.resolve(void 0)]);return{...F?{miniProgram:F}:{},...G?{userProfile:G}:{}}}finally{clearTimeout(U),k.abort()}}async function m(N,b){try{const C=e.identity.get()?.version?.trim(),k=await M($l,{mini_program_id:N,...C?{miniprogram_version:C}:{}},b),U=Et(k,"小程序公开资料"),z=Tt(U.name),F=Tt(U.icon_url);return z||F?{...z?{name:z}:{},...F?{avatarUrl:F}:{}}:void 0}catch{return}}async function A(N){try{const b=await M(Hc,void 0,N),C=Et(b,"账号基础信息"),k=Tt(C.display_username),U=Tt(C.display_avatar);return k||U?{...k?{nickname:k}:{},...U?{avatar:U}:{}}:void 0}catch{return}}async function _(N,b){if(of(d,"auth.login"),!c&&N.includes(ko))throw g("INVALID_PARAMS","auth.login 参数不合法");const C=T(),k=await R(b),U=i,z=await M(ef,{runtimeContext:{miniProgramId:C,...await u()},scopes:N});await S(k,U);const F=Et(z,"小程序登录"),G=ys(F,"loginCode"),re=ys(F,"consentChallenge");if(G===re)throw g("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let $;if(G)$=gs(F.loginCode,c);else{const Y=wf(F.consentChallenge,c),ue=await y(C,Y,b,k,U);await S(k,U);const Rr=await M(tf,{runtimeContext:{miniProgramId:C,...await u()},challenge:Y.challenge,selectedScopes:ue});if(await S(k,U),$=gs(Et(Rr,"小程序登录确认"),c),$.scopes.some(Bt=>!ue.includes(Bt)))throw g("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const Y of $.scopes)n.add(Y);r.invalidate();const J=e.account.getAccountKey?await P(k,U,C):void 0;return E("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...J===void 0?{}:{accountKey:J}}),E("user_info_authorization_change",Ei(n,c)),{...$,...J===void 0?{}:{accountKey:J}}}async function j(N,b){const C=i,k=await M(Xl,{runtimeContext:{miniProgramId:b,...await u()}});await S(N,C);const U=If(Et(k,"用户本地身份"),c);for(const z of c?Rt:Gc)n.add(z);return E("user_info_authorization_change",Ei(n,c)),U}function H(N){I();const b=T(),C=`${N}\0${b}\0${i}\0${c}`;return r.read(C,()=>j(N,b))}async function L(N){if(!N)throw g("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const b=T(),C=i,k=await v();if(!k)throw g("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const U=await M(Zl,{runtimeContext:{miniProgramId:b,...await u()}});await S(k,C),Et(U,"用户授权撤销"),p(),E("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:V,login:_,getOrCreateLocalIdentity:H,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Ei(n,c),revoke:L,onEvent(N){return t.add(N),()=>t.delete(N)},dispose(){o||(o=!0,p(),r.dispose(),h(),t.clear())}}}function yi(e,t,r){const n=g(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function Et(e,t){if(!B(e))throw g("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":gf.has(r)?r:"REQUEST_FAILED";throw g(n,r)}if(!B(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function gs(e,t){if(!B(e))throw g("INVALID_RESPONSE","login code 必须是对象");const r=Un(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!r.includes("identity"))throw g("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function wf(e,t){if(!B(e))throw g("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Un(e.requestedScopes,"challenge requestedScopes",t),n=Un(e.displayedScopes,"challenge displayedScopes",t);if(typeof e.challenge!="string"||!e.challenge.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!Number.isInteger(e.consentUiVersion)||Number(e.consentUiVersion)<0||!r.length||!r.includes("identity")||!n.length||!n.includes("identity")||r.some(i=>!n.includes(i)))throw g("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function If(e,t){if(!B(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw g("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw g("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const n=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return n?{appUserId:r,steamId:n}:{appUserId:r}}function Mf(e,t,r){const n=Un(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw g("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Tt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Af(e){const t=Tt(e?.name),r=Tt(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function ps(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 Nf(e,t){return t.aborted?Promise.reject(io()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(io()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function io(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Un(e,t,r){const n=r?pf:Gc;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw g("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Ei(e,t){const r=t?Rt:Rt.filter(n=>n!==ko);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function ys(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Df(e){return B(e)?Object.values(e).some(t=>t==="denied"):!1}function oo(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Es(e,t,r){return t.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):oo(e)?e:g("REQUEST_FAILED",r)}const Sf=new Set(Rt);function Tf(e){return{[an]:async t=>{if(t!==void 0)throw g("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[cn]:async(t,r)=>e.authorization.login(bf(t),r.trustedUserGesture)}}function bf(e){if(e===void 0)return["identity"];if(!B(e)||Object.keys(e).some(t=>t!=="scopes"))throw ws();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Sf.has(t))||new Set(e.scopes).size!==e.scopes.length)throw ws();return[...e.scopes]}function ws(){return g("INVALID_PARAMS","auth.login 参数不合法")}const Of={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 de(e,"排行榜记录删除接口响应异常")}},_f={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 de(e,"当前排行榜记录接口响应异常")}},vf={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 de(e,"排行榜信息接口响应异常")}},Lf={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 de(e,"排行榜列表接口响应异常")}},Cf={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 de(e,"排行榜提交接口响应异常")}};function Wr(){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:Wr()}function Is(e){return e instanceof ae?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function K(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Wr());let n;try{n=e()}catch(i){return Promise.reject(Is(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Wr())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(Wr()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(Is(d))))})}const Rf={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 Qc(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await K(()=>si(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(Hn(i)||Zt(i,"REQUEST_UNSUPPORTED")||Zt(i,"RATE_LIMITED")||Zt(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof ae)throw ne("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof kt&&Zt(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Pt){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw ne("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw ne("UNAUTHORIZED","当前用户未登录")}throw i instanceof kt||i instanceof Pt?zn(e.subject):i instanceof Or?X(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):X(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function xe(e,t,r){if(!ge(e)||typeof e.status!="string")throw X(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Pf(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw X(`${t} 响应缺少 result`);return e.result}function Yc(e,t){try{return e.onChange(t)}catch(r){if(Zt(r,Tc))return()=>{};throw r}}function Pf(e,t){if(e.status==="login"||e.status==="relogin")throw ne("UNAUTHORIZED",Jt(e.msg)||"当前用户未登录");const r=Ms(e.result)??Ms(e),n=Jt(r?.user_message)||Jt(e.msg)||Jt(r?.developer_message)||`${t}请求失败`;throw r?ne(kf(r),n,{status:e.status,sbe:r}):ne("HEYBOX_API_ERROR",n,{status:e.status})}function Ms(e){return ge(e)&&ge(e.sbe)?e.sbe:void 0}function kf(e){const t=Jt(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 Rf[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 ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Zt(e,t){return ge(e)&&e.code===t}function ne(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function X(e){return ne("INVALID_RESPONSE",e)}function zn(e){return ne("REQUEST_FAILED",`${e}请求失败`)}function Hn(e){return e instanceof Error&&e.name==="AbortError"}const xf="default",Ze="排行榜",jf=/^[A-Za-z0-9_-]{1,64}$/,Uf=300*1e3,zf=250,Hf=3;class Ff{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Yc(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(Cf,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=xe(i,je,Ze);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),wi(o,je)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=qt("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(Lf,{miniProgramId:r,...t}),s=xe(o,De,Ze);if(!ge(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw X(`${De} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw X(`${De} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>wi(a,De)),...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=qt("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(_f,{miniProgramId:n,...t}),c=xe(a,Qe,Ze);if(!ge(c))throw X(`${Qe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:wi(c.entry,Qe)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Of,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=xe(i,ct,Ze);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!ge(o)||typeof o.deleted!="boolean")throw X(`${ct} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",qt("info"),async()=>{const i=await this.request(vf,{miniProgramId:r,...t}),o=xe(i,Re,Ze);if(!ge(o)||typeof o.key!="string"||!jf.test(o.key))throw X(`${Re} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw X(`${Re} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw X(`${Re} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw X(`${Re} 返回的 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=qt(t,n),d=this.inflight.get(c);if(d)return d.promise;const l=this.accountGeneration,f=o?.generation,u=i().then(h=>(this.assertAccountGeneration(l),o&&s&&o.generation===f&&(r==="list"?s.size>=zf&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Uf,value:h})),h)).finally(()=>{this.inflight.get(c)?.promise===u&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:u}),u}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=Hf)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)As(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){As(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 Hn(n)?n:zn(Ze)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ne("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ne("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return qt(t,r??xf)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ne("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return Qc({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Ze,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 ne("INVALID_STATE","Cloud capability 已释放")}}function Vf(e){return new Ff(e)}function wi(e,t){if(!ge(e))throw X(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw X(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw X(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw X(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw X(`${t} 返回的 score 必须是有限数字`);if(!ge(e.extra))throw X(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw X(`${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 As(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function qt(...e){return JSON.stringify(e)}const Bf={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 de(e,"云端存储删除接口响应异常")}},Ns={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 de(e,"云端存储读取接口响应异常")}},Ds={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 de(e,"云端存储 key 列表接口响应异常")}},Gf={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:e.expectedVersion,expected_revision:e.expectedRevision}},parse(e,t){return de(e,"云端存储写入接口响应异常")}},Xe="云端存储",Qf=3e4,Yf=128,qf=500;class $f{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Yc(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=xe(await this.request(Ds,{}),dt,Xe);if(this.assertAccountGeneration(t),!ge(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw X("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"?qf: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=xe(await this.request(Bf,{key:t}),Ct,Xe);if(this.assertAccountGeneration(r.generation),!ge(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw X("删除结果不合法");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 X("云存储版本超出安全整数范围");const o=xe(await this.request(Gf,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),Lt,Xe);if(this.assertAccountGeneration(r.generation),!ge(o)||o.success!==!0)throw X("云存储写入结果不合法");const s=Ss({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw X("写入版本凭证不匹配");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(Ns,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=Ss(xe(c,vt,Xe));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>=Yf&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+Qf,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([Ns.id,Ds.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(ne("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(ne("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 Hn(o)?o:zn(Xe)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),ne("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),ne("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw ne("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ne("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ne("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw ne("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await K(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw Hn(s)?s:zn(Xe)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw ne("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return Qc({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Xe,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(W(this.options.operationContext.signal),this.disposed)throw ne("INVALID_STATE","Cloud capability 已释放")}}function Wf(e){return new $f(e)}function Ss(e){if(!ge(e))throw X("云存储读取结果必须是对象");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 X("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw X("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const Kf=/^[A-Za-z0-9_-]{1,64}$/,Ts=20,Jf=100,bs=2048,Zf=/^[A-Za-z0-9_-]{1,128}$/,Os=16*1024,Xf=new RegExp("[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]");function eh(e){const t=Vf(e),r=Wf(e);return{handlers:{[je]:async i=>t.submit(th(i)),[De]:async i=>t.getList(rh(i)),[Qe]:async i=>t.getCurrentUserEntry(Ii(i,Qe)),[ct]:async i=>t.deleteCurrentUserEntry(Ii(i,ct)),[Re]:async i=>t.getInfo(Ii(i,Re)),[vt]:async i=>r.getItem(_s(i,vt)),[Lt]:async i=>{const{key:o,value:s}=nh(i);return r.setItem(o,s)},[Ct]:async i=>r.removeItem(_s(i,Ct)),[dt]:async i=>(ih(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function th(e){const t=Ft(e,je,!1);if(Vt(t,["key","score","extra"],je),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{...xo(t.key,je),score:t.score,...t.extra===void 0?{}:{extra:oh(t.extra)}}}function rh(e){if(e===void 0)return{limit:Ts};const t=Ft(e,De,!0);Vt(t,["key","limit","cursor"],De);const r=t.limit===void 0?Ts:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>Jf)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{...xo(t.key,De),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Ii(e,t){if(e===void 0)return{};const r=Ft(e,t,!0);return Vt(r,["key"],t),xo(r.key,t)}function _s(e,t){const r=Ft(e,t,!1);return Vt(r,["key"],t),qc(r.key,t)}function nh(e){const t=Lt,r=Ft(e,t,!1);Vt(r,["key","value"],t);const n=qc(r.key,t);if(typeof r.value!="string")throw pe("INVALID_PARAMS",`${t} value 必须是字符串`);if(Xf.test(r.value))throw pe("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>Os)throw pe("INVALID_PARAMS",`${t} value 不能超过 ${Os} 字节`);return{key:n,value:r.value}}function ih(e){const t=Ft(e,dt,!0);Vt(t,[],dt)}function qc(e,t){if(typeof e!="string"||!Zf.test(e))throw pe("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function Ft(e,t,r){if(e===void 0&&r)return{};if(!$c(e))throw pe("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Vt(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw pe("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function xo(e,t){if(e===void 0)return{};if(typeof e!="string"||!Kf.test(e))throw pe("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function oh(e){if(!$c(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 $c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pe(e,t){return{code:e,message:t}}const sh=new Set(["stdio","attachments","notifications"]),Wc=new Set(["windows-x64","macos-arm64"]),ah=new Set(["unsigned","valid","invalid","unknown"]),ch=/^[a-f0-9]{64}$/,dh=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),uh=new Set(Dc),lh=new Set([...Dc,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Kc=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 fh(e){const t=async(n,i,o,s)=>{const a=hh(n);try{Ce(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Ce(i.signal),c}catch(c){throw ao(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw g("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>mh(d,i)).catch(d=>{throw ao(d)});Ce(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Ce(o.signal),c.status!=="granted")throw g("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[qn]:(n,i)=>t(n,i,async(o,s)=>so(await e.companion.getInfo(o,s),o)),[$n]:(n,i)=>t(n,i,async(o,s)=>vs(await e.companion.getPreparationStatus(o,s))),[Wn]:(n,i)=>t(n,i,async(o,s)=>{const a=vs(await e.companion.getPreparationStatus(o,s));return Ce(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Ce(i.signal),so(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(Zc(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[Kn]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Jn]:(n,i)=>t(n,i,async(o,s)=>Ls(await e.companion.getActiveSession(o,s),o)),[Zn]:(n,i)=>t(n,i,async(o,s)=>{const a=Ls(await e.companion.getActiveSession(o,s),o);return Ce(i.signal),a||(await r("launch",o,i),Ce(i.signal),Xc(await e.companion.launch(o,s),o))}),[Xn]:(n,i)=>wt(n,i,e,"write"),[ei]:(n,i)=>wt(n,i,e,"closeStdin"),[ti]:(n,i)=>wt(n,i,e,"terminate"),[ri]:(n,i)=>wt(n,i,e,"ackOutput"),[ni]:async(n,i)=>{const o=await wt(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[ii]:(n,i)=>wt(n,i,e,"showNotification")}}function hh(e){if(!B(e)||typeof e.alias!="string"||!Qu.test(e.alias))throw g("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Ce(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function wt(e,t,r,n){if(!B(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw g("INVALID_PARAMS","Companion Session controller 不合法");try{Ce(t.signal);const i=await r.companion[n](gh(e,n),{...r.operationContext,signal:t.signal});return Ce(t.signal),i}catch(i){throw ao(i)}}function be(){throw g("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Jc(e){return!Array.isArray(e)||e.some(t=>!sh.has(t))?be():Object.freeze([...new Set(e)])}function so(e,t){return!B(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Wc.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!ah.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?be():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Jc(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function mh(e,t){const r=so(e,t);return!B(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!ch.test(e.sha256)?be():Object.freeze({...r,sha256:e.sha256})}function Zc(e){return B(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}):be():be()}function vs(e){return B(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Zc(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&B(e.error)&&typeof e.error.code=="string"&&uh.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:Kc[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):be():be()}function Xc(e,t){return!B(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Wc.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?be():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Jc(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Ls(e,t){return e===void 0?void 0:Xc(e,t)}function gh(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Ic(r.data))throw g("INVALID_PARAMS","Companion write data 不合法");return{...n,data:new Uint8Array(r.data)}}if(t==="ackOutput"){if(r.stream!=="stdout"&&r.stream!=="stderr"||!Number.isSafeInteger(r.sequence)||Number(r.sequence)<0)throw g("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw g("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw g("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function ph(e){return!B(e)||!dh.has(String(e.reason))?be():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):be():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?be():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function yh(e){if(!B(e)||!B(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||!Ic(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:ph(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 ao(e,t){return B(e)&&typeof e.code=="string"&&lh.has(e.code)?g(e.code,Kc[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&B(e)&&e.name==="AbortError"?g(t,"Companion 准备已取消"):g("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Cs=5e3,Rs=1e4;function he(e){throw{code:"INVALID_PARAMS",message:e}}function jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ed(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&he(`${r} 不支持字段: ${n.join(", ")}`)}function Eh(e){if(e===void 0)return{intensity:"light",delay:0};if(!jo(e))return he("device.vibrate 参数必须是对象");ed(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return he("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Cs?he(`device.vibrate delay 必须是 0-${Cs} 的整数毫秒`):{intensity:r,delay:n}}function wh(e){return jo(e)?(ed(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?he("device.setClipboard text 必须是非空字符串"):e.text.length>Rs?he(`device.setClipboard text 不能超过 ${Rs} 字符`):{text:e.text}):he("device.setClipboard 参数必须是对象")}function Ih(e){return typeof e=="string"?e.trim()?e:he("device.executeProtocol 协议字符串不能为空"):jo(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?he("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(co(e,new Set),e):he("device.executeProtocol 参数必须是协议字符串或协议对象")}function co(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||he("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":he("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":he(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&he("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)co(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&he("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))co(i,t);t.delete(r)}function Mh(e){return{[Cn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.vibrate(Eh(t),e.operationContext),e.operationContext.signal)},[Rn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.setClipboard(wh(t),e.operationContext),e.operationContext.signal)},[Pn]:async(t,r)=>{const n=ut(e.operationContext,r.signal);W(n.signal);const i=Ih(t);await K(()=>e.protocol.invoke(i,n),n.signal)}}}const Ah=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"]),Nh={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 wr(e){const t=Uo(e),r=t&&Ah.has(t)?g(t,Nh[t]??"文件操作失败"):g("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function ke(e){try{return e()}catch(t){throw wr(t)}}function Uo(e){try{if(!B(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function td(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):uo,remove:o?s=>e.remove(s):nd,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):uo,stat:s=>e.stat(s)})}function rd(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=>td(e.file(a),n,{allowRemove:o}),directory:a=>rd(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):uo,remove:s?(a,c)=>e.remove(a,c):nd,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function uo(){return Promise.reject(g("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function nd(){return Promise.reject(g("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Ps=1024;class Dh{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareFile(t,r,n),[o]=this.registerMany([i]);return zr(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=ke(()=>{if(!Array.isArray(t))throw g("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw g("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>Ps)throw g("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw g("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>zr(a.handle,{kind:"file",handleId:s[c]}))}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[o]=this.registerMany([i]);return xs(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!oi(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Th(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Ir(r.relativePath),o=this.prepareFile(ke(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=bh(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==="."?".":Ir(r.relativePath),o=this.prepareDirectory(i==="."?n.hostHandle:ke(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Us(t),zr(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),ke(()=>{if(!Array.isArray(r))throw g("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw g("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw g("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,r[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return ke(()=>{if(B(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return zr(n.handle,ks(t.ref,n.handle.name))}if(B(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return xs(n.handle,Sh(t.ref,n.handle.name))}throw g("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=_r(r),i=this.prepareFile(ke(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:ks(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw g("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return ke(()=>{Us(t);const i=n??t.mode;return js(t.mode,i),{handle:td(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return ke(()=>{vh(t,i);const o=n??t.mode;return js(t.mode,o),{handle:rd(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Ps)throw g("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Oh();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw g("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!_h(t))throw g("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw g("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw g("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Te("files.sandbox");return this.prepareDirectory(ke(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw g("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Te("files")}}function Ir(e){if(!Co(e))throw g("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function _r(e,t="文件名"){const r=Ir(e);if(r.includes("/"))throw g("INVALID_PARAMS",`${t} 只能是 basename`);return r}function ks(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Ir(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Sh(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Ir(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function zr(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function xs(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function js(e,t){if(t==="readwrite"&&e!=="readwrite")throw g("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Th(e){return oi(e)||id(),e}function bh(e){return wc(e)||id(),e}function id(){throw g("INVALID_PARAMS","文件引用不合法")}function Oh(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw g("FILE_IO_FAILED","当前环境缺少安全随机数能力");const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function _h(e){return/^[0-9a-f]{32}$/.test(e)}function Us(e){if(!B(e)||e.kind!=="file"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.create!="function"||typeof e.read!="function"||typeof e.write!="function"||typeof e.stat!="function")throw g("FILE_IO_FAILED","Host 返回了无效 File handle");_r(e.name,"Host File name")}function vh(e,t=!1){if(!B(e)||e.kind!=="directory"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.file!="function"||typeof e.directory!="function"||typeof e.create!="function"||typeof e.stat!="function"||typeof e.list!="function")throw g("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw g("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&_r(e.name,"Host Directory name")}const zs=1e3,Lh=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function Ch(e){const t=r=>ut(e.operationContext,r.signal);return{files:{[In]:async(r,n)=>{Mi(n);const i=Ai(e.picker),o=Rh(r),s=await ye(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Mn]:async(r,n)=>{Mi(n);const i=Ai(e.picker),o=Ph(r),s=await ye(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[An]:async(r,n)=>{Mi(n);const i=Ai(e.picker),o=kh(r).suggestedName,s=t(n);if(!i.saveFile)throw Te("files.saveFile");const a=await ye(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[fr]:async(r,n)=>{const i=Ie(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);It(o.mode),await ye(()=>o.create(Hs(i),t(n)))},[hr]:async(r,n)=>{const i=Ie(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),It(o.handle.mode),!o.handle.remove)throw Te(hr);await ye(()=>o.handle.remove(t(n)))},[Nn]:async(r,n)=>{const i=Ie(r);return Fs(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!B(o)||o.kind!=="file")throw Bs()})},[mr]:async(r,n)=>{const i=Ie(r),o=Vs(await ye(()=>e.registry.resolveFile(i.target).read(t(n))));try{const s=new TextDecoder("utf-8",{fatal:!0}).decode(o);return s.charCodeAt(0)===65279?s.slice(1):s}catch{throw g("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Dn]:async(r,n)=>{const i=Ie(r,["content"]);typeof i.content!="string"&&Ae("content 必须是字符串");const o=e.registry.resolveFile(i.target);It(o.mode),await ye(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[gr]:async(r,n)=>{const i=Ie(r),o=await ye(()=>e.registry.resolveFile(i.target).read(t(n)));return Vs(o)},[Sn]:async(r,n)=>{const i=Ie(r,["content"]),o=e.registry.resolveFile(i.target);It(o.mode),await ye(()=>o.write(jh(i.content),t(n)))},[pr]:async(r,n)=>{const i=Ie(r),o=await ye(()=>e.registry.resolveFile(i.target).stat(t(n)));return Uh(o)}},directory:{[Tn]:async(r,n)=>{const i=Ie(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);It(o.mode),await ye(()=>o.create(Hs(i),t(n)))},[yr]:async(r,n)=>{const i=Ie(r,["recursive"]);if(B(i.target)&&i.target.relativePath===".")throw g("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),It(o.handle.mode),!o.handle.remove)throw Te(yr);await ye(()=>o.handle.remove({recursive:i.recursive===void 0?!1:Fn(i.recursive,"recursive")},t(n)))},[bn]:async(r,n)=>{const i=Ie(r);return Fs(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!B(o)||o.kind!=="directory")throw Bs()})},[On]:async(r,n)=>{const i=Ie(r,["limit"]),o=xh(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await ye(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function Rh(e){if(e===void 0)return{mode:"read",multiple:!1};B(e)||Ae("pickFiles 参数必须是对象"),ai(e,["mode","accept","multiple"]);const t=od(e.mode,"read"),r=e.multiple===void 0?!1:Fn(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)))&&Ae("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function Ph(e){return e===void 0?{mode:"read"}:(B(e)||Ae("pickDirectory 参数必须是对象"),ai(e,["mode"]),{mode:od(e.mode,"read")})}function kh(e){return B(e)||Ae("saveFile 参数必须是对象"),ai(e,["suggestedName"]),{suggestedName:_r(e.suggestedName,"suggestedName")}}function Ie(e,t=[]){return(!B(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Ae("文件操作参数必须包含 target"),ai(e,["target",...t]),e}function Hs(e){return{recursive:e.recursive===void 0?!1:Fn(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Fn(e.exclusive,"exclusive")}}function od(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&Ae("mode 必须是 read 或 readwrite"),e)}function Fn(e,t){return typeof e!="boolean"&&Ae(`${t} 必须是布尔值`),e}function xh(e){if(e===void 0)return zs;if((!Number.isSafeInteger(e)||e<=0)&&Ae("limit 必须是正整数"),e>zs)throw g("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function ai(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&Ae(`不支持字段: ${r.join(", ")}`)}function It(e){if(e!=="readwrite")throw g("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Mi(e){if(!e.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Ai(e){if(!e)throw Te("files.external");return e}async function Fs(e){try{return await e(),!0}catch(t){if(Lh.has(Uo(t)??""))return!1;throw wr(t)}}async function ye(e){try{return await e()}catch(t){throw wr(t)}}function jh(e){return e instanceof Uint8Array||Ae("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Ae("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Vs(e){if(!(e instanceof Uint8Array))throw g("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Bs(){return g("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Uh(e){if(!B(e)||e.kind!=="file"||!zh(e.size))throw g("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Hh(e[t]))throw g("FILE_IO_FAILED",`Host 返回了无效 ${t}`);return{kind:"file",size:e.size,...e.modifiedAt===void 0?{}:{modifiedAt:e.modifiedAt},...e.createdAt===void 0?{}:{createdAt:e.createdAt}}}function zh(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Hh(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Ae(e){throw g("INVALID_PARAMS",e)}const Hr=4294967296;function Fh(e){const t=new Vh;return t.write(e),t.finish()}class Vh{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<Hr?(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=Bh(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<Hr)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/Hr),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Hr)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Bh(e){const t=new Uint8Array(Gh(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 Gh(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 sd(e){lo(e);const t=Fh(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 lo(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)lo(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");lo(s,t+1,r)}r.delete(e)}const Qh=["pc","console","mobile"],Yh=["game","wiki"];function Vn(e){throw{code:"INVALID_PARAMS",message:e}}function qh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qe(e,t){return typeof e!="string"||!e.trim()?Vn(t):e.trim()}function Gs(e,t,r){return typeof e!="string"||!t.includes(e)?Vn(r):e}function $h(e){const t={target:"game_detail",appId:qe(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Gs(e.gameType,Qh,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Gs(e.page,Yh,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=qe(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=qe(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Wh(e){return{target:"user_detail",userId:qe(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Kh(e){const t={target:"post_detail",linkId:qe(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=qe(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=qe(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Jh(e){const t={target:"mini_program",miniProgramId:qe(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Zh(e){return qh(e)?e.target==="game_detail"?$h(e):e.target==="user_detail"?Wh(e):e.target==="post_detail"?Kh(e):e.target==="mini_program"?Jh(e):Vn("navigation.openAppPage target 不支持"):Vn("navigation.openAppPage options 必须是对象")}function Xh(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 em(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function tm(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 rm(e){const t=e;return t.target==="game_detail"?Xh(t):t.target==="user_detail"?em(t):tm(t)}const nm="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",im="data-hb-sdk-fullscreen-exit",om=3e3,sm=2e3,Qs="var(--white-70a,rgba(255,255,255,.7))",Ys="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function am(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(im,""),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 ${Qs}`,`box-shadow:${Ys}`,"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=nm,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 l(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function f(){o||(t.style.width=l())}function u(){d?.cancel(),d=void 0}function h(T=sm){clearTimeout(c),c=setTimeout(()=>{u(),o=!1,t.style.width=l(),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 p(){u(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Qs,t.style.boxShadow=Ys,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),h()}async function E(){if(!(s||a)){if(!o){p();return}a=!0,clearTimeout(c),u();try{await e()}catch{}finally{a=!1,s||p()}}}return t.addEventListener("click",E),window.addEventListener("resize",f),document.body.append(t),!r&&t.animate&&(d=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),h(om),{dispose(){s=!0,clearTimeout(c),u(),t.removeEventListener("click",E),window.removeEventListener("resize",f),t.remove()}}}const ad=1e4;function cd(e){const t=new AbortController;let r;const n=()=>{r??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},t.abort()};e.addEventListener("abort",n,{once:!0}),e.aborted&&n();const i=setTimeout(()=>{r??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},t.abort()},ad);return{signal:t.signal,async run(o){try{return await K(o,t.signal)}catch(s){throw r??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",n)}}}function dd(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 Ni(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Fr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function cm(e){let t,r,n={mode:"portrait",hideCapsule:!1},i={mode:"portrait",hideCapsule:!1},o;function s(){o?.dispose(),o=void 0}function a(u){if(!u.hideCapsule){s();return}o??=am(()=>f.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(u,h){if(t===u){if(t=void 0,clearTimeout(u.timer),e.operationContext.signal.removeEventListener("abort",d),"error"in h)u.controller.abort();else if(r={options:u.options,result:h.result},n=u.options,a(u.options),e.onApplied?.(u.options),h.result.supported&&!Ni(i,u.options)){i={...u.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:u.source})}catch{}}for(const p of u.subscribers)p.dispose(),"error"in h?p.reject(h.error):p.resolve(h.result);u.subscribers.clear()}}function d(){t&&c(t,{error:Fr()})}function l(u,h){return new Promise((p,E)=>{const T=()=>{u.subscribers.delete(I),I.dispose(),E(Fr()),u.subscribers.size===0&&c(u,{error:Fr()})},I={resolve:p,reject:E,dispose:()=>h?.removeEventListener("abort",T)};u.subscribers.add(I),h?.addEventListener("abort",T,{once:!0}),h?.aborted&&T()})}const f={async apply(u,h,p="api"){if(W(e.operationContext.signal),h?.aborted)throw Fr();const E=dd(u),T=t?.options??n,I={mode:E.orientation??T.mode,hideCapsule:E.fullscreen??T.hideCapsule};I.mode==="landscape"&&(I.hideCapsule=!0);const v=e.presentation.applyOrientation;if(!v)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&Ni(t.options,I))return l(t,h);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),r&&Ni(r.options,I))return r.result;r=void 0;const S={options:I,source:p,controller:new AbortController,subscribers:new Set};t=S;const P=l(S,h);return e.operationContext.signal.addEventListener("abort",d,{once:!0}),h||(S.timer=setTimeout(()=>{c(S,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},ad)),K(()=>v.call(e.presentation,I,{...e.operationContext,signal:S.controller.signal}),S.controller.signal).then(V=>c(S,{result:V??{supported:!0}}),V=>c(S,{error:V})),P},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return f}function ud(e){throw{code:"INVALID_PARAMS",message:e}}function qs(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&ud(`${t} 不支持参数`)}function dm(e){return{[kn]:async t=>{W(e.operationContext.signal),qs(t,"navigation.close"),await K(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[xn]:async t=>{W(e.operationContext.signal),qs(t,"navigation.reload"),await K(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[jn]:async(t,r)=>{const n=ut(e.operationContext,r?.signal);W(n.signal);const i=Zh(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=sd(i.extra)}catch{ud("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=cd(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(rm(i),n),n.signal)}}}const um=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),lm=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),fm=new Set(["range","if-range","a-im"]),hm=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"]),mm=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Vr={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class gm{constructor(t){this.signal=t}phase="initial";transition(t){if(Vr[t]<=Vr[this.phase])throw g("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Vr[this.phase]<Vr.committed&&this.signal.aborted)throw fd()}normalizeHostError(t,r){return this.throwIfCancelled(),Ho(t,r,this.signal)}}async function pm(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Te("network.download");const o=ut(r.operationContext,t.signal),s=new gm(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Im(e,i,o)}catch(l){throw s.normalizeHostError(l,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(l){throw s.normalizeHostError(l,"network")}let d=!1;try{s.throwIfCancelled(),s.transition("validate");const l=Am(c);Nm(c,l);const f=Dm(c.status,l);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw g("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const u=Mm(e,a,l,i);let h=0;const p=Em(f.expectedBytes,e.maxBytes);Si(t,Di(0,f));const E={...o,onProgress(v){!Number.isSafeInteger(v)||v<h||p!==void 0&&v>p||(h=v,Si(t,Di(h,f)))}};s.transition("transfer"),d=!0;let T;try{T=await n.files.writeResource(u.hostHandle,c.body,{mode:u.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...f.expectedBytes===void 0?{}:{expectedBytes:f.expectedBytes}},E)}catch(v){throw s.normalizeHostError(v,"transfer")}s.transition("committed"),h=ym(T,f,h,e.maxBytes),Si(t,Di(h,f));const I=i.describeFile(u.handle,u.ref);return s.transition("completed"),I}finally{d||wm(n.network,c.body)}}function ym(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 Em(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function wm(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Im(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return fo(i.handle.mode),await Lm(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return fo(n.handle.mode),await Cm(n.handle,r),{kind:"directory",...n}}function Mm(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Tm(e,r),o=n.deriveFile(t,i);return fo(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 g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!B(e.headers))throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!um.has(r)||!Array.isArray(n)||n.length===0)throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Nm(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw g("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:vm(t,lm)});if((t["content-range"]?.length??0)>0)throw g("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 g("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw g("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw g("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=Sm(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 Sm(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Di(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Si(e,t){try{e.postProgress(t)}catch{}}function Tm(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=bm(i);if(o&&Kr(o))return o}for(const i of r){const o=Om(i);if(o&&Kr(o))return o}if(e.suggestedName!==void 0)return zo(e.suggestedName);const n=_m(e.url);return n&&Kr(n)?n:"download.bin"}function bm(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 Om(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 _m(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function zo(e){try{_r(e,"suggestedName")}catch{throw g("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Kr(e))throw g("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Kr(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||mm.test(e))}function vm(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Lm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw ld()}catch(r){throw Ho(r,"file",t.signal)}}async function Cm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw ld()}catch(r){throw Ho(r,"file",t.signal)}}function fo(e){if(e!=="readwrite")throw g("FILE_ACCESS_DENIED","下载目标只允许读取")}const Rm={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 Ho(e,t,r){if(r.aborted)return fd();const n=Pm(e);if(n&&hm.has(n)){const o=g(n,Rm[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?g("DOWNLOAD_TIMEOUT","下载网络请求超时"):g("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?g("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):g("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function Pm(e){return B(e)&&typeof e.code=="string"?e.code:void 0}function ld(){return g("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function fd(){return g("DOWNLOAD_CANCELLED","下载已取消")}function km(e){if(!e)return;const t=Object.keys(e).find(r=>fm.has(r.trim().toLowerCase()));if(t)throw g("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const $s={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function xm(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw Te("network.upload");const o=ut(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw g("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(u){throw s(),wr(u)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw g("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw g("FILE_TOO_LARGE","文件超过大小限制");let d=0,l=!1;const f=u=>{l||o.signal.aborted||!Number.isSafeInteger(u)||u<d||u>c.size||(d=u,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:u,...h}=e,p=await n.upload(a,{...h,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:f});if(l=!0,!Number.isSafeInteger(p.uploadedBytes)||p.uploadedBytes<d||p.uploadedBytes>c.size)throw g("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(p.status>=200&&p.status<300&&p.uploadedBytes!==c.size)throw g("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:p.uploadedBytes,total:c.size,lengthComputable:!0}),p}catch(u){l=!0;const h=Uo(u);throw h&&$s[h]?g(h,$s[h]):o.signal.aborted?g("UPLOAD_CANCELLED","上传已取消"):h?.startsWith("FILE_")||h?.startsWith("DIRECTORY_")?wr(u):g("UPLOAD_NETWORK_FAILED","上传网络失败")}}const Fo="withCredentials",jm=new Set(["url","method","params","data","headers","timeout",Fo]),Um=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Fo]),zm=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Ws=3e4,ho=2*1024*1024,Hm=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,hd=/[\u0000-\u0008\u000A-\u001F\u007F]/,Fm=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Vm="network.request 不支持 multipart/form-data,请使用专用上传能力";function Bm(e){const t=Gm(e.runtimePermissions),r=ig(e.allowedHttpOrigins);return{[wn]:async(n,i)=>{const o=Ym(n,{permission:t,allowedHttpOrigins:r}),s=await xm(o,i,e),{uploadedBytes:a,...c}=s;return Js(c)},[En]:async(n,i)=>{const o=qm(n,{permission:t,allowedHttpOrigins:r});return pm(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[yn]:async(n,i)=>{const o=ut(e.operationContext,i?.signal);W(o.signal);const s=Qm(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await K(()=>e.network.request(s,o),o.signal)}catch(c){throw sg(c)?c:ag(c,"REQUEST_UNSUPPORTED")?Q("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):Q("REQUEST_FAILED","网络请求失败")}return Js(a)}}}function Gm(e){const t=Se(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Qm(e,t){const r=xt(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!jm.has(c));if(n.length>0)throw Q("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);md(r,"network.request");const i=Vo(r,t,"network.request"),o=Wm(r.method),s=r.data;s!==void 0&&Zm(s),eg(i.headers,s);const a=tg(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 Ym(e,t){const r=xt(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(l=>!n.has(l)))throw Q("INVALID_PARAMS","network.upload 包含不支持的字段");const i=Vo(r,t,"network.upload");if(i.official)throw Q("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw Q("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!oi(r.from))throw Q("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Q("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw Q("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw Q("INVALID_PARAMS","上传 HTTP 方法不支持");const s={from:r.from,format:r.format,request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"upload",method:o,...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}};if(r.format==="raw"){if(["fieldName","fields","fileName","contentType"].some(l=>r[l]!==void 0))throw Q("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(l=>l.toLowerCase()==="content-type"))throw Q("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=Ks(r.fieldName),c=r.fields===void 0?void 0:xt(r.fields,"fields 必须是字符串字典");for(const[l,f]of Object.entries(c??{}))if(Ks(l),typeof f!="string"||l===a)throw Q("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw Q("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||hd.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw Q("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:a,fields:c,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>ho)throw Q("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:zo(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function Ks(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw Q("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function qm(e,t){const r=xt(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!Um.has(c));if(n.length>0)throw Q("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);md(r,"network.download");const i=Vo(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw Q("INVALID_PARAMS","network.download timeout 必须是有限正数");km(i.headers);const o=oi(r.to),s=wc(r.to);if(!o&&!s)throw Q("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw Q("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw Q("INVALID_PARAMS","suggestedName 必须是字符串");a=zo(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw Q("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Q("INVALID_PARAMS","maxBytes 必须是正的 safe integer");return{request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"download",method:"GET",...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},url:i.url,to:r.to,targetKind:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function Vo(e,t,r){const n=$m(e.url,t.allowedHttpOrigins,r),i=Tl(n);if(i&&!t.permission.useOfficialDomain)throw Q("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(Sl(n.pathname,i))throw Q("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...xt(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Km(e.headers,r),timeout:Jm(e.timeout,r)}}function $m(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw Q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw Q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw Q("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw Q("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Wm(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw Q("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!zm.has(t))throw Q("INVALID_PARAMS","network.request method 不合法");return t}function Km(e,t="network.request"){const r=xt(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!Hm.test(s)||typeof o!="string"||hd.test(o))throw Q("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(bl(s))throw Q("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function md(e,t){const r=e[Fo];if(r!==void 0&&typeof r!="boolean")throw Q("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Jm(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw Q("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Ws)throw Q("INVALID_PARAMS",`${t} timeout 不能超过 ${Ws}ms`);return e}}function Zm(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw Q("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Xm(e)>ho)throw Q("INVALID_PARAMS",`network.request data 不能超过 ${ho} 字节`)}function Xm(e){if(typeof e=="string")return Ti(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return Ti(e.toString());try{const t=JSON.stringify(e);return t?Ti(t):0}catch{throw Q("INVALID_PARAMS","network.request data 必须可序列化")}}function eg(e,t){const r=gd(e),n=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(r?.includes("multipart/form-data")||n)throw Q("INVALID_PARAMS",Vm)}function tg(e,t,r){if(t===void 0)return;const n=gd(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)||ng(t))?"form":rg(t)?"json":void 0}function gd(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function rg(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function ng(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ig(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&&og(n.hostname)&&t.add(n.origin)}catch{}return t}function og(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 Js(e){return Object.keys(e.headers).some(Zs)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Zs(t)))}:e}function Zs(e){const t=e.trim().toLowerCase();return Fm.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function sg(e){return e instanceof Error&&e.name==="AbortError"}function ag(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function xt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Q("INVALID_PARAMS",t);return e}function Ti(e){return new TextEncoder().encode(e).length}function Q(e,t){return{code:e,message:t}}function cg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dg(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 ug(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=dg(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function lg(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 pd(e,t){if(e==null)return{};if(!cg(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=ug(e.topicIds),n=lg(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 fg(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function hg(e){try{if(fg(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function ce(e){throw{code:"INVALID_PARAMS",message:e}}function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mo(e,t){return typeof e!="string"||!e.trim()?ce(t):e}function mg(e,t){const r=mo(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?ce(t):r}catch{return ce(t)}}function gg(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function yd(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return ce(`${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 ce(`${t} 缺少有效的小程序分享地址`)}}function pg(e,t){if(!vr(e))return ce("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return ce("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!gg(r))return ce("share.showShareMenu channel 不合法");const n=Ed(e.extra,"share.showShareMenu");return{title:mo(e.title,"share.showShareMenu title 必须是非空字符串"),description:mo(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:yd(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:mg(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Ed(e,t){if(e!==void 0)try{return sd(e)}catch{return ce(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function wd(e,t){return e.invalidMessage&&await K(()=>hg(t.environment),t.operationContext.signal)?ce(e.invalidMessage):e.post}function Xs(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function yg(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Xs(t.windowWidth,0),height:Xs(t.windowHeight,0)}}function go(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?ce(t):r}function ea(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?ce(t):r}function Eg(e){return vr(e)?{left:go(e.left,"share.screenshot rect.left 必须是非负数字"),top:go(e.top,"share.screenshot rect.top 必须是非负数字"),width:ea(e.width,"share.screenshot rect.width 必须是正数"),height:ea(e.height,"share.screenshot rect.height 必须是正数")}:ce("share.screenshot rect 必须是对象")}function wg(e,t){if(e!=null&&!vr(e))return ce("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?ce("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?ce("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?yg(t):Eg(r.rect),...r.delay===void 0?{}:{delay:go(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function Ig(e,t){W(t.operationContext.signal);const r=pg(e,t);let n=pd(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await wd(n,t);return K(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function Mg(e,t){if(W(t.operationContext.signal),e!==void 0&&!vr(e))return ce("share.copyLink 参数必须是对象");const r=Ed(e?.extra,"share.copyLink"),n=yd(t,"share.copyLink",r);return await K(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Ag(e,t,r){W(t.operationContext.signal);const n=pd(vr(e)?e.post:void 0,{method:"share.screenshot"}),i=await wd(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=Ng(),{watermarkTheme:a,...c}=r;let d=!1,l,f;try{d=!0,await K(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),l=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{l?.()}const u=d?await Dg(t.presentation,s,t.operationContext.signal):void 0;if(f.status==="rejected")throw f.error;if(u)throw u;return f.value}function Ng(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Dg(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 Sg(e){let t=Promise.resolve();return{[fn]:(r,n)=>Mg(r,e),[hn]:(r,n)=>Ig(r,e),[mn]:async(r,n)=>{const i=ut(e.operationContext,n.signal);W(i.signal);const o=wg(r,e.presentation),s=t.then(()=>Ag(r,{...e,operationContext:i},o));return t=s.then(()=>{},()=>{}),K(()=>s,i.signal)}}}const ta=new WeakMap;function Id(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return rl(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${bc(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Md(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 l=await n();let f=ta.get(t);f||(f=new Map,ta.set(t,f));const u=f.get(l)??Promise.resolve(),h=async()=>(W(c.signal,{preserveReason:!0}),d(l)),p=u.catch(()=>{}).then(()=>e.lock?e.lock(l,h):h());f.set(l,p);try{return await p}finally{f.get(l)===p&&f.delete(l)}},o=async(c,d,l=!1)=>{const f=mt(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(p=>p.key.startsWith(f)&&p.value!=="").map(p=>p.key.slice(f.length)))];const u=await e.storage.getRaw(xr(c),d);if((u===void 0||u==="")&&!l)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let h;try{h=u?JSON.parse(u):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(h)||h.length>rs||h.some(p=>typeof p!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(p)))throw new Error("本地数据索引异常");return[...new Set(h)]},s=async(c,d)=>{if(e.diagnostics){const u=mt(c,"");return(await e.diagnostics.listRaw(d)).filter(h=>h.key.startsWith(u)&&h.value!=="").map(h=>({...h,key:h.key.slice(u.length)}))}const l=[],f=await o(c,d);for(let u=0;u<f.length;u+=16){W(d.signal,{preserveReason:!0});const h=await Promise.all(f.slice(u,u+16).map(async p=>{const E=await e.storage.getRaw(mt(c,p),d);return E!==void 0&&E!==""?{area:"local",key:p,value:E}:void 0}));for(const p of h)p&&l.push(p)}return l},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,l=>e.storage.getRaw(mt(l,c),d))},set(c,d,l){return a(c),i(l,async f=>{const u=await o(f,l,!0);if(!u.includes(c)&&u.length>=rs)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const h=[...new Set([...u,c])];await e.storage.setRaw(xr(f),JSON.stringify(h),l)}W(l.signal,{preserveReason:!0}),await e.storage.setRaw(mt(f,c),d,l),W(l.signal,{preserveReason:!0})})},list(c){return i(c,d=>s(d,c))},clear(c){return i(c,async d=>{const l=await o(d,c);e.diagnostics||await e.storage.setRaw(xr(d),JSON.stringify(l),c);for(let f=0;f<l.length;f+=16){W(c.signal,{preserveReason:!0});const h=(await Promise.allSettled(l.slice(f,f+16).map(p=>e.storage.setRaw(mt(d,p),"",c)))).find(p=>p.status==="rejected");if(h)throw h.reason}W(c.signal,{preserveReason:!0}),await e.storage.setRaw(xr(d),"[]",c)})}}}function Tg(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 bg=128,Og=/^[A-Za-z0-9_-]+$/;function _g(e){const t=e.scopedStorage??Md({storage:e.storage,resolveScope:()=>Id({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[ur]:async n=>{W(e.operationContext.signal);const i=ra(n,ur,e.storageLimits?.maxKeyLength),o=await K(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:na(o)}},[lr]:async n=>{W(e.operationContext.signal);const i=Ad(n,"storage.setStorage 参数必须是对象"),o=ra(i,lr,e.storageLimits?.maxKeyLength),s=vg(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"?ot("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:na(o),serializedValue:o,bytes:Nd(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function ra(e,t,r=bg){const i=Ad(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw ot("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!Og.test(i))throw ot("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function vg(e,t){let r;try{r=JSON.stringify(e)}catch{throw ot("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw ot("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Nd(r)>t)throw ot("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function na(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Ad(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw ot("INVALID_PARAMS",t);return e}function Nd(e){return new TextEncoder().encode(e).length}function ot(e,t){return{code:e,message:t}}const ia=120;function Be(e){throw{code:"INVALID_PARAMS",message:e}}function Bo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dd(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Be(`${r} 不支持字段: ${n.join(", ")}`)}function Lg(e){if(!Bo(e))return Be("ui.showToast 参数必须是对象");if(Dd(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Be("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>ia)return Be(`ui.showToast message 不能超过 ${ia} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Be("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function Cg(e){return e===void 0?{dismissible:!1}:Bo(e)?(Dd(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Be("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Be("ui.showLoading 参数必须是对象")}function Rg(e){e!==void 0&&(!Bo(e)||Object.keys(e).length)&&Be("ui.hideLoading 不支持参数")}function Pg(e){return{[_n]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.showToast(Lg(t),e.operationContext),e.operationContext.signal)},[vn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.showLoading(Cg(t),e.operationContext),e.operationContext.signal)},[Ln]:async t=>{W(e.operationContext.signal),Rg(t),await K(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const kg={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return de(e,"当前用户首页资料接口响应异常")}},xg=3e4;function jg(e,t,r={}){const n=r.ttlMs??xg,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 si(e,kg,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(u){throw t.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):u instanceof ae?g("REQUEST_UNSUPPORTED",u.message):u instanceof Or?g("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof kt?g("REQUEST_FAILED","user home_v2 请求失败"):u instanceof Pt?i&&(u.status===403||u.status===429)?g("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:u.status,...u.retryAfterMs===void 0?{}:{retryAfterMs:u.retryAfterMs}}):g("REQUEST_FAILED",u.message):zg(u)?u:g("REQUEST_FAILED","user home_v2 请求失败")}return Ug(f,"user home_v2")}function l(f){const u=Date.now();if(a?.userId===f&&a.expiresAt>u)return Promise.resolve(a.value);if(c?.userId===f&&c.generation===s)return c.promise;const h=s,p=d().then(E=>(s===h&&(a={userId:f,value:E,expiresAt:Date.now()+n}),E)).finally(()=>{c?.promise===p&&(c=void 0)});return c={userId:f,generation:h,promise:p},p}return{get:l,clear(){s+=1,a=void 0,c=void 0}}}function Ug(e,t){if(!B(e))throw g("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw g(n,r)}if(!B(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function zg(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Hg={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 de(e,"Steam 游戏库接口响应异常")}};function Fg(e,t=no){const r=_l({version:"2",validate:Bg}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):no,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 oa(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 Vg(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 Bg(e){if(!B(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 bt();for(const t of e.gameList){if(!B(t)||!po(t.appid)||!po(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw bt();for(const r of["image","portraitImage","icon"])Gg(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 bt()}return e}function po(e){return typeof e=="number"&&Number.isFinite(e)}function sa(e,t){if(e[t]!==void 0&&!po(e[t]))throw bt()}function Gg(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw bt()}function bt(){return g("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Sd=20,Qg=100,Yg=128,Td=0,bd="weeks",qg=100,$g=new Set(["weeks","all","achieved"]);function Wg(){return{nickname:"",avatar:""}}function Kg(e){const t=jg(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??vc(),i=Fg(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(w,D){const y=JSON.stringify([w,D]);return(!o||o.key!==y)&&(o={key:y,scope:n.createScope(D,n.createScope(w))}),o.scope}function d(){const w=o;o=void 0,w&&n.invalidateScope(w.scope).catch(()=>{}),s.clear()}const l=Fc({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??zc))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let u=0,h=!1;const p=e.account.onChange(()=>{u+=1,t.clear(),l.invalidate(),d()}),E=e.authorization.onEvent((w,D)=>{w==="user_info_authorization_change"&&Object.values(D).some(y=>y==="denied")&&(u+=1,t.clear(),l.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(I(),y.trim()))}).catch(()=>{}))});function T(){if(h||e.operationContext.signal.aborted)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function I(){const w=e.identity.get()?.miniProgramId?.trim();if(!w)throw g("INVALID_STATE","用户能力缺少 canonical 小程序身份");return w}async function v(){T(),await a,T();let w;try{w=await e.account.getCurrentUserId(e.operationContext)}catch(D){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):da(D)?D:g("REQUEST_FAILED","读取小黑盒账号失败")}return typeof w=="string"&&w.trim()?w.trim():void 0}async function S(w,D){const y=await v();if(u!==D||y!==w)throw g("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function P(w,D,y=e.operationContext.signal){try{return await si(e.network,w,D,{...e.operationContext,signal:y,credentials:"heybox-session",...f?{gate:f}:{}})}catch(O){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):O instanceof ae?g("REQUEST_UNSUPPORTED",O.message):O instanceof Or?g("INVALID_RESPONSE","用户接口响应不合法"):O instanceof kt?g("REQUEST_FAILED","用户请求失败"):O instanceof Pt?r&&(O.status===403||O.status===429)?g("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:O.status,...O.retryAfterMs===void 0?{}:{retryAfterMs:O.retryAfterMs}}):g("REQUEST_FAILED",O.message):da(O)?O:g("REQUEST_FAILED","用户请求失败")}}async function V(){I();const w=u,D=await v();if(!D)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[y,O]=await Promise.all([e.authorization.getOrCreateLocalIdentity(D),R(D).catch(()=>Wg())]);return await S(D,w),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:y.appUserId,profile:O,...y.steamId?{steam_id:y.steamId}:{}}}}function R(w){return l.read(w,()=>P(Hc,void 0).then(D=>{const y=aa(D,"账号基础信息");if(y.display_username!==void 0&&typeof y.display_username!="string")throw g("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(y.display_avatar!==void 0&&typeof y.display_avatar!="string")throw g("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:y.display_username??"",avatar:y.display_avatar??""}}))}async function M(w){const D=Jg(w),y=I(),O=u,m=await v();if(!m)return d(),{isLogin:!1,isBound:!1,data:null};const A=await t.get(m);await S(m,O);const _=Od(A.steam_id_info);if(Object.keys(_).length===0)return await n.invalidateScope(c(y,m)).catch(()=>{}),await S(m,O),s.delete(JSON.stringify([y,m])),{isLogin:!0,isBound:!1,data:null};const j=JSON.stringify([y,m]),H=c(y,m),L=oa({...D,steamId:void 0},_),N=_d(_.personal_infomation_open??_.personal_information_open),b=JSON.stringify([L??null,N??null]),C=s.get(j);C&&C.identity!==b&&(await n.invalidateScope(H).catch(()=>{}),await S(m,O));const k={identity:b,scope:n.createScope(b,H)};s.set(j,k);const U=oa(D,_),z=U?i.persistent:i.unresolved,F=n.createScope(U??"unresolved",k.scope),G=async()=>{if(await S(m,O),I()!==y||s.get(j)?.identity!==b)throw g("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},re=await z.read({scope:F,key:Vg({miniProgramId:y,userId:m,effectiveSteamId:U,personalInformationOpen:N,query:D}),signal:e.operationContext.signal,load:async $=>{const J=await P(Hg,{userId:m,...D,personalInformationOpen:N},$);return await G(),rp(aa(J,"Steam 游戏库"),D)}}).catch(async $=>{throw await G(),$});return await G(),{isLogin:!0,isBound:!0,data:re}}return{getInfo:V,getSteamGameList:M,async invalidateSteamGameListCache(){const w=I(),D=u,y=await v();if(!y)return;const O=c(w,y);await Promise.all([i.persistent.invalidateScope(O),i.unresolved.invalidateScope(O)]),t.clear(),s.delete(JSON.stringify([w,y])),await S(y,D)},dispose(){h||(h=!0,u+=1,p(),E(),t.clear(),l.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function Jg(e){if(e==null)return{limit:Sd,offset:Td,sort:bd,includeHidden:!1};if(!B(e))throw Ge("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Ge(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Zg(e.limit),offset:Xg(e.offset),sort:ep(e.sort),includeHidden:tp(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>Yg)throw Ge("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ge("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,qg))}return r}function Zg(e){if(e===void 0)return Sd;if(!Number.isInteger(e)||Number(e)<1)throw Ge("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Qg)}function Xg(e){if(e===void 0)return Td;if(!Number.isInteger(e)||Number(e)<0)throw Ge("user.getSteamGameList offset 必须是非负整数");return Number(e)}function ep(e){if(e===void 0)return bd;if(typeof e!="string"||!$g.has(e))throw Ge("user.getSteamGameList sort 不支持");return e}function tp(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ge("user.getSteamGameList includeHidden 必须是 boolean");return e}function rp(e,t){if(!Array.isArray(e.game_list))throw g("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(np).filter(a=>a!==void 0),n=Bn(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=_d(e.is_me);return s!==void 0&&(o.isMe=s),o}function np(e){const t=Od(e),r=Bn(t.appid),n=Bn(t.steam_appid)??r,i=Go(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};bi(o,"image",t.image),typeof t.vertical_head_image=="string"&&bi(o,"portraitImage",t.vertical_head_image),bi(o,"icon",t.appicon??t.icon),ca(o,"playtimeForever",t.playtime_forever),ca(o,"playtime2Weeks",t.playtime_2weeks);const s=ip(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function aa(e,t){if(!B(e))throw g("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw g(n,r)}if(!B(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Od(e){return B(e)?e:{}}function Go(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function ip(e){return Array.isArray(e)?e.map(Go).filter(Boolean):[]}function Bn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function _d(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function bi(e,t,r){const n=Go(r);n&&Object.assign(e,{[t]:n})}function ca(e,t,r){const n=Bn(r);n!==void 0&&Object.assign(e,{[t]:n})}function Ge(e){return g("INVALID_PARAMS",e)}function da(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}function op(e){return{[dn]:async t=>(ua(t,"user.getInfo"),e.user.getInfo()),[un]:async(t,r)=>{ua(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[ln]:async t=>e.user.getSteamGameList(t)}}function ua(e,t){if(e!==void 0)throw g("INVALID_PARAMS",`${t} 不接收入参`)}function la(e){throw{code:"INVALID_PARAMS",message:e}}function $t(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function vd(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Br(e,t,r){return Math.min(vd(e,t),r)}async function sp(e){try{return vd(await e.getNavigationBarHeight(),0)}catch{return 0}}function ap(e,t,r,n){const i=Br(e.safeArea?.left,0,t),o=Math.max(i,Br(e.safeArea?.right,t,t)),s=Br(e.safeArea?.top,n,r),a=Math.max(s,Br(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function fa(e){const t=e.getViewportMetrics(),r=$t(t.windowWidth,0),n=$t(t.windowHeight,0),i=await sp(e);return{pixelRatio:$t(t.pixelRatio,1),screenWidth:$t(t.screenWidth,r),screenHeight:$t(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:ap(t,r,n,i),screenTop:i}}function cp(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;fa(r.presentation).then(u=>{if(n||r.operationContext.signal.aborted||f!==i)return;const h=JSON.stringify(u);h!==o&&(o=h,r.onViewportChange?.(u))}).catch(()=>{})},c=cm({...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:{[at]:async(f,u)=>c.apply(f,u?.signal),[gn]:async()=>(W(r.operationContext.signal),fa(r.presentation)),[pn]:async f=>{if(W(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return la("viewport.setNavigationBarStyle 参数必须是对象");const u=f.foregroundStyle;if(u!=="light"&&u!=="dark")return la("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await K(()=>r.presentation.setNavigationBarStyle(u,e.operationContext),r.operationContext.signal)}},applyOrientation:(f,u)=>c.apply({orientation:f.mode,fullscreen:f.hideCapsule},u),notifyChange:()=>{o=void 0,a()},dispose:d}}const dp=new Map(Ye.map(e=>[e.method,e]));function Xt(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function up(e){const t=Yu(e);return r=>t(r.requirement,r.method)}function lp(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=l=>{a||(a=!0,n.removeEventListener("abort",d),l())},d=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",d,{once:!0}),i.then(l=>c(()=>o({status:"handled",value:l})),l=>c(()=>s(l)))})}function fp(e){const t=up(e.runtimePermissions),r=Se(e.runtimePermissions);let n=0,i=0,o=0;return{async dispatch(s,a,c){const d=e.now??hp,l=e.onTrace?d():0,f=e.onTrace?`cap_${++n}`:"",u=s===at?++i:void 0;let h;try{if(e.terminalSignal.aborted)throw Xt("RUNTIME_DESTROYED","小程序 Runtime 已终止");il(s,e.effectiveCapabilities);const p=dp.get(s);if(!p)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const E=t(p),T=!E.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!E.allowed&&!T)throw Xt(E.code,E.message,E.data);const I=e.handlers[s];if(!I)throw new Error(`Capability method ${s} 缺少 handler`);u!==void 0&&(h=cd(c.signal));const v=h?{...c,signal:h.signal}:c,S=async()=>{for(const V of e.policies??[]){const R=await V.evaluate({method:s,payload:a,capability:p});if(e.terminalSignal.aborted||h?.signal.aborted)throw ga();if(!R.allowed)throw Xt(R.code,R.message,R.data)}if(e.terminalSignal.aborted||h?.signal.aborted)throw ga();if(u!==void 0){if(dd(a),u<o)throw Xt("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=u}return I(a,v)},P=await lp(()=>h?h.run(S):S(),void 0,c,e.terminalSignal);return ha(e.onTrace,ma(f,s,a,l,P),d),P}catch(p){throw ha(e.onTrace,ma(f,s,a,l,{status:"error",error:p}),d),p}finally{h?.dispose()}}}}function hp(){return typeof performance>"u"?Date.now():performance.now()}function ha(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 ma(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:mp(i.error)}:{},...gp(t,r,i)}}function mp(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function gp(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"&&Ld(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 Ld(e){return typeof e=="object"&&e!==null}function ga(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function pp(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=Ql(e.requestPolicy);let n;if(e.files)try{n=kl(e.files,t)}catch{}const i=vc({store:n}),o=e.onRequestPolicyReport??(r.debugReport?yp:void 0),s=r.enabled?Fl({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Dh(e.files,e.miniProgramDetail),c=Ch({registry:a,picker:e.picker,operationContext:t}),d=Ef({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 l,f,u,h=()=>{},p=()=>{};try{l=cp({operationContext:t,presentation:e.hostPresentation,onDisplayChange:R=>e.eventSink.postEvent("display_change",R),onViewportChange:R=>e.eventSink.postEvent("viewport_change",R)}),f=Kg({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}),h=d.onEvent((R,M)=>e.eventSink.postEvent(R,M)),p=e.hostCompanion?.onSessionEvent?.(R=>{const M=yh(R);!e.terminalSignal.aborted&&M&&e.eventSink.postEvent(M.type,M.payload)})??(()=>{}),u=eh({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const E=_g({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),T=[{name:"auth",handlers:Tf({authorization:d})},{name:"user",handlers:op({user:f,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:Sg({prepareScreenshot:e.prepareScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:l.handlers},{name:"storage",handlers:E.handlers},{name:"network",handlers:Bm({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[sn]:async()=>{throw Xt("CAPABILITY_UNAVAILABLE","当前 Runtime 不支持工作区卡片刷新")}}},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"ui",handlers:Pg({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Mh({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:dm({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:R=>l.applyOrientation({mode:"portrait",hideCapsule:!1},R)}:{}})},{name:"cloud",handlers:u.handlers},{name:"companion",handlers:fh({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],I=Ep(T);let v=!1;const S=()=>{v||(v=!0,e.terminalSignal.removeEventListener("abort",S),l?.dispose(),u?.dispose(),h(),p(),f?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?S():e.terminalSignal.addEventListener("abort",S,{once:!0});const P=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:T,handlers:I,allowsCompanionAttachmentAccess:(R,M)=>P.has(R)&&Ld(M)&&a.isCompanionAttachmentRef(M.target),applyOrientation:l.applyOrientation,notifyViewportChange:l.notifyChange,...E.diagnostics?{storageDiagnostics:E.diagnostics}:{},dispose:S}}catch(E){throw l?.dispose(),u?.dispose(),h(),p(),f?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),E}}function yp(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Ep(e){const t=new Map(Ye.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=Ye.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Ye.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const wp="heybox-mini-dev:";function pa(e){try{return Ip(new URL(e))}catch{return!1}}function Ip(e){return e.protocol===wp}function Mp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Ap(e)}function Ap(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 Np=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Dp(e,t){const r=[],n=Sp(e.environmentInfo,r),i=Jr(n?.appVersion,"host.appVersion",r),o=bp(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:Tp(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:Jr(t.miniProgramId),version:Jr(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function Sp(e,t){if(e!=null){if(Cd(e))return e;t.push("environmentInfo")}}function Tp(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function bp(e,t){if(e==null)return{name:"unknown",version:null};if(!Cd(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=Np.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:Jr(e.version,"operatingSystem.version",t)}}function Jr(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Cd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Op="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxv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gMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function Cp(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:fixed;left:${r.left}px;top:${r.top+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const l=e.createElement("div");l.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 u=e.createElement("img");u.src=a?vp:Op,u.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 p=e.createElement("img");p.src=a?Lp:_p,p.style.cssText="width:12px;height:12px;flex-shrink:0;";const E=e.createElement("span");E.textContent=t?.trim()||"小程序工坊",E.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const 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(p,E),f.append(u,h),l.append(f,T),s.append(l),e.body.append(s);const I=()=>{s.remove(),n.removeEventListener("abort",I)};n.addEventListener("abort",I,{once:!0});try{return await K(()=>Promise.all([u.decode(),p.decode()]),n),await K(()=>new Promise(v=>{let S=o.requestAnimationFrame(()=>{S=o.requestAnimationFrame(()=>{n.removeEventListener("abort",P),v()})});const P=()=>o.cancelAnimationFrame(S);n.addEventListener("abort",P,{once:!0})}),n),I}catch(v){throw I(),v}}const Rp=1,Rd="allow-scripts allow-same-origin",Pp="",kp="no-referrer";function xp(e=Rd){return!e.split(/\s+/).includes("allow-same-origin")}function ya(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const jp=new Set(["javascript:","data:","blob:","file:"]),Ea="xiaoheihe.cn";function Up(e,t=window.location.href,r={}){const n=e.trim();if(!n)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(n)}catch{throw new Error("小程序链接必须是绝对 URL")}if(jp.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!Bp(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function zp(e,t){const r=new URL(e);return r.searchParams.set(vu,t),r.toString()}function Hp(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Fp(r)??Vp(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Fp(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Vp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function wa(e){const t=new URL(e);return Qo(t)?"loopback":Yo(t)?"lan":"production"}function Bp(e,t,r){return Gp(e)||Qo(e)||Yo(e)&&Yp(t,r)}function Gp(e){return e.protocol==="https:"&&Wp(e.hostname)}function Qo(e){return e.protocol==="http:"&&Qp(e.hostname)}function Qp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Yo(e){return e.protocol==="http:"&&qp(e.hostname)}function Yp(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Qo(r)||Yo(r)}catch{return!1}}function qp(e){const t=$p(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function $p(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 Wp(e){return e===Ea||e.endsWith(`.${Ea}`)}const Kp=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"]),Jp=new Set(["url","inline","eval","unknown"]),Zp=/^\/(?:\:segment(?:\/\:segment)*)?$/,Xp=/^[a-f0-9]{64}$/,ey=255,ty=160,ry=256;function ny(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!Kp.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>ry||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Jp.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=iy(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>ty||!Zp.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Xp.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 iy(e){if(e!==void 0&&!(typeof e!="string"||e.length>ey))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const oy=/^(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 sy(e){if(!e?.minimumSdkVersion)throw Z("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=rt(e.minimumSdkVersion),r=e.sdkVersion?rt(e.sdkVersion):void 0;if(!t)throw Z("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw Z("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=rt("0.6.0");if(!r){if(Zr(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw Z("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0)throw Z("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(Zr(r,t)<0)throw Z("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Zr(r,rt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function ay(e,t){if(typeof t!="string"||!rt(t))throw Z("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw Z("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function Pd(e,t){const r=rt(e),n=rt(t);if(!(!r||!n))return Zr(r,n)}function rt(e){const t=oy.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 Zr(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 ci=["android","ios","ohos","windows","macos","linux"],cy="0.9.0",dy=Object.freeze(["android","ios","ohos","windows","macos"]),kd="该小程序暂不支持当前平台",uy="PLATFORM_UNSUPPORTED";function ly(e){return typeof e=="string"&&ci.includes(e)}function fy(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 hy(e){const t=e.manifest;if(!Ey(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Ma(e.sdkVersion)??Ma(t.sdkVersion);return py(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:gy()}const r=xd(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function my(e){const t=fy(e.operatingSystemName);if(!t)return Nt("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Nt("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:ci,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=hy({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Nt("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):Ia(t,s)}if(r.effectivePlatforms===void 0)return Nt("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=xd(r.effectivePlatforms);if("reason"in n)return Nt("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=yy(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return Ia(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function Ia(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Nt("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Nt(e,t={}){return{status:"denied",reason:e,message:kd,...t}}function gy(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:dy,platformsDeclared:!1,policy:"legacy_mobile_default"}}function xd(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(!ly(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(ci.filter(r=>t.has(r)))}}function py(e){if(typeof e!="string"||!e.trim())return!1;const t=Pd(e.trim(),cy);return t!==void 0&&t>=0}function Ma(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function yy(e){return e==="explicit"||e==="legacy_mobile_default"}function Ey(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const wy=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 Iy(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:My(i.pathname),sanitizedPathnameHash:Ay(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function My(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function Ay(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 I=o[T-15],v=o[T-2],S=ve(I,7)^ve(I,18)^I>>>3,P=ve(v,17)^ve(v,19)^v>>>10;o[T]=o[T-16]+S+o[T-7]+P>>>0}let[c,d,l,f,u,h,p,E]=i;for(let T=0;T<64;T+=1){const I=E+(ve(u,6)^ve(u,11)^ve(u,25))+(u&h^~u&p)+wy[T]+o[T]>>>0,v=(ve(c,2)^ve(c,13)^ve(c,22))+(c&d^c&l^d&l);E=p,p=h,h=u,u=f+I>>>0,f=l,l=d,d=c,c=I+v>>>0}[c,d,l,f,u,h,p,E].forEach((T,I)=>{i[I]=i[I]+T>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ve(e,t){return e>>>t|e<<32-t}const Ny=1e4,Oi=2e3,Dy=2,Sy="open-with-native-credential-policy",jd="安全提示",Ud="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class Ty{nonce=ya();runtimeId=ya();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=_c(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??Ny,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??Z("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??Z("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(ky(),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=Z("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.armDocumentRevalidationTimer(this.documentRevalidationGeneration),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=qu(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=sy(t.sdkVersionPolicy);const n=Dp(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=my({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw Uy(this.platformGateDecision);if(this.miniProgramDetail=zy(t),this.effectiveCapabilities=Oc(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),vy(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(Cy(i)),this.launchUrl=i,this.miniProgramSrc=zp(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=Po(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:at,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,ze(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[at])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=pp({account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,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||(Pd(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):Cp(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=fp({handlers:this.capabilityGraph.handlers,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:l})=>{const f={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...l?{network:l}:{}};ze(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new Xu({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(Z("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 _y(t)?t:zd(Z("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 Up(t,r,{allowPrivateNetwork:pa(r)||Aa(r)||await this.isDevRuntime()})}catch(r){throw Z("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??Py)({message:Ud,title:jd,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(wa(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!pa(r)&&!Aa(r)}async closeAfterDevLaunchCancellation(){const t=Z("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{Na(),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(()=>Na())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Pp),this.iframe.setAttribute("referrerpolicy",kp),this.iframe.setAttribute("sandbox",Rd)}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(),ze(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(),ze(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{ay(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(Z("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>=Dy)){this.failRuntime(Z("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Pr,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},Oi),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Pr})}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),this.armDocumentRevalidationTimer(r),t.deferProbe||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.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(Pr,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Pr})}armDocumentRevalidationTimer(t){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(Z("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 文档再验证超时")))},Oi))}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()},Oi))}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===Cu){this.handleCspViolation(t.payload);return}if(t.method!==Lu)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(Z("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Hp(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(Z("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=ny(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){ze(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=Iy(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(Z("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:Rp,launchUrlType:wa(t),networkPolicy:Sy})}failRuntime(t){const r=by(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),ze(this.options.onError,Oy(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,ze(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){ze(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 by(e){const t=Po(e);return Gn(e)&&"cause"in e&&zd(t,e.cause),t}function zd(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function Oy(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function _y(e){return Gn(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Gn(e){return!!e&&typeof e=="object"}function ze(e,t){try{e?.(t)}catch{}}function vy(e,t,r){try{e?.(t,r)}catch{}}function Aa(e){try{const t=new URL(e);return t.protocol==="http:"&&Mp(t.hostname)}catch{return!1}}function Ly(e){try{return new URL(e).origin}catch{return}}function Cy(e){return xp()?"*":Ly(e)}function Ry(e){return`${jd}
|
|
1
|
+
import{H as ts,ax as fu,aY as hu,M as mu,aH as gu,aI as pu,aj as Tr,b6 as q,aa as yu,ak as lc,aq as Eu,b0 as wu,am as Iu,d as Mu,aE as fc,a8 as Au,at as hc,r as Nu,az as mc,o as Du,aD as Su,a5 as Tu,a_ as bu,aZ as Ou,c as _u}from"./desktop-app-launch-lns4avol.js";const sn="workspaceCards.requestRefresh",an="auth.getAccountState",cn="auth.login",dn="user.getInfo",un="user.revokeAuthorization",ln="user.getSteamGameList",fn="share.copyLink",hn="share.showShareMenu",mn="share.screenshot",at="viewport.setDisplay",gn="viewport.getWindowInfo",pn="viewport.setNavigationBarStyle",ur="storage.getStorage",lr="storage.setStorage",yn="network.request",En="network.download",wn="network.upload",In="files.pickFiles",Mn="files.pickDirectory",An="files.saveFile",fr="file.create",hr="file.remove",Nn="file.exists",mr="file.readText",Dn="file.writeText",gr="file.readBytes",Sn="file.writeBytes",pr="file.stat",Tn="directory.create",yr="directory.remove",bn="directory.exists",On="directory.list",_n="ui.showToast",vn="ui.showLoading",Ln="ui.hideLoading",Cn="device.vibrate",Rn="device.setClipboard",Pn="device.executeProtocol",kn="navigation.close",xn="navigation.reload",jn="navigation.openAppPage",je="cloud.leaderboard.submit",De="cloud.leaderboard.getList",Qe="cloud.leaderboard.getCurrentUserEntry",ct="cloud.leaderboard.deleteCurrentUserEntry",Re="cloud.leaderboard.getInfo",vt="cloud.storage.getStorage",Lt="cloud.storage.setStorage",Ct="cloud.storage.removeItem",dt="cloud.storage.getKeys",qn="companion.getInfo",$n="companion.getPreparationStatus",Wn="companion.prepare",Kn="companion.cancelPreparation",Jn="companion.getActiveSession",Zn="companion.launch",Xn="companion.session.write",ei="companion.session.closeStdin",ti="companion.session.terminate",ri="companion.session.ackOutput",ni="companion.openAttachment",ii="companion.showNotification",Ye=[{method:sn,module:"workspaceCards",capability:sn,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:an,module:"auth",capability:an,requirement:{kind:"none"},risk:"low"},{method:cn,module:"auth",capability:cn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:dn,module:"user",capability:dn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:un,module:"user",capability:un,requirement:{kind:"none"},risk:"high"},{method:ln,module:"user",capability:ln,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:fn,module:"share",capability:fn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:hn,module:"share",capability:hn,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:mn,module:"share",capability:mn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:gn,module:"viewport",capability:gn,requirement:{kind:"none"},risk:"low"},{method:pn,module:"viewport",capability:pn,requirement:{kind:"none"},risk:"low"},{method:at,module:"viewport",capability:at,requirement:{kind:"none"},risk:"low"},{method:ur,module:"storage",capability:ur,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:lr,module:"storage",capability:lr,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:yn,module:"network",capability:yn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:En,module:"network",capability:En,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:wn,module:"network",capability:wn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:In,module:"files",capability:In,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mn,module:"files",capability:Mn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:An,module:"files",capability:An,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:fr,module:"file",capability:fr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:hr,module:"file",capability:hr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Nn,module:"file",capability:Nn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:mr,module:"file",capability:mr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dn,module:"file",capability:Dn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:gr,module:"file",capability:gr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Sn,module:"file",capability:Sn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:pr,module:"file",capability:pr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Tn,module:"directory",capability:Tn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:yr,module:"directory",capability:yr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:bn,module:"directory",capability:bn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:On,module:"directory",capability:On,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_n,module:"ui",capability:_n,requirement:{kind:"none"},risk:"low"},{method:vn,module:"ui",capability:vn,requirement:{kind:"none"},risk:"low"},{method:Ln,module:"ui",capability:Ln,requirement:{kind:"none"},risk:"low"},{method:Cn,module:"device",capability:Cn,requirement:{kind:"none"},risk:"low"},{method:Rn,module:"device",capability:Rn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Pn,module:"device",capability:Pn,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:kn,module:"navigation",capability:kn,requirement:{kind:"none"},risk:"medium"},{method:xn,module:"navigation",capability:xn,requirement:{kind:"none"},risk:"medium"},{method:jn,module:"navigation",capability:jn,requirement:{kind:"none"},risk:"medium"},{method:je,module:"cloud",capability:je,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:De,module:"cloud",capability:De,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Qe,module:"cloud",capability:Qe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:ct,module:"cloud",capability:ct,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Re,module:"cloud",capability:Re,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:vt,module:"cloud",capability:vt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:Lt,module:"cloud",capability:Lt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Ct,module:"cloud",capability:Ct,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:dt,module:"cloud",capability:dt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[qn,$n,Wn,Kn,Jn,Zn,Xn,ei,ti,ri,ni,ii].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],et="heybox:miniprogram",gc=2,vu="hb_mini_bridge_nonce",pc="sdk.handshake",Pr="runtime.location.probe",Lu="sdk.location.report",Cu="sdk.csp.violation",yc="operation.progress",Ru="companion.session.output",Pu="companion.session.exit",ku="companion.session.ownershipLost";function xu(e){return!Je(e)||e.namespace!==et||e.version!==1&&e.version!==2||!fe(e.nonce)?!1:e.type==="handshake"?fe(e.id)&&e.method===pc&&e.error===void 0&&Hu(e.payload):e.type==="request"?fe(e.id)&&fe(e.method)&&e.error===void 0:e.type==="response"?fe(e.id)&&(e.method===void 0||fe(e.method))&&(e.error===void 0||Fu(e.error)):e.type==="event"?!fe(e.method)||e.error!==void 0?!1:e.method===yc?e.version===2&&fe(e.id)&&zu(e.payload):e.id===void 0||fe(e.id):e.type==="cancel"?e.version===2&&fe(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Co(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function Ec(e){return Je(e)?e.kind==="sandbox"?Ue(e,["kind"]):e.kind==="directory"&&fe(e.handleId)&&Ue(e,["kind","handleId"]):!1}function oi(e){return!Je(e)||e.kind!=="file"?!1:fe(e.handleId)?Ue(e,["kind","handleId"]):Ec(e.root)&&Co(e.relativePath)&&Ue(e,["kind","root","relativePath"])}function wc(e){return!Je(e)||e.kind!=="directory"?!1:fe(e.handleId)?Ue(e,["kind","handleId"]):Ec(e.root)&&(e.relativePath==="."||Co(e.relativePath))&&Ue(e,["kind","root","relativePath"])}function Ic(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function ju(e){return!Je(e)||!St(e.loaded)||typeof e.lengthComputable!="boolean"||!Ue(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?St(e.total)&&e.loaded<=e.total:e.total===void 0}function Uu(e){return Je(e)?e.phase==="downloading"?St(e.loaded)&&(e.total===void 0||St(e.total)&&e.loaded<=e.total)&&Ue(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:St(e.processed)&&St(e.total)&&e.processed<=e.total&&Ue(e,["phase","processed","total"]):!1}function zu(e){return ju(e)||Uu(e)}function Hu(e){return Je(e)&&fe(e.href)&&typeof e.userAgent=="string"&&fe(e.sdkVersion)}function Fu(e){return Je(e)&&fe(e.code)&&typeof e.message=="string"}function St(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function fe(e){return typeof e=="string"&&e.length>0}function Ue(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Er=["userInfo","steamLibrary","share","storage","cloud_storage","filesystem","clipboard","leaderboard","network","companion","appProtocol","workspaceCards"],Mc=[{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:"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(Er);const Vu=new Set(Er);function Bu(e){return Vu.has(e)}function Se(e){if(!kr(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(!kr(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),!!Bu(o)){if(o==="network"){const s=n.config;if(!kr(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&&(!kr(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 kr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const qr=["network","companion","appProtocol"];function Ac(e){if(!Gt(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>qr.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Gt(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(!Gt(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(!Gt(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Gt(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>qr.indexOf(n.key)-qr.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Gu(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Se(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of qr)!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 Ro(e){const t=Se(e.runtimePermissions),r=Ac(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of Er)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:Mc.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=Nc(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:Er.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function Nc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gt(e,t){return Nc(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Rt=["identity","profile","steam_account"],Qu=/^[a-z][a-z0-9-]{0,31}$/,Dc=["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"];Ye.map(e=>e.method);function Yu(e){const t=Se(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 qu(e){const t=Se(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 Z(e,t,r){return{code:e,message:t,data:r}}function Po(e){return $u(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?Z("RUNTIME_ERROR",e.message):Z("UNKNOWN_ERROR","小程序运行时异常",e)}function $u(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function Wu(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Ku=1e3;function Ju(e,t=Wu()){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<=Ku}const Zu="runtime.gate.probe",Sc=new Set(Ye.map(e=>e.method));class Xu{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=gc;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:et,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:et,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:et,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:et,version:2,nonce:this.nonce,type:"event",id:t,method:yc,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=Ju(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&&xu(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:et,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:pc,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===Zu){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,Z("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Sc.has(t.method)){this.postResponse(t,void 0,Z("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,Z("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=Po(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:et,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!el(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 el(e){return typeof e=="string"&&Sc.has(e)}const Tc="METHOD_FORBIDDEN";function Te(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Tc,t}class ae 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 tl=/^[A-Za-z0-9_-]{1,64}$/,rs=1e3;function bc(e){return tl.test(e)?e:nl(e)}function rl(e){return`id_${bc(e.trim())}`}function mt(e,t){return`hb_miniprogram_${e}_${t}`}function xr(e){return`hb_miniprogram_keys_${e}`}function nl(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 ns={[sn]:["workspaceCards.requestRefresh"],[an]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[cn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[dn]:["account.getCurrentUserId","account.onChange","network.request"],[un]:["account.getCurrentUserId","account.onChange","network.request"],[ln]:["account.getCurrentUserId","account.onChange","network.request"],[fn]:["presentation.setClipboard"],[hn]:["presentation.showShareMenu"],[mn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[at]:["presentation.applyOrientation"],[gn]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[pn]:["presentation.setNavigationBarStyle"],[ur]:["storage.getRaw"],[lr]:["storage.setRaw"],[yn]:["network.request"],[En]:["network.stream","files.transfer","files.access"],[wn]:["network.upload","files.access"],[In]:["files.external"],[Mn]:["files.external"],[An]:["files.save"],[fr]:["files.access"],[hr]:["files.removeFile"],[Nn]:["files.access"],[mr]:["files.access"],[Dn]:["files.access"],[gr]:["files.access"],[Sn]:["files.access"],[pr]:["files.access"],[Tn]:["files.access"],[yr]:["files.removeDirectory"],[bn]:["files.access"],[On]:["files.access"],[_n]:["presentation.showToast"],[vn]:["presentation.showLoading"],[Ln]:["presentation.hideLoading"],[Cn]:["presentation.vibrate"],[Rn]:["presentation.setClipboard"],[Pn]:["protocol.invoke"],[kn]:["presentation.close"],[xn]:["presentation.reload"],[jn]:["presentation.openAppPage"],[je]:["account.getCurrentUserId","account.onChange","network.request"],[De]:["account.onChange","network.request"],[Qe]:["account.getCurrentUserId","account.onChange","network.request"],[ct]:["account.getCurrentUserId","account.onChange","network.request"],[Re]:["account.onChange","network.request"],[vt]:["account.getCurrentUserId","account.onChange","network.request"],[Lt]:["account.getCurrentUserId","account.onChange","network.request"],[Ct]:["account.getCurrentUserId","account.onChange","network.request"],[dt]:["account.getCurrentUserId","account.onChange","network.request"],[qn]:["companion.getInfo"],[$n]:["companion.getPreparationStatus"],[Wn]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[Kn]:["companion.cancelPreparation"],[Jn]:["companion.getActiveSession"],[Zn]:["companion.getInfo","companion.launch"],[Xn]:["companion.session.write"],[ei]:["companion.session.closeStdin"],[ti]:["companion.session.terminate"],[ri]:["companion.session.ackOutput"],[ni]:["companion.openAttachment"],[ii]:["companion.showNotification"]};function il(e,t){if(t[e]!==!0)throw Te(e)}const ol=32*1024*1024,sl=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function al(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:ol},i);return cl(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function cl(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:dl(t,ll(e,"content-type"))}}function dl(e,t){ul(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new ae("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!sl.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function ul(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new ae(`Host network response 不支持 charset=${t}`)}function ll(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function x(e){return typeof e=="function"}function is(e){return(...t)=>{throw Te(e)}}function oe(e){return async(...t)=>{throw Te(e)}}const fl=(e,t)=>{},hl=()=>()=>{};function ml(e){const t={request:x(e.network?.request)?e.network.request.bind(e.network):oe("network.request")},r={...x(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:x(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):oe("account.getCurrentUserId"),ensureAuthenticated:x(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):oe("account.ensureAuthenticated"),onChange:x(e.account?.onChange)?e.account.onChange.bind(e.account):hl},n={getRaw:x(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):oe("storage.getRaw"),setRaw:x(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):oe("storage.setRaw")},i={...x(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...x(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:x(e.presentation?.close)?e.presentation.close.bind(e.presentation):oe("presentation.close"),reload:x(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):oe("presentation.reload"),openAppPage:x(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):oe("presentation.openAppPage"),openWindow:x(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):oe("presentation.openWindow"),getViewportMetrics:x(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):is("presentation.getViewportMetrics"),getNavigationBarHeight:x(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):is("presentation.getNavigationBarHeight"),setNavigationBarStyle:x(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):oe("presentation.setNavigationBarStyle"),showShareMenu:x(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):oe("presentation.showShareMenu"),setScreenshotChromeHidden:x(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):fl,captureAndShare:x(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):oe("presentation.captureAndShare"),showToast:x(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):oe("presentation.showToast"),showLoading:x(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):oe("presentation.showLoading"),hideLoading:x(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):oe("presentation.hideLoading"),vibrate:x(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):oe("presentation.vibrate"),setClipboard:x(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):oe("presentation.setClipboard")},o=x(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,x(e.companion?.[c])?e.companion[c].bind(e.companion):oe(`companion.${c}`)]));x(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const a={invoke:x(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):oe("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.transfer===void 0?{}:{transfer:e.transfer},...e.scopedStorage?{scopedStorage:e.scopedStorage}:{},...o?{storageDiagnostics:o}:{}}}function gl(e){const t=pl(e.files?.sandbox),r=x(e.picker?.pickFiles)&&x(e.picker?.pickDirectory),n=x(e.picker?.saveFile),i=t||r||n||x(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":x(e.account?.getAccountKey),"account.getCurrentUserId":x(e.account?.getCurrentUserId),"account.ensureAuthenticated":x(e.account?.ensureAuthenticated),"account.onChange":x(e.account?.onChange),"network.request":x(e.network?.request),"network.stream":x(e.transfer?.network.open)&&x(e.transfer?.network.release),"network.upload":x(e.transfer?.upload?.upload),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":x(o?.remove),"files.removeDirectory":x(e.files?.sandbox.remove),"files.transfer":x(e.transfer?.files.writeResource),"storage.getRaw":x(e.scopedStorage?.get)||x(e.storage?.getRaw),"storage.setRaw":x(e.scopedStorage?.set)||x(e.storage?.setRaw),"presentation.close":x(e.presentation?.close),"presentation.reload":x(e.presentation?.reload),"presentation.openAppPage":x(e.presentation?.openAppPage),"presentation.applyOrientation":x(e.presentation?.applyOrientation),"presentation.openWindow":x(e.presentation?.openWindow),"presentation.getViewportMetrics":x(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":x(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":x(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":x(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":x(e.presentation?.captureAndShare),"presentation.showToast":x(e.presentation?.showToast),"presentation.showLoading":x(e.presentation?.showLoading),"presentation.hideLoading":x(e.presentation?.hideLoading),"presentation.vibrate":x(e.presentation?.vibrate),"presentation.setClipboard":x(e.presentation?.setClipboard),"workspaceCards.requestRefresh":!1,"companion.getInfo":x(e.companion?.getInfo),"companion.getPreparationStatus":x(e.companion?.getPreparationStatus),"companion.prepare":x(e.companion?.prepare),"companion.cancelPreparation":x(e.companion?.cancelPreparation),"companion.getActiveSession":x(e.companion?.getActiveSession),"companion.launch":x(e.companion?.launch),"companion.session.write":x(e.companion?.write),"companion.session.closeStdin":x(e.companion?.closeStdin),"companion.session.terminate":x(e.companion?.terminate),"companion.session.ackOutput":x(e.companion?.ackOutput),"companion.openAttachment":x(e.companion?.openAttachment),"companion.showNotification":x(e.companion?.showNotification),"protocol.invoke":x(e.protocol?.invoke)}}function pl(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&x(t.file)&&x(t.directory)&&x(t.create)&&x(t.stat)&&x(t.list)}function os(e,t){return t?.[e]!==!1}function yl(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("companion.")}function Oc(e,t={}){const r={};for(const n of Object.keys(ns)){const o=ns[n].every(a=>e[a]),s=!yl(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=os(n,t.callerCapabilities)&&os(n,t.hostCapabilities)&&o&&s}return r}function _c(e={},t={}){const r=gl(e),n=Oc(r,t);return{ports:ml(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function ut(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):El(e.signal,t);return{...e,signal:r}}function El(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 wl(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 Il=4,Ml=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Al=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),Nl=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Dl=["/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 Sl(e,t){const r=Ol(e);return r===null||ss(r,Nl)?!0:t&&ss(r,Dl)}function Tl(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Ml.some(r=>t===r||t.endsWith(`.${r}`))}function bl(e){const t=e.trim().toLowerCase();return Al.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Ol(e){let t=e;for(let r=0;r<Il;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return as(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return as(t)}function ss(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function as(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function gt(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function cs(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function vc(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,o=new Map,s=new Set,a=new Set;let c=!1;function d(E,T){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:E,type:T})).catch(()=>{})}catch{}}function l(E){const T=r.get(E);if(!T)throw new Error("Unknown runtime cache scope");return T}function f(E,T){return E.flatMap((I,v)=>{const S=JSON.stringify(E.slice(0,v+1));return[JSON.stringify([S]),JSON.stringify([S,T])]})}function u(E,T){return JSON.stringify(f(E,T).map(I=>n.get(I)??0))}async function h(E,T){const I=l(E),v=JSON.stringify([JSON.stringify(I),...T?[T]:[]]),S=(n.get(v)??0)+1;n.set(v,S),i.add(v);for(const P of a)P(I,T);if(!e.store){i.delete(v),d(T??"*","invalidation");return}try{await e.store.invalidate(I,T)}catch(P){throw d(T??"*","storage_error"),P}n.get(v)===S&&i.delete(v),d(T??"*","invalidation")}function p(E){if(c)throw new Error("Runtime cache manager disposed");const T=o.get(E.namespace);if(T){if(T.sourceCodec!==E.codec||T.definition.codec.version!==E.codec.version||JSON.stringify(T.definition.policy)!==JSON.stringify(E.policy))throw new Error("Conflicting runtime cache namespace");return T.cache}if(!E.namespace||!E.codec.version)throw new Error("Invalid runtime cache definition");const I=Object.freeze({...E.policy}),v=Object.freeze({version:E.codec.version,encode:E.codec.encode.bind(E.codec),decode:E.codec.decode.bind(E.codec),validate:E.codec.validate.bind(E.codec),clone:E.codec.clone.bind(E.codec)}),S=E.namespace;for(const L of[I.ttlMs,I.memoryMaxEntries,I.diskMaxEntries,I.diskMaxBytes,I.maxEntryBytes])if(!Number.isFinite(L)||L<0)throw new Error("Invalid runtime cache policy");const P=new Map,V=new Map,R=new Map;let M=!1;function w(L,N,b){if(c||M||L.aborted||u(N,S)!==b)throw gt()}function D(L){return I.ttlMs>0&&I.persistence==="memory-and-disk"&&!!e.store&&!f(L,S).some(N=>i.has(N))}function y(L,N,b){const C=t();return L.envelopeVersion===1&&JSON.stringify(L.address)===JSON.stringify(N)&&cs(L.revisions,b)&&L.payload.byteLength<=I.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+I.ttlMs)>C}function O(L,N,b,C,k){if(!(I.ttlMs<=0||I.memoryMaxEntries<1)){for(const[U,z]of P)Math.min(z.entry.expiresAt,z.entry.cachedAt+I.ttlMs)<=t()&&P.delete(U);for(P.delete(L);P.size>=Math.floor(I.memoryMaxEntries);){const U=P.keys().next();if(U.done)break;P.delete(U.value)}P.set(L,{entry:N,value:b,epoch:C,persistent:k})}}async function m(L,N,b,C){const k={namespace:S,codecVersion:v.version,scopeIds:N,key:L.key},U=JSON.stringify(k);let z=[],F=D(N);if(F)try{z=await e.store.readRevisions(N,S)}catch{F=!1,d(S,"storage_error")}w(C.signal,N,b);async function G(){if(!F)return!0;try{return cs(z,await e.store.readRevisions(N,S))}catch{return F=!1,d(S,"storage_error"),!1}}const re=P.get(U);if(I.ttlMs>0&&re&&re.epoch===b&&y(re.entry,k,z)&&re.persistent===F&&await G())return w(C.signal,N,b),d(S,"memory_hit"),re.value;if(P.delete(U),F){let Y,ue;try{Y=await e.store.read(k,I.maxEntryBytes),Y&&y(Y,k,z)?ue=v.decode(Y.payload):Y=void 0}catch{Y=void 0,d(S,"storage_error")}if(w(C.signal,N,b),Y&&await G())return w(C.signal,N,b),O(U,Y,ue,b,!0),d(S,"disk_hit"),ue}d(S,"miss");const $=v.validate(await L.load(C.signal));w(C.signal,N,b);const J=v.clone($);if(!await G()&&F)throw gt();if(w(C.signal,N,b),I.ttlMs>0){const Y=t();let ue;try{ue=v.encode(J)}catch{return J}const Rr={envelopeVersion:1,address:k,revisions:F?z:[],cachedAt:Y,expiresAt:Y+I.ttlMs,payload:ue};if(F&&ue.byteLength<=I.maxEntryBytes){let Bt=!0,es=!1;try{Bt=await e.store.publish(Rr,I),es=Bt}catch{d(S,"storage_error")}if(w(C.signal,N,b),!Bt)throw gt();es&&d(S,"published")}w(C.signal,N,b),O(U,Rr,J,b,F)}return J}async function A(L){if(c||M||L.signal?.aborted)return Promise.reject(gt());const N=l(L.scope),b=u(N,S);let C;if(D(N)){const F=new AbortController;R.set(F,N);const G=()=>F.abort();L.signal?.addEventListener("abort",G,{once:!0});let re=()=>{};try{C=await Promise.race([e.store.readRevisions(N,S),new Promise(($,J)=>{const Y=()=>J(gt());F.signal.addEventListener("abort",Y,{once:!0}),re=()=>F.signal.removeEventListener("abort",Y)})])}catch{F.signal.aborted||d(S,"storage_error")}finally{re(),R.delete(F),L.signal?.removeEventListener("abort",G)}}w(L.signal??new AbortController().signal,N,b);const k=JSON.stringify([N,L.key,b,C]);let U=V.get(k);if(U?.controller.signal.aborted&&(U=void 0),!U){const F=new AbortController;U={ids:N,controller:F,waiters:0,promise:Promise.resolve(void 0)};const G=U;G.promise=m(L,N,b,F).finally(()=>{V.get(k)===G&&V.delete(k)}),V.set(k,G)}const z=U;return z.waiters+=1,new Promise((F,G)=>{let re=!1;function $(Y){re||(re=!0,L.signal?.removeEventListener("abort",J),z.controller.signal.removeEventListener("abort",J),z.waiters-=1,z.waiters===0&&z.controller.abort(),Y())}function J(){$(()=>G(gt()))}L.signal?.addEventListener("abort",J,{once:!0}),z.controller.signal.addEventListener("abort",J,{once:!0}),z.promise.then(Y=>$(()=>{try{w(L.signal??new AbortController().signal,N,b),F(v.clone(Y))}catch(ue){G(ue)}}),Y=>$(()=>G(Y)))})}function _(L,N){if(N&&N!==S)return;const b=C=>L.every((k,U)=>C[U]===k);for(const[C,k]of P)b(k.entry.address.scopeIds)&&P.delete(C);for(const[C,k]of V)b(k.ids)&&(k.controller.abort(),V.delete(C));for(const[C,k]of R)b(k)&&C.abort()}function j(){if(!M){M=!0,P.clear();for(const L of R.keys())L.abort();R.clear();for(const L of V.values())L.controller.abort();V.clear(),s.delete(j),a.delete(_),o.get(S)?.cache===H&&o.delete(S)}}const H={read:A,invalidateScope:L=>h(L,S),dispose:j};return s.add(j),a.add(_),o.set(S,{definition:{namespace:S,codec:v,policy:I},sourceCodec:E.codec,cache:H}),H}return{createScope(E,T){if(c||!E)throw new Error("Invalid runtime cache scope");const I=Object.freeze({});return r.set(I,[...T?l(T):[],E]),I},register:p,invalidateScope:E=>h(E),dispose(){if(!c){c=!0;for(const E of[...s])E();o.clear(),n.clear(),i.clear()}}}}function _l(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 vl=".hb-runtime-cache-v1",Ll=1e3,pi=64*1024,pt=1e3,Cl=2048,Qt=32*1024*1024,Rl=1024,$r=new TextEncoder,ds=new TextDecoder("utf-8",{fatal:!0});function Yt(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function jr(e){const t=await globalThis.crypto.subtle.digest("SHA-256",$r.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Oe(e,t){return JSON.stringify(e)===JSON.stringify(t)}function us(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function Pl(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function ls(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function kl(e,t){const r=e.sandbox.directory(vl),n=r.directory("revisions"),i=r.directory("entries");for(const m of[r,n,i,i.directory("capability-check")])ls(m,["directory","file","create","stat","list","remove"]),ls(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 l(m){d=m,o.abort(),t.signal.removeEventListener("abort",s)}function f(m){if(Pl(m))throw l(m),m}function u(){if(d)throw d;if(a.signal.aborted)throw Yt()}function h(m,A=a.signal){const _=c.then(()=>{if(A.aborted)throw d??Yt();return u(),m()},()=>{if(A.aborted)throw d??Yt();return u(),m()}).catch(N=>{throw f(N),N});if(c=_.catch(()=>{}),A.aborted)return Promise.reject(d??Yt());let j=()=>{};const H=new Promise((N,b)=>{const C=()=>b(d??Yt());A.addEventListener("abort",C,{once:!0}),j=()=>A.removeEventListener("abort",C)}),L=setTimeout(()=>{l(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},Ll);return Promise.race([_,H]).finally(()=>{clearTimeout(L),j()})}async function p(){u(),await n.create({recursive:!0,exclusive:!1},a),u(),await i.create({recursive:!0,exclusive:!1},a),u()}async function E(m,A){const _=n.file(`${await jr([m,A??null])}.revision`);await I(_);let j=!1;try{await _.create({recursive:!1,exclusive:!0},a),j=!0}catch(N){f(N),u()}if(j){const N=us();return await _.write($r.encode(N),a),u(),N}const H=await _.stat(a);if(H.size<1||H.size>128)throw new Error("缓存 revision 文件损坏");const L=ds.decode(await _.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(L))throw new Error("缓存 revision 文件损坏");return u(),L}async function T(m){const A=await m.list({limit:pt},a);if(A.length>=pt)throw new Error("缓存目录超过治理上限");return A}async function I(m){try{await m.stat(a);return}catch(_){if(!Ur(_))throw _}if((await T(n)).length>=pt-1)throw new Error("缓存 metadata 超过治理上限")}async function v(m,A){await p();const _=[];for(let j=0;j<m.length;j+=1){const H=m.slice(0,j+1);_.push(await E(H),await E(H,A))}return _}async function S(m){return r.directory(`entries/${await jr([m.namespace,m.codecVersion,m.scopeIds])}`)}async function P(m){return(await S(m)).file(`${await jr(m.key)}.cache`)}async function V(m,A){const _=await m.stat(a);if(_.size<5||_.size>A+pi+4)throw new Error("缓存条目超过大小限制");const j=await m.read(a);if(u(),j.length!==_.size)throw new Error("缓存条目读取不完整");const H=new DataView(j.buffer,j.byteOffset,j.byteLength).getUint32(0);if(H<1||H>pi||H+4>j.length)throw new Error("缓存信封损坏");const L=JSON.parse(ds.decode(j.subarray(4,H+4))),N=j.slice(H+4);if(L.envelopeVersion!==1||!L.address||!Array.isArray(L.address.scopeIds)||!L.address.scopeIds.every(b=>typeof b=="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(b=>typeof b=="string"&&b.length>0)||!Number.isSafeInteger(L.cachedAt)||!Number.isSafeInteger(L.expiresAt)||L.cachedAt<0||L.expiresAt<=L.cachedAt||L.payloadBytes!==N.length||N.length>A)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:L.address,revisions:L.revisions,cachedAt:L.cachedAt,expiresAt:L.expiresAt,payload:N}}async function R(m){if(!m.remove)throw new Error("Host 不支持缓存文件删除");await m.remove(a)}async function M(m){try{if((await m.file.stat(a)).size!==m.size)return!1;const A=await V(m.file,Qt);return!Oe(A.address,m.entry.address)||!Oe(A.revisions,m.entry.revisions)||A.cachedAt!==m.entry.cachedAt||A.expiresAt!==m.entry.expiresAt||!Oe(await w(A.payload),await w(m.entry.payload))?!1:(await R(m.file),!0)}catch(A){if(Ur(A))return!0;throw A}}async function w(m){const A=await globalThis.crypto.subtle.digest("SHA-256",m);return Array.from(new Uint8Array(A),_=>_.toString(16).padStart(2,"0")).join("")}async function D(){const m=await T(n);let A=0;for(const L of m)if(L.kind==="file"&&(A+=(await L.stat(a)).size,A>Qt))throw new Error("缓存扫描超过字节上限");const _=[];let j=0,H=A;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"||++j>Cl)throw new Error("缓存文件超过治理上限");const b=(await N.stat(a)).size;if(H+=b,H>Qt)throw new Error("缓存扫描超过字节上限");try{const C=await V(N,Qt);_.push({file:N,entry:C,size:(await N.stat(a)).size,bucketName:L.name})}catch(C){f(C),u(),Ur(C)||await R(N)}}}return{entries:_,metadataBytes:A}}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(A){f(A),u()}}function O(m){const{payload:A,..._}=m,j=$r.encode(JSON.stringify({..._,payloadBytes:A.length}));if(j.length>pi)throw new Error("缓存信封过大");const H=new Uint8Array(4+j.length+A.length);return new DataView(H.buffer).setUint32(0,j.length),H.set(j,4),H.set(A,j.length+4),H}return{readRevisions:(m,A)=>h(()=>v(m,A)),read:(m,A)=>h(async()=>{u();const _=await P(m);let j;try{j=await V(_,A)}catch(H){if(u(),Ur(H))return;throw H}if(!(!Oe(j.address,m)||j.expiresAt<=Date.now())&&Oe(j.revisions,await v(m.scopeIds,m.namespace)))return j}),publish:(m,A)=>h(async()=>{u();const{address:_}=m;if(!Oe(m.revisions,await v(_.scopeIds,_.namespace)))return!1;const j=O(m);if(m.payload.length>A.maxEntryBytes||j.length>A.diskMaxBytes||A.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await p();const H=await S(_),L=await P(_),N=await D(),b=[],C=new Map;for(const z of N.entries){if(z.bucketName===H.name&&z.file.name===L.name)continue;const F=JSON.stringify([z.entry.address.scopeIds,z.entry.address.namespace]);let G=C.get(F);if(G||(G=await v(z.entry.address.scopeIds,z.entry.address.namespace),C.set(F,G)),z.entry.expiresAt<=Date.now()||!Oe(z.entry.revisions,G)){if(!await M(z))throw new Error("缓存治理期间条目已变化")}else b.push(z)}b.sort((z,F)=>z.entry.cachedAt-F.entry.cachedAt);function k(){const z=b.filter(F=>F.bucketName===H.name);return b.length+1>Rl||j.length+N.metadataBytes+b.reduce((F,G)=>F+G.size,0)>Qt||z.length+1>Math.min(A.diskMaxEntries,pt-1)||j.length+z.reduce((F,G)=>F+G.size,0)>A.diskMaxBytes}for(;k();){const z=b.filter(re=>re.bucketName===H.name),G=z.length+1>Math.min(A.diskMaxEntries,pt-1)||j.length+z.reduce((re,$)=>re+$.size,0)>A.diskMaxBytes?z[0]:b[0];if(!G||!await M(G))throw new Error("缓存容量不足或条目已变化");b.splice(b.indexOf(G),1)}await y();const U=await T(i);if(!U.some(z=>z.name===H.name)&&U.length>=pt-1)throw new Error("缓存目录超过治理上限");if(await H.create({recursive:!0,exclusive:!1},a),!Oe(m.revisions,await v(_.scopeIds,_.namespace)))return!1;try{await L.create({recursive:!1,exclusive:!0},a)}catch(z){f(z),await L.stat(a)}return await L.write(j,a),u(),Oe(m.revisions,await v(_.scopeIds,_.namespace))}),invalidate:(m,A)=>h(async()=>{await p();const _=n.file(`${await jr([m,A??null])}.revision`);await I(_);try{await _.create({recursive:!1,exclusive:!0},a)}catch(j){f(j),await _.stat(a)}await _.write($r.encode(us()),a),u();try{const{entries:j}=await D();for(const H of j){if(A!==void 0&&H.entry.address.namespace!==A||!m.every((N,b)=>H.entry.address.scopeIds[b]===N))continue;const L=await v(H.entry.address.scopeIds,H.entry.address.namespace);Oe(H.entry.revisions,L)||await M(H)}await y()}catch(j){f(j),u()}})}}function Ur(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const xl="RATE_LIMITED_BY_RUNTIME",jl="RATE_LIMITED",Lc=20,Cc=40,Rc=150,Pc=20,kc=1e4,xc=45e3,jc=1,Ul=300*1e3,zl=64;function yt(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Hl(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Fl(e={}){const t=e.now??Date.now,r=Hl(e.coalesceWindowMs,Rc),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,yt(e.budget?.ratePerSecond,Lc)),burst:Math.max(1,Math.floor(yt(e.budget?.burst,Cc)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(yt(e.loopDetection?.maxCalls,Pc))),windowMs:Math.max(1,Math.floor(yt(e.loopDetection?.windowMs,kc)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(yt(e.circuitBreaker?.failureThreshold,jc))),openMs:Math.max(1,Math.floor(yt(e.circuitBreaker?.openMs,xc)))},s=new Map,a=new Map,c=new Set,d=new Map,l=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},f={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let u=!1;function h(M){try{e.onReport?.(M)}catch{}}function p(M,w){if(!i)return{exceeded:!1,count:0};const D=a.get(M)??[],y=w-i.windowMs;let O=0;for(;O<D.length&&D[O]<=y;)O+=1;O>0&&D.splice(0,O);const m=D.length>=i.maxCalls;return m||(D.push(w),D.length>i.maxCalls+1&&D.splice(0,D.length-(i.maxCalls+1))),a.set(M,D),{exceeded:m,count:D.length}}function E(M){if(!n)return!0;const w=Math.max(0,M-l.updatedAt)/1e3;return l.tokens=Math.min(n.burst,l.tokens+w*n.ratePerSecond),l.updatedAt=M,l.tokens<1?!1:(l.tokens-=1,!0)}function T(M){if(!n)return 0;const w=Math.max(0,M-l.updatedAt)/1e3,D=Math.min(n.burst,l.tokens+w*n.ratePerSecond);return Math.max(0,Math.ceil((1-D)/n.ratePerSecond*1e3))}function I(M,w,D,y,O){if(!o)return;const m=d.get(w),A=(m?.open?0:m?.failures??0)+1;if(A<o.failureThreshold){d.set(w,{open:!1,openedAt:0,openMs:0,failures:A});return}const _=Math.min(Math.max(o.openMs,y),Ul);d.set(w,{open:!0,openedAt:O,openMs:_,failures:A}),f.circuitOpened+=1,h({type:"circuit_opened",capability:M,endpointId:w,status:D,openMs:_,timestamp:O})}function v(M){const w=d.get(M);w&&!w.open&&d.delete(M)}function S(M){for(const[w,D]of s)!D.pending&&D.expiresAt<=M&&s.delete(w);for(;s.size>=zl;){const w=[...s].find(([,D])=>!D.pending);if(!w)break;s.delete(w[0])}}function P(M,w){if(M===void 0)return;const D=s.get(M);D?.promise===w&&(D.pending=!1)}function V(M,w){if(M===void 0)return;s.get(M)?.promise===w&&s.delete(M)}async function R(M){if(u)return M.load();const w=t();if(o){const m=d.get(M.endpointId);if(m?.open){const A=m.openedAt+m.openMs-w;if(A>0)throw f.circuitRejected+=1,h({type:"circuit_rejected",capability:M.capability,endpointId:M.endpointId,retryAfterMs:A,timestamp:w}),Gl("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:M.endpointId,retryAfterMs:A});d.delete(M.endpointId)}}const D=p(M.endpointId,w);D.exceeded&&i?c.has(M.endpointId)||(c.add(M.endpointId),h({type:"loop_detected",capability:M.capability,endpointId:M.endpointId,count:D.count,windowMs:i.windowMs,timestamp:w})):c.delete(M.endpointId);const y=r>0?M.coalesceKey:void 0;if(y!==void 0){const m=s.get(y);if(m&&(m.pending||m.expiresAt>w))return f.coalesced+=1,h({type:"coalesced",capability:M.capability,endpointId:M.endpointId,timestamp:w}),m.promise;m&&s.delete(y)}if(D.exceeded&&i)throw f.loopRejected+=1,fs("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:M.capability,endpointId:M.endpointId,count:D.count,windowMs:i.windowMs});if(!E(w)){f.budgetRejected+=1;const m=T(w);throw h({type:"budget_exhausted",capability:M.capability,endpointId:M.endpointId,retryAfterMs:m,timestamp:w}),fs("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:M.capability,endpointId:M.endpointId,retryAfterMs:m})}y!==void 0&&S(w);const O=M.load().then(m=>(P(y,O),v(M.endpointId),m),m=>{V(y,O);const A=Vl(m);throw A!==void 0&&I(M.capability,M.endpointId,A,Bl(m),w),m});return y!==void 0&&s.set(y,{endpointId:M.endpointId,promise:O,expiresAt:w+r,pending:!0}),O}return{execute:R,invalidateCoalescing(M){if(M===void 0){s.clear();return}for(const[w,D]of s)M.includes(D.endpointId)&&s.delete(w)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,M])=>M.open).map(([M])=>M)}},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function Vl(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 Bl(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 fs(e,t){return{code:xl,message:e,data:t}}function Gl(e,t){return{code:jl,message:e,data:t}}const Uc=3e4,zc=6e4,no=1440*60*1e3;function Ql(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??Uc)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??zc)):0,steamGameListTtlMs:t?Yl(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:Lc,burst:Cc},coalesceWindowMs:r?.coalesceWindowMs??Rc,loopDetection:r?.loopDetection??{maxCalls:Pc,windowMs:kc},circuitBreaker:r?.circuitBreaker??{failureThreshold:jc,openMs:xc}}}}function Yl(e){return e===void 0||!Number.isFinite(e)?no:Math.max(0,Math.floor(e))}function g(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function B(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ql(e){return typeof e=="object"&&e!==null}function de(e,t){const r=e.data;if(!ql(r)||typeof r.status!="string")throw new Error(t);return r}const Hc={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},$l={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 de(e,"工坊小程序详情加载失败")}};function br(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Wl(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Kl(e){const t=de(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=Wl(r.consent_challenge)),{...t,result:n}}const Jl={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=>({...br(e.runtimeContext),challenge:e.challenge}),parse:e=>de(e,"小程序授权取消接口响应异常")},Zl={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=>br(e.runtimeContext),parse:e=>de(e,"小程序授权撤销接口响应异常")},Xl={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=>br(e.runtimeContext),parse(e){const t=de(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}:{}}}}},ef={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=>({...br(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Kl(e)},tf={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=>({...br(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=de(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},rf=64;function Fc(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??rf)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(f){for(const[u,h]of i)h.expiresAt<=f&&i.delete(u)}function d(f,u,h){if(a||t<=0||h!==s)return;const p=n();for(c(p),i.delete(f);i.size>=r;){const E=i.keys().next();if(E.done)break;i.delete(E.value)}i.set(f,{expiresAt:p+t,value:u})}function l(f,u){if(a)return u();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 p=s,E=u().then(T=>(d(f,T,p),T)).finally(()=>{o.get(f)===E&&o.delete(f)});return o.set(f,E),E}return{read:l,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function nf(e,t){return t?e?"server":"local":"legacy"}function of(e,t){if(e==="local")throw g("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const sf=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],af=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),cf=/authorization|cookie|pkey|password|secret|token/i,Vc=/authorization|cookie|pkey|token|password|secret/i;function _e(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function df(e){for(const t of Object.keys(e))if(!af.has(t))throw new ae(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of sf)if(Object.prototype.hasOwnProperty.call(e,t)&&_e(e,t)!==void 0)throw new ae(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(_e(e,"bodyEncoding")!==void 0&&_e(e,"bodyEncoding")!=="json"&&_e(e,"bodyEncoding")!=="form")throw new ae("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(_e(e,"failurePresentation")!==void 0&&_e(e,"failurePresentation")!=="none")throw new ae("endpoint failurePresentation 必须为 none");if(_e(e,"auth")!==void 0&&_e(e,"auth")!=="none"&&_e(e,"auth")!=="optional"&&_e(e,"auth")!=="required")throw new ae("endpoint auth 必须为 none、optional 或 required")}function nr(e){if(Array.isArray(e))return e.map(nr);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))cf.test(n)||(r[n]=nr(i));return r}function hs(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Vc.test(r)||(t[r]=n);return t}function uf(e){if(!e)return;const t=Object.keys(e).find(r=>Vc.test(r));if(t)throw new ae(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Pt 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 ms=1440*60*1e3,lf=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function ff(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,ms):void 0}if(!lf.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,ms):void 0}function hf(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 Bc(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class kt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Bc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Or extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Bc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function mf(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:nr(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:hs(o),method:e.method,metadata:{endpointId:e.id},query:nr(n),timeout:e.timeout,url:r},data:nr(a.data),headers:hs(a.headers)||{},status:a.status,statusText:a.statusText}}async function si(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(df(t),typeof t.id!="string"||!t.id)throw new ae("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new ae("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new ae("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;uf(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 ae?h:new kt({endpointId:t.id,cause:h})}if(f.status<200||f.status>=300)throw new Pt({endpointId:t.id,status:f.status,retryAfterMs:ff(f.headers)});const u=mf(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(u,r)}catch(h){throw new Or({endpointId:t.id,cause:h})}return u.data},d=n.gate;if(!d)return c();const l=hf(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...l===void 0?{}:{coalesceKey:l},load:c})}const gf=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),pf=new Set(Rt),ko="steam_account",Gc=new Set(Rt.filter(e=>e!==ko)),yf=1e3;function Ef(e){const t=new Set,r=Fc({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??Uc))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??nf(e.networkEnabled===!0,c),l=e.requestPolicyEnabled!==!1,f=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function u(){if(!c&&!e.authorizationContext)return{};if(!e.authorizationContext)throw g("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let N;try{N=await e.authorizationContext.get(e.operationContext)}catch(C){throw oo(C)?yi(C.code,C.message,C):yi("REQUEST_FAILED","读取 Runtime auth context 失败",C)}if(N.steamAccount!==c||N.userDataMode!==d)throw g("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const b=N.token.trim();if(!b)throw g("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:b}}const h=e.account.onChange(N=>{if(p(),E("heybox_app_login_change",N?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),N&&e.account.getAccountKey){const b=i;V().then(C=>{!o&&i===b&&E("heybox_app_login_change",C)}).catch(()=>{})}});function p(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function E(N,b){N==="user_info_authorization_change"&&Df(b)&&r.invalidate();for(const C of t)try{C(N,b)}catch{}}function T(){const N=e.identity.get()?.miniProgramId?.trim();if(!N)throw g("INVALID_STATE","当前能力缺少 canonical 小程序身份");return N}function I(){if(o||e.operationContext.signal.aborted)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function v(){I();let N;try{N=await e.account.getCurrentUserId(e.operationContext)}catch(b){throw Es(b,e.operationContext.signal,"读取小黑盒账号失败")}return typeof N=="string"&&N.trim()?N.trim():void 0}async function S(N,b){const C=await v();if(i!==b||C!==N)throw g("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function P(N,b,C=T()){if(!e.account.getAccountKey)throw g("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let k;try{k=await e.account.getAccountKey(C,N,e.operationContext)}catch{throw I(),g("REQUEST_FAILED","读取本地账号标识失败")}if(await S(N,b),T()!==C)throw g("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof k!="string"||!k.trim())throw g("INVALID_RESPONSE","Host 返回了无效的账号标识");return k}async function V(){const N=T(),b=i,C=await v();if(I(),i!==b)throw g("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return C?{isHeyboxAppLoggedIn:!0,accountKey:await P(C,b,N)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function R(N){I();try{await e.account.ensureAuthenticated({trustedUserGesture:N,reason:"runtime_auth",signal:e.operationContext.signal})}catch(C){throw Es(C,e.operationContext.signal,"小黑盒登录失败")}const b=await v();if(!b)throw g("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return b}async function M(N,b,C=e.operationContext.signal){try{if(C.aborted)throw io();return await Nf(si(e.network,N,b,{...e.operationContext,credentials:"heybox-session",signal:C,...f?{gate:f}:{}}),C)}catch(k){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):k instanceof ae?g("REQUEST_UNSUPPORTED",k.message):k instanceof Or?g("INVALID_RESPONSE","授权接口响应不合法"):k instanceof kt?g("REQUEST_FAILED","授权请求失败"):k instanceof Pt?l&&(k.status===403||k.status===429)?g("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:k.status,...k.retryAfterMs===void 0?{}:{retryAfterMs:k.retryAfterMs}}):g("REQUEST_FAILED",k.message):oo(k)?k:g("REQUEST_FAILED","授权请求失败")}}async function w(N,b){await M(Jl,{runtimeContext:{miniProgramId:N,...await u()},challenge:b}).catch(()=>{})}function D(N){const b=async()=>{const k=ps(e.operationContext.signal);a=k;try{return await N(k.signal)}finally{a===k&&(a=void 0),k.abort()}},C=s.then(b,b);return s=C.then(()=>{},()=>{}),C}async function y(N,b,C,k,U){if(!C)throw await w(N,b.challenge),g("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await w(N,b.challenge),g("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return D(async z=>{await S(k,U);const F=await O(N,b.displayedScopes,z);await S(k,U);let G;try{G=await e.authPresentation.confirmAuthorization({miniProgramId:N,scopes:b.displayedScopes,...F,signal:z})}catch($){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await S(k,U),await w(N,b.challenge),yi("REQUEST_FAILED","授权确认界面执行失败",$))}if(await S(k,U),G.status!=="granted")throw await w(N,b.challenge),g("AUTHORIZATION_CANCELLED","用户取消授权");const re=Mf(G.grantedScopes,b.displayedScopes,c);if(!re.includes("identity"))throw await w(N,b.challenge),g("AUTHORIZATION_CANCELLED","用户拒绝授权");return re})}async function O(N,b,C){const k=ps(C),U=setTimeout(()=>k.abort(),yf);try{const z=Af(e.miniProgramPresentation),[F,G]=await Promise.all([z?Promise.resolve(z):m(N,k.signal),b.includes("profile")?A(k.signal):Promise.resolve(void 0)]);return{...F?{miniProgram:F}:{},...G?{userProfile:G}:{}}}finally{clearTimeout(U),k.abort()}}async function m(N,b){try{const C=e.identity.get()?.version?.trim(),k=await M($l,{mini_program_id:N,...C?{miniprogram_version:C}:{}},b),U=Et(k,"小程序公开资料"),z=Tt(U.name),F=Tt(U.icon_url);return z||F?{...z?{name:z}:{},...F?{avatarUrl:F}:{}}:void 0}catch{return}}async function A(N){try{const b=await M(Hc,void 0,N),C=Et(b,"账号基础信息"),k=Tt(C.display_username),U=Tt(C.display_avatar);return k||U?{...k?{nickname:k}:{},...U?{avatar:U}:{}}:void 0}catch{return}}async function _(N,b){if(of(d,"auth.login"),!c&&N.includes(ko))throw g("INVALID_PARAMS","auth.login 参数不合法");const C=T(),k=await R(b),U=i,z=await M(ef,{runtimeContext:{miniProgramId:C,...await u()},scopes:N});await S(k,U);const F=Et(z,"小程序登录"),G=ys(F,"loginCode"),re=ys(F,"consentChallenge");if(G===re)throw g("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let $;if(G)$=gs(F.loginCode,c);else{const Y=wf(F.consentChallenge,c),ue=await y(C,Y,b,k,U);await S(k,U);const Rr=await M(tf,{runtimeContext:{miniProgramId:C,...await u()},challenge:Y.challenge,selectedScopes:ue});if(await S(k,U),$=gs(Et(Rr,"小程序登录确认"),c),$.scopes.some(Bt=>!ue.includes(Bt)))throw g("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const Y of $.scopes)n.add(Y);r.invalidate();const J=e.account.getAccountKey?await P(k,U,C):void 0;return E("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...J===void 0?{}:{accountKey:J}}),E("user_info_authorization_change",Ei(n,c)),{...$,...J===void 0?{}:{accountKey:J}}}async function j(N,b){const C=i,k=await M(Xl,{runtimeContext:{miniProgramId:b,...await u()}});await S(N,C);const U=If(Et(k,"用户本地身份"),c);for(const z of c?Rt:Gc)n.add(z);return E("user_info_authorization_change",Ei(n,c)),U}function H(N){I();const b=T(),C=`${N}\0${b}\0${i}\0${c}`;return r.read(C,()=>j(N,b))}async function L(N){if(!N)throw g("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const b=T(),C=i,k=await v();if(!k)throw g("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const U=await M(Zl,{runtimeContext:{miniProgramId:b,...await u()}});await S(k,C),Et(U,"用户授权撤销"),p(),E("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:V,login:_,getOrCreateLocalIdentity:H,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Ei(n,c),revoke:L,onEvent(N){return t.add(N),()=>t.delete(N)},dispose(){o||(o=!0,p(),r.dispose(),h(),t.clear())}}}function yi(e,t,r){const n=g(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function Et(e,t){if(!B(e))throw g("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":gf.has(r)?r:"REQUEST_FAILED";throw g(n,r)}if(!B(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function gs(e,t){if(!B(e))throw g("INVALID_RESPONSE","login code 必须是对象");const r=Un(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!r.includes("identity"))throw g("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function wf(e,t){if(!B(e))throw g("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Un(e.requestedScopes,"challenge requestedScopes",t),n=Un(e.displayedScopes,"challenge displayedScopes",t);if(typeof e.challenge!="string"||!e.challenge.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!Number.isInteger(e.consentUiVersion)||Number(e.consentUiVersion)<0||!r.length||!r.includes("identity")||!n.length||!n.includes("identity")||r.some(i=>!n.includes(i)))throw g("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function If(e,t){if(!B(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw g("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw g("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const n=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return n?{appUserId:r,steamId:n}:{appUserId:r}}function Mf(e,t,r){const n=Un(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw g("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Tt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Af(e){const t=Tt(e?.name),r=Tt(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function ps(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 Nf(e,t){return t.aborted?Promise.reject(io()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(io()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function io(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Un(e,t,r){const n=r?pf:Gc;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw g("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Ei(e,t){const r=t?Rt:Rt.filter(n=>n!==ko);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function ys(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Df(e){return B(e)?Object.values(e).some(t=>t==="denied"):!1}function oo(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Es(e,t,r){return t.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):oo(e)?e:g("REQUEST_FAILED",r)}const Sf=new Set(Rt);function Tf(e){return{[an]:async t=>{if(t!==void 0)throw g("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[cn]:async(t,r)=>e.authorization.login(bf(t),r.trustedUserGesture)}}function bf(e){if(e===void 0)return["identity"];if(!B(e)||Object.keys(e).some(t=>t!=="scopes"))throw ws();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Sf.has(t))||new Set(e.scopes).size!==e.scopes.length)throw ws();return[...e.scopes]}function ws(){return g("INVALID_PARAMS","auth.login 参数不合法")}const Of={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 de(e,"排行榜记录删除接口响应异常")}},_f={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 de(e,"当前排行榜记录接口响应异常")}},vf={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 de(e,"排行榜信息接口响应异常")}},Lf={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 de(e,"排行榜列表接口响应异常")}},Cf={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 de(e,"排行榜提交接口响应异常")}};function Wr(){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:Wr()}function Is(e){return e instanceof ae?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function K(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Wr());let n;try{n=e()}catch(i){return Promise.reject(Is(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Wr())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(Wr()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(Is(d))))})}const Rf={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 Qc(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await K(()=>si(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(Hn(i)||Zt(i,"REQUEST_UNSUPPORTED")||Zt(i,"RATE_LIMITED")||Zt(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof ae)throw ne("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof kt&&Zt(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Pt){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw ne("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw ne("UNAUTHORIZED","当前用户未登录")}throw i instanceof kt||i instanceof Pt?zn(e.subject):i instanceof Or?X(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):X(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function xe(e,t,r){if(!ge(e)||typeof e.status!="string")throw X(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Pf(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw X(`${t} 响应缺少 result`);return e.result}function Yc(e,t){try{return e.onChange(t)}catch(r){if(Zt(r,Tc))return()=>{};throw r}}function Pf(e,t){if(e.status==="login"||e.status==="relogin")throw ne("UNAUTHORIZED",Jt(e.msg)||"当前用户未登录");const r=Ms(e.result)??Ms(e),n=Jt(r?.user_message)||Jt(e.msg)||Jt(r?.developer_message)||`${t}请求失败`;throw r?ne(kf(r),n,{status:e.status,sbe:r}):ne("HEYBOX_API_ERROR",n,{status:e.status})}function Ms(e){return ge(e)&&ge(e.sbe)?e.sbe:void 0}function kf(e){const t=Jt(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 Rf[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 ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Zt(e,t){return ge(e)&&e.code===t}function ne(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function X(e){return ne("INVALID_RESPONSE",e)}function zn(e){return ne("REQUEST_FAILED",`${e}请求失败`)}function Hn(e){return e instanceof Error&&e.name==="AbortError"}const xf="default",Ze="排行榜",jf=/^[A-Za-z0-9_-]{1,64}$/,Uf=300*1e3,zf=250,Hf=3;class Ff{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Yc(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(Cf,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=xe(i,je,Ze);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),wi(o,je)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=qt("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(Lf,{miniProgramId:r,...t}),s=xe(o,De,Ze);if(!ge(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw X(`${De} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw X(`${De} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>wi(a,De)),...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=qt("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(_f,{miniProgramId:n,...t}),c=xe(a,Qe,Ze);if(!ge(c))throw X(`${Qe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:wi(c.entry,Qe)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Of,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=xe(i,ct,Ze);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!ge(o)||typeof o.deleted!="boolean")throw X(`${ct} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",qt("info"),async()=>{const i=await this.request(vf,{miniProgramId:r,...t}),o=xe(i,Re,Ze);if(!ge(o)||typeof o.key!="string"||!jf.test(o.key))throw X(`${Re} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw X(`${Re} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw X(`${Re} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw X(`${Re} 返回的 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=qt(t,n),d=this.inflight.get(c);if(d)return d.promise;const l=this.accountGeneration,f=o?.generation,u=i().then(h=>(this.assertAccountGeneration(l),o&&s&&o.generation===f&&(r==="list"?s.size>=zf&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Uf,value:h})),h)).finally(()=>{this.inflight.get(c)?.promise===u&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:u}),u}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=Hf)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)As(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){As(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 Hn(n)?n:zn(Ze)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ne("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ne("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return qt(t,r??xf)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ne("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return Qc({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Ze,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 ne("INVALID_STATE","Cloud capability 已释放")}}function Vf(e){return new Ff(e)}function wi(e,t){if(!ge(e))throw X(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw X(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw X(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw X(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw X(`${t} 返回的 score 必须是有限数字`);if(!ge(e.extra))throw X(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw X(`${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 As(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function qt(...e){return JSON.stringify(e)}const Bf={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 de(e,"云端存储删除接口响应异常")}},Ns={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 de(e,"云端存储读取接口响应异常")}},Ds={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 de(e,"云端存储 key 列表接口响应异常")}},Gf={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:e.expectedVersion,expected_revision:e.expectedRevision}},parse(e,t){return de(e,"云端存储写入接口响应异常")}},Xe="云端存储",Qf=3e4,Yf=128,qf=500;class $f{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Yc(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=xe(await this.request(Ds,{}),dt,Xe);if(this.assertAccountGeneration(t),!ge(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw X("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"?qf: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=xe(await this.request(Bf,{key:t}),Ct,Xe);if(this.assertAccountGeneration(r.generation),!ge(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw X("删除结果不合法");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 X("云存储版本超出安全整数范围");const o=xe(await this.request(Gf,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),Lt,Xe);if(this.assertAccountGeneration(r.generation),!ge(o)||o.success!==!0)throw X("云存储写入结果不合法");const s=Ss({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw X("写入版本凭证不匹配");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(Ns,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=Ss(xe(c,vt,Xe));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>=Yf&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+Qf,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([Ns.id,Ds.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(ne("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(ne("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 Hn(o)?o:zn(Xe)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),ne("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),ne("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw ne("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ne("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ne("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw ne("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await K(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw Hn(s)?s:zn(Xe)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw ne("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return Qc({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Xe,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(W(this.options.operationContext.signal),this.disposed)throw ne("INVALID_STATE","Cloud capability 已释放")}}function Wf(e){return new $f(e)}function Ss(e){if(!ge(e))throw X("云存储读取结果必须是对象");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 X("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw X("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const Kf=/^[A-Za-z0-9_-]{1,64}$/,Ts=20,Jf=100,bs=2048,Zf=/^[A-Za-z0-9_-]{1,128}$/,Os=16*1024,Xf=new RegExp("[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]");function eh(e){const t=Vf(e),r=Wf(e);return{handlers:{[je]:async i=>t.submit(th(i)),[De]:async i=>t.getList(rh(i)),[Qe]:async i=>t.getCurrentUserEntry(Ii(i,Qe)),[ct]:async i=>t.deleteCurrentUserEntry(Ii(i,ct)),[Re]:async i=>t.getInfo(Ii(i,Re)),[vt]:async i=>r.getItem(_s(i,vt)),[Lt]:async i=>{const{key:o,value:s}=nh(i);return r.setItem(o,s)},[Ct]:async i=>r.removeItem(_s(i,Ct)),[dt]:async i=>(ih(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function th(e){const t=Ft(e,je,!1);if(Vt(t,["key","score","extra"],je),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{...xo(t.key,je),score:t.score,...t.extra===void 0?{}:{extra:oh(t.extra)}}}function rh(e){if(e===void 0)return{limit:Ts};const t=Ft(e,De,!0);Vt(t,["key","limit","cursor"],De);const r=t.limit===void 0?Ts:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>Jf)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{...xo(t.key,De),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Ii(e,t){if(e===void 0)return{};const r=Ft(e,t,!0);return Vt(r,["key"],t),xo(r.key,t)}function _s(e,t){const r=Ft(e,t,!1);return Vt(r,["key"],t),qc(r.key,t)}function nh(e){const t=Lt,r=Ft(e,t,!1);Vt(r,["key","value"],t);const n=qc(r.key,t);if(typeof r.value!="string")throw pe("INVALID_PARAMS",`${t} value 必须是字符串`);if(Xf.test(r.value))throw pe("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>Os)throw pe("INVALID_PARAMS",`${t} value 不能超过 ${Os} 字节`);return{key:n,value:r.value}}function ih(e){const t=Ft(e,dt,!0);Vt(t,[],dt)}function qc(e,t){if(typeof e!="string"||!Zf.test(e))throw pe("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function Ft(e,t,r){if(e===void 0&&r)return{};if(!$c(e))throw pe("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Vt(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw pe("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function xo(e,t){if(e===void 0)return{};if(typeof e!="string"||!Kf.test(e))throw pe("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function oh(e){if(!$c(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 $c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pe(e,t){return{code:e,message:t}}const sh=new Set(["stdio","attachments","notifications"]),Wc=new Set(["windows-x64","macos-arm64"]),ah=new Set(["unsigned","valid","invalid","unknown"]),ch=/^[a-f0-9]{64}$/,dh=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),uh=new Set(Dc),lh=new Set([...Dc,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Kc=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 fh(e){const t=async(n,i,o,s)=>{const a=hh(n);try{Ce(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Ce(i.signal),c}catch(c){throw ao(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw g("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>mh(d,i)).catch(d=>{throw ao(d)});Ce(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Ce(o.signal),c.status!=="granted")throw g("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[qn]:(n,i)=>t(n,i,async(o,s)=>so(await e.companion.getInfo(o,s),o)),[$n]:(n,i)=>t(n,i,async(o,s)=>vs(await e.companion.getPreparationStatus(o,s))),[Wn]:(n,i)=>t(n,i,async(o,s)=>{const a=vs(await e.companion.getPreparationStatus(o,s));return Ce(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Ce(i.signal),so(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(Zc(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[Kn]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Jn]:(n,i)=>t(n,i,async(o,s)=>Ls(await e.companion.getActiveSession(o,s),o)),[Zn]:(n,i)=>t(n,i,async(o,s)=>{const a=Ls(await e.companion.getActiveSession(o,s),o);return Ce(i.signal),a||(await r("launch",o,i),Ce(i.signal),Xc(await e.companion.launch(o,s),o))}),[Xn]:(n,i)=>wt(n,i,e,"write"),[ei]:(n,i)=>wt(n,i,e,"closeStdin"),[ti]:(n,i)=>wt(n,i,e,"terminate"),[ri]:(n,i)=>wt(n,i,e,"ackOutput"),[ni]:async(n,i)=>{const o=await wt(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[ii]:(n,i)=>wt(n,i,e,"showNotification")}}function hh(e){if(!B(e)||typeof e.alias!="string"||!Qu.test(e.alias))throw g("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Ce(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function wt(e,t,r,n){if(!B(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw g("INVALID_PARAMS","Companion Session controller 不合法");try{Ce(t.signal);const i=await r.companion[n](gh(e,n),{...r.operationContext,signal:t.signal});return Ce(t.signal),i}catch(i){throw ao(i)}}function be(){throw g("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Jc(e){return!Array.isArray(e)||e.some(t=>!sh.has(t))?be():Object.freeze([...new Set(e)])}function so(e,t){return!B(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Wc.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!ah.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?be():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Jc(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function mh(e,t){const r=so(e,t);return!B(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!ch.test(e.sha256)?be():Object.freeze({...r,sha256:e.sha256})}function Zc(e){return B(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}):be():be()}function vs(e){return B(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Zc(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&B(e.error)&&typeof e.error.code=="string"&&uh.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:Kc[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):be():be()}function Xc(e,t){return!B(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Wc.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?be():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Jc(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Ls(e,t){return e===void 0?void 0:Xc(e,t)}function gh(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Ic(r.data))throw g("INVALID_PARAMS","Companion write data 不合法");return{...n,data:new Uint8Array(r.data)}}if(t==="ackOutput"){if(r.stream!=="stdout"&&r.stream!=="stderr"||!Number.isSafeInteger(r.sequence)||Number(r.sequence)<0)throw g("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw g("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw g("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function ph(e){return!B(e)||!dh.has(String(e.reason))?be():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):be():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?be():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function yh(e){if(!B(e)||!B(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||!Ic(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:ph(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 ao(e,t){return B(e)&&typeof e.code=="string"&&lh.has(e.code)?g(e.code,Kc[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&B(e)&&e.name==="AbortError"?g(t,"Companion 准备已取消"):g("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Cs=5e3,Rs=1e4;function he(e){throw{code:"INVALID_PARAMS",message:e}}function jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ed(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&he(`${r} 不支持字段: ${n.join(", ")}`)}function Eh(e){if(e===void 0)return{intensity:"light",delay:0};if(!jo(e))return he("device.vibrate 参数必须是对象");ed(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return he("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Cs?he(`device.vibrate delay 必须是 0-${Cs} 的整数毫秒`):{intensity:r,delay:n}}function wh(e){return jo(e)?(ed(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?he("device.setClipboard text 必须是非空字符串"):e.text.length>Rs?he(`device.setClipboard text 不能超过 ${Rs} 字符`):{text:e.text}):he("device.setClipboard 参数必须是对象")}function Ih(e){return typeof e=="string"?e.trim()?e:he("device.executeProtocol 协议字符串不能为空"):jo(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?he("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(co(e,new Set),e):he("device.executeProtocol 参数必须是协议字符串或协议对象")}function co(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||he("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":he("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":he(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&he("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)co(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&he("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))co(i,t);t.delete(r)}function Mh(e){return{[Cn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.vibrate(Eh(t),e.operationContext),e.operationContext.signal)},[Rn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.setClipboard(wh(t),e.operationContext),e.operationContext.signal)},[Pn]:async(t,r)=>{const n=ut(e.operationContext,r.signal);W(n.signal);const i=Ih(t);await K(()=>e.protocol.invoke(i,n),n.signal)}}}const Ah=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"]),Nh={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 wr(e){const t=Uo(e),r=t&&Ah.has(t)?g(t,Nh[t]??"文件操作失败"):g("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function ke(e){try{return e()}catch(t){throw wr(t)}}function Uo(e){try{if(!B(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function td(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):uo,remove:o?s=>e.remove(s):nd,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):uo,stat:s=>e.stat(s)})}function rd(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=>td(e.file(a),n,{allowRemove:o}),directory:a=>rd(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):uo,remove:s?(a,c)=>e.remove(a,c):nd,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function uo(){return Promise.reject(g("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function nd(){return Promise.reject(g("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Ps=1024;class Dh{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareFile(t,r,n),[o]=this.registerMany([i]);return zr(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=ke(()=>{if(!Array.isArray(t))throw g("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw g("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>Ps)throw g("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw g("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>zr(a.handle,{kind:"file",handleId:s[c]}))}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[o]=this.registerMany([i]);return xs(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!oi(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Th(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Ir(r.relativePath),o=this.prepareFile(ke(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=bh(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==="."?".":Ir(r.relativePath),o=this.prepareDirectory(i==="."?n.hostHandle:ke(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Us(t),zr(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),ke(()=>{if(!Array.isArray(r))throw g("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw g("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw g("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,r[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return ke(()=>{if(B(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return zr(n.handle,ks(t.ref,n.handle.name))}if(B(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return xs(n.handle,Sh(t.ref,n.handle.name))}throw g("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=_r(r),i=this.prepareFile(ke(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:ks(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw g("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return ke(()=>{Us(t);const i=n??t.mode;return js(t.mode,i),{handle:td(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return ke(()=>{vh(t,i);const o=n??t.mode;return js(t.mode,o),{handle:rd(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Ps)throw g("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Oh();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw g("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!_h(t))throw g("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw g("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw g("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Te("files.sandbox");return this.prepareDirectory(ke(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw g("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Te("files")}}function Ir(e){if(!Co(e))throw g("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function _r(e,t="文件名"){const r=Ir(e);if(r.includes("/"))throw g("INVALID_PARAMS",`${t} 只能是 basename`);return r}function ks(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Ir(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Sh(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Ir(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function zr(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function xs(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function js(e,t){if(t==="readwrite"&&e!=="readwrite")throw g("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Th(e){return oi(e)||id(),e}function bh(e){return wc(e)||id(),e}function id(){throw g("INVALID_PARAMS","文件引用不合法")}function Oh(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw g("FILE_IO_FAILED","当前环境缺少安全随机数能力");const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function _h(e){return/^[0-9a-f]{32}$/.test(e)}function Us(e){if(!B(e)||e.kind!=="file"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.create!="function"||typeof e.read!="function"||typeof e.write!="function"||typeof e.stat!="function")throw g("FILE_IO_FAILED","Host 返回了无效 File handle");_r(e.name,"Host File name")}function vh(e,t=!1){if(!B(e)||e.kind!=="directory"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.file!="function"||typeof e.directory!="function"||typeof e.create!="function"||typeof e.stat!="function"||typeof e.list!="function")throw g("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw g("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&_r(e.name,"Host Directory name")}const zs=1e3,Lh=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function Ch(e){const t=r=>ut(e.operationContext,r.signal);return{files:{[In]:async(r,n)=>{Mi(n);const i=Ai(e.picker),o=Rh(r),s=await ye(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Mn]:async(r,n)=>{Mi(n);const i=Ai(e.picker),o=Ph(r),s=await ye(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[An]:async(r,n)=>{Mi(n);const i=Ai(e.picker),o=kh(r).suggestedName,s=t(n);if(!i.saveFile)throw Te("files.saveFile");const a=await ye(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[fr]:async(r,n)=>{const i=Ie(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);It(o.mode),await ye(()=>o.create(Hs(i),t(n)))},[hr]:async(r,n)=>{const i=Ie(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),It(o.handle.mode),!o.handle.remove)throw Te(hr);await ye(()=>o.handle.remove(t(n)))},[Nn]:async(r,n)=>{const i=Ie(r);return Fs(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!B(o)||o.kind!=="file")throw Bs()})},[mr]:async(r,n)=>{const i=Ie(r),o=Vs(await ye(()=>e.registry.resolveFile(i.target).read(t(n))));try{const s=new TextDecoder("utf-8",{fatal:!0}).decode(o);return s.charCodeAt(0)===65279?s.slice(1):s}catch{throw g("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Dn]:async(r,n)=>{const i=Ie(r,["content"]);typeof i.content!="string"&&Ae("content 必须是字符串");const o=e.registry.resolveFile(i.target);It(o.mode),await ye(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[gr]:async(r,n)=>{const i=Ie(r),o=await ye(()=>e.registry.resolveFile(i.target).read(t(n)));return Vs(o)},[Sn]:async(r,n)=>{const i=Ie(r,["content"]),o=e.registry.resolveFile(i.target);It(o.mode),await ye(()=>o.write(jh(i.content),t(n)))},[pr]:async(r,n)=>{const i=Ie(r),o=await ye(()=>e.registry.resolveFile(i.target).stat(t(n)));return Uh(o)}},directory:{[Tn]:async(r,n)=>{const i=Ie(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);It(o.mode),await ye(()=>o.create(Hs(i),t(n)))},[yr]:async(r,n)=>{const i=Ie(r,["recursive"]);if(B(i.target)&&i.target.relativePath===".")throw g("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),It(o.handle.mode),!o.handle.remove)throw Te(yr);await ye(()=>o.handle.remove({recursive:i.recursive===void 0?!1:Fn(i.recursive,"recursive")},t(n)))},[bn]:async(r,n)=>{const i=Ie(r);return Fs(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!B(o)||o.kind!=="directory")throw Bs()})},[On]:async(r,n)=>{const i=Ie(r,["limit"]),o=xh(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await ye(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function Rh(e){if(e===void 0)return{mode:"read",multiple:!1};B(e)||Ae("pickFiles 参数必须是对象"),ai(e,["mode","accept","multiple"]);const t=od(e.mode,"read"),r=e.multiple===void 0?!1:Fn(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)))&&Ae("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function Ph(e){return e===void 0?{mode:"read"}:(B(e)||Ae("pickDirectory 参数必须是对象"),ai(e,["mode"]),{mode:od(e.mode,"read")})}function kh(e){return B(e)||Ae("saveFile 参数必须是对象"),ai(e,["suggestedName"]),{suggestedName:_r(e.suggestedName,"suggestedName")}}function Ie(e,t=[]){return(!B(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Ae("文件操作参数必须包含 target"),ai(e,["target",...t]),e}function Hs(e){return{recursive:e.recursive===void 0?!1:Fn(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Fn(e.exclusive,"exclusive")}}function od(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&Ae("mode 必须是 read 或 readwrite"),e)}function Fn(e,t){return typeof e!="boolean"&&Ae(`${t} 必须是布尔值`),e}function xh(e){if(e===void 0)return zs;if((!Number.isSafeInteger(e)||e<=0)&&Ae("limit 必须是正整数"),e>zs)throw g("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function ai(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&Ae(`不支持字段: ${r.join(", ")}`)}function It(e){if(e!=="readwrite")throw g("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Mi(e){if(!e.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Ai(e){if(!e)throw Te("files.external");return e}async function Fs(e){try{return await e(),!0}catch(t){if(Lh.has(Uo(t)??""))return!1;throw wr(t)}}async function ye(e){try{return await e()}catch(t){throw wr(t)}}function jh(e){return e instanceof Uint8Array||Ae("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Ae("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Vs(e){if(!(e instanceof Uint8Array))throw g("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Bs(){return g("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Uh(e){if(!B(e)||e.kind!=="file"||!zh(e.size))throw g("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Hh(e[t]))throw g("FILE_IO_FAILED",`Host 返回了无效 ${t}`);return{kind:"file",size:e.size,...e.modifiedAt===void 0?{}:{modifiedAt:e.modifiedAt},...e.createdAt===void 0?{}:{createdAt:e.createdAt}}}function zh(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Hh(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Ae(e){throw g("INVALID_PARAMS",e)}const Hr=4294967296;function Fh(e){const t=new Vh;return t.write(e),t.finish()}class Vh{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<Hr?(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=Bh(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<Hr)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/Hr),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Hr)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Bh(e){const t=new Uint8Array(Gh(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 Gh(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 sd(e){lo(e);const t=Fh(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 lo(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)lo(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");lo(s,t+1,r)}r.delete(e)}const Qh=["pc","console","mobile"],Yh=["game","wiki"];function Vn(e){throw{code:"INVALID_PARAMS",message:e}}function qh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qe(e,t){return typeof e!="string"||!e.trim()?Vn(t):e.trim()}function Gs(e,t,r){return typeof e!="string"||!t.includes(e)?Vn(r):e}function $h(e){const t={target:"game_detail",appId:qe(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Gs(e.gameType,Qh,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Gs(e.page,Yh,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=qe(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=qe(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Wh(e){return{target:"user_detail",userId:qe(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Kh(e){const t={target:"post_detail",linkId:qe(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=qe(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=qe(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Jh(e){const t={target:"mini_program",miniProgramId:qe(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Zh(e){return qh(e)?e.target==="game_detail"?$h(e):e.target==="user_detail"?Wh(e):e.target==="post_detail"?Kh(e):e.target==="mini_program"?Jh(e):Vn("navigation.openAppPage target 不支持"):Vn("navigation.openAppPage options 必须是对象")}function Xh(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 em(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function tm(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 rm(e){const t=e;return t.target==="game_detail"?Xh(t):t.target==="user_detail"?em(t):tm(t)}const nm="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",im="data-hb-sdk-fullscreen-exit",om=3e3,sm=2e3,Qs="var(--white-70a,rgba(255,255,255,.7))",Ys="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function am(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(im,""),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 ${Qs}`,`box-shadow:${Ys}`,"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=nm,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 l(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function f(){o||(t.style.width=l())}function u(){d?.cancel(),d=void 0}function h(T=sm){clearTimeout(c),c=setTimeout(()=>{u(),o=!1,t.style.width=l(),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 p(){u(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Qs,t.style.boxShadow=Ys,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),h()}async function E(){if(!(s||a)){if(!o){p();return}a=!0,clearTimeout(c),u();try{await e()}catch{}finally{a=!1,s||p()}}}return t.addEventListener("click",E),window.addEventListener("resize",f),document.body.append(t),!r&&t.animate&&(d=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),h(om),{dispose(){s=!0,clearTimeout(c),u(),t.removeEventListener("click",E),window.removeEventListener("resize",f),t.remove()}}}const ad=1e4;function cd(e){const t=new AbortController;let r;const n=()=>{r??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},t.abort()};e.addEventListener("abort",n,{once:!0}),e.aborted&&n();const i=setTimeout(()=>{r??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},t.abort()},ad);return{signal:t.signal,async run(o){try{return await K(o,t.signal)}catch(s){throw r??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",n)}}}function dd(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 Ni(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Fr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function cm(e){let t,r,n={mode:"portrait",hideCapsule:!1},i={mode:"portrait",hideCapsule:!1},o;function s(){o?.dispose(),o=void 0}function a(u){if(!u.hideCapsule){s();return}o??=am(()=>f.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(u,h){if(t===u){if(t=void 0,clearTimeout(u.timer),e.operationContext.signal.removeEventListener("abort",d),"error"in h)u.controller.abort();else if(r={options:u.options,result:h.result},n=u.options,a(u.options),e.onApplied?.(u.options),h.result.supported&&!Ni(i,u.options)){i={...u.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:u.source})}catch{}}for(const p of u.subscribers)p.dispose(),"error"in h?p.reject(h.error):p.resolve(h.result);u.subscribers.clear()}}function d(){t&&c(t,{error:Fr()})}function l(u,h){return new Promise((p,E)=>{const T=()=>{u.subscribers.delete(I),I.dispose(),E(Fr()),u.subscribers.size===0&&c(u,{error:Fr()})},I={resolve:p,reject:E,dispose:()=>h?.removeEventListener("abort",T)};u.subscribers.add(I),h?.addEventListener("abort",T,{once:!0}),h?.aborted&&T()})}const f={async apply(u,h,p="api"){if(W(e.operationContext.signal),h?.aborted)throw Fr();const E=dd(u),T=t?.options??n,I={mode:E.orientation??T.mode,hideCapsule:E.fullscreen??T.hideCapsule};I.mode==="landscape"&&(I.hideCapsule=!0);const v=e.presentation.applyOrientation;if(!v)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&Ni(t.options,I))return l(t,h);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),r&&Ni(r.options,I))return r.result;r=void 0;const S={options:I,source:p,controller:new AbortController,subscribers:new Set};t=S;const P=l(S,h);return e.operationContext.signal.addEventListener("abort",d,{once:!0}),h||(S.timer=setTimeout(()=>{c(S,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},ad)),K(()=>v.call(e.presentation,I,{...e.operationContext,signal:S.controller.signal}),S.controller.signal).then(V=>c(S,{result:V??{supported:!0}}),V=>c(S,{error:V})),P},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return f}function ud(e){throw{code:"INVALID_PARAMS",message:e}}function qs(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&ud(`${t} 不支持参数`)}function dm(e){return{[kn]:async t=>{W(e.operationContext.signal),qs(t,"navigation.close"),await K(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[xn]:async t=>{W(e.operationContext.signal),qs(t,"navigation.reload"),await K(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[jn]:async(t,r)=>{const n=ut(e.operationContext,r?.signal);W(n.signal);const i=Zh(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=sd(i.extra)}catch{ud("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=cd(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(rm(i),n),n.signal)}}}const um=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),lm=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),fm=new Set(["range","if-range","a-im"]),hm=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"]),mm=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Vr={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class gm{constructor(t){this.signal=t}phase="initial";transition(t){if(Vr[t]<=Vr[this.phase])throw g("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Vr[this.phase]<Vr.committed&&this.signal.aborted)throw fd()}normalizeHostError(t,r){return this.throwIfCancelled(),Ho(t,r,this.signal)}}async function pm(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Te("network.download");const o=ut(r.operationContext,t.signal),s=new gm(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Im(e,i,o)}catch(l){throw s.normalizeHostError(l,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(l){throw s.normalizeHostError(l,"network")}let d=!1;try{s.throwIfCancelled(),s.transition("validate");const l=Am(c);Nm(c,l);const f=Dm(c.status,l);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw g("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const u=Mm(e,a,l,i);let h=0;const p=Em(f.expectedBytes,e.maxBytes);Si(t,Di(0,f));const E={...o,onProgress(v){!Number.isSafeInteger(v)||v<h||p!==void 0&&v>p||(h=v,Si(t,Di(h,f)))}};s.transition("transfer"),d=!0;let T;try{T=await n.files.writeResource(u.hostHandle,c.body,{mode:u.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...f.expectedBytes===void 0?{}:{expectedBytes:f.expectedBytes}},E)}catch(v){throw s.normalizeHostError(v,"transfer")}s.transition("committed"),h=ym(T,f,h,e.maxBytes),Si(t,Di(h,f));const I=i.describeFile(u.handle,u.ref);return s.transition("completed"),I}finally{d||wm(n.network,c.body)}}function ym(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 Em(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function wm(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Im(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return fo(i.handle.mode),await Lm(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return fo(n.handle.mode),await Cm(n.handle,r),{kind:"directory",...n}}function Mm(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Tm(e,r),o=n.deriveFile(t,i);return fo(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 g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!B(e.headers))throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!um.has(r)||!Array.isArray(n)||n.length===0)throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Nm(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw g("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:vm(t,lm)});if((t["content-range"]?.length??0)>0)throw g("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 g("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw g("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw g("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=Sm(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 Sm(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Di(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Si(e,t){try{e.postProgress(t)}catch{}}function Tm(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=bm(i);if(o&&Kr(o))return o}for(const i of r){const o=Om(i);if(o&&Kr(o))return o}if(e.suggestedName!==void 0)return zo(e.suggestedName);const n=_m(e.url);return n&&Kr(n)?n:"download.bin"}function bm(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 Om(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 _m(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function zo(e){try{_r(e,"suggestedName")}catch{throw g("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Kr(e))throw g("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Kr(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||mm.test(e))}function vm(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Lm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw ld()}catch(r){throw Ho(r,"file",t.signal)}}async function Cm(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw ld()}catch(r){throw Ho(r,"file",t.signal)}}function fo(e){if(e!=="readwrite")throw g("FILE_ACCESS_DENIED","下载目标只允许读取")}const Rm={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 Ho(e,t,r){if(r.aborted)return fd();const n=Pm(e);if(n&&hm.has(n)){const o=g(n,Rm[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?g("DOWNLOAD_TIMEOUT","下载网络请求超时"):g("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?g("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):g("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function Pm(e){return B(e)&&typeof e.code=="string"?e.code:void 0}function ld(){return g("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function fd(){return g("DOWNLOAD_CANCELLED","下载已取消")}function km(e){if(!e)return;const t=Object.keys(e).find(r=>fm.has(r.trim().toLowerCase()));if(t)throw g("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const $s={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function xm(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw Te("network.upload");const o=ut(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw g("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(u){throw s(),wr(u)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw g("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw g("FILE_TOO_LARGE","文件超过大小限制");let d=0,l=!1;const f=u=>{l||o.signal.aborted||!Number.isSafeInteger(u)||u<d||u>c.size||(d=u,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:u,...h}=e,p=await n.upload(a,{...h,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:f});if(l=!0,!Number.isSafeInteger(p.uploadedBytes)||p.uploadedBytes<d||p.uploadedBytes>c.size)throw g("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(p.status>=200&&p.status<300&&p.uploadedBytes!==c.size)throw g("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:p.uploadedBytes,total:c.size,lengthComputable:!0}),p}catch(u){l=!0;const h=Uo(u);throw h&&$s[h]?g(h,$s[h]):o.signal.aborted?g("UPLOAD_CANCELLED","上传已取消"):h?.startsWith("FILE_")||h?.startsWith("DIRECTORY_")?wr(u):g("UPLOAD_NETWORK_FAILED","上传网络失败")}}const Fo="withCredentials",jm=new Set(["url","method","params","data","headers","timeout",Fo]),Um=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Fo]),zm=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Ws=3e4,ho=2*1024*1024,Hm=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,hd=/[\u0000-\u0008\u000A-\u001F\u007F]/,Fm=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Vm="network.request 不支持 multipart/form-data,请使用专用上传能力";function Bm(e){const t=Gm(e.runtimePermissions),r=ig(e.allowedHttpOrigins);return{[wn]:async(n,i)=>{const o=Ym(n,{permission:t,allowedHttpOrigins:r}),s=await xm(o,i,e),{uploadedBytes:a,...c}=s;return Js(c)},[En]:async(n,i)=>{const o=qm(n,{permission:t,allowedHttpOrigins:r});return pm(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[yn]:async(n,i)=>{const o=ut(e.operationContext,i?.signal);W(o.signal);const s=Qm(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await K(()=>e.network.request(s,o),o.signal)}catch(c){throw sg(c)?c:ag(c,"REQUEST_UNSUPPORTED")?Q("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):Q("REQUEST_FAILED","网络请求失败")}return Js(a)}}}function Gm(e){const t=Se(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Qm(e,t){const r=xt(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!jm.has(c));if(n.length>0)throw Q("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);md(r,"network.request");const i=Vo(r,t,"network.request"),o=Wm(r.method),s=r.data;s!==void 0&&Zm(s),eg(i.headers,s);const a=tg(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 Ym(e,t){const r=xt(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(l=>!n.has(l)))throw Q("INVALID_PARAMS","network.upload 包含不支持的字段");const i=Vo(r,t,"network.upload");if(i.official)throw Q("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw Q("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!oi(r.from))throw Q("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Q("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw Q("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw Q("INVALID_PARAMS","上传 HTTP 方法不支持");const s={from:r.from,format:r.format,request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"upload",method:o,...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}};if(r.format==="raw"){if(["fieldName","fields","fileName","contentType"].some(l=>r[l]!==void 0))throw Q("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(l=>l.toLowerCase()==="content-type"))throw Q("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=Ks(r.fieldName),c=r.fields===void 0?void 0:xt(r.fields,"fields 必须是字符串字典");for(const[l,f]of Object.entries(c??{}))if(Ks(l),typeof f!="string"||l===a)throw Q("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw Q("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||hd.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw Q("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:a,fields:c,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>ho)throw Q("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:zo(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function Ks(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw Q("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function qm(e,t){const r=xt(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!Um.has(c));if(n.length>0)throw Q("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);md(r,"network.download");const i=Vo(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw Q("INVALID_PARAMS","network.download timeout 必须是有限正数");km(i.headers);const o=oi(r.to),s=wc(r.to);if(!o&&!s)throw Q("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw Q("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw Q("INVALID_PARAMS","suggestedName 必须是字符串");a=zo(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw Q("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Q("INVALID_PARAMS","maxBytes 必须是正的 safe integer");return{request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"download",method:"GET",...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},url:i.url,to:r.to,targetKind:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function Vo(e,t,r){const n=$m(e.url,t.allowedHttpOrigins,r),i=Tl(n);if(i&&!t.permission.useOfficialDomain)throw Q("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(Sl(n.pathname,i))throw Q("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...xt(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Km(e.headers,r),timeout:Jm(e.timeout,r)}}function $m(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw Q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw Q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw Q("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw Q("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Wm(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw Q("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!zm.has(t))throw Q("INVALID_PARAMS","network.request method 不合法");return t}function Km(e,t="network.request"){const r=xt(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!Hm.test(s)||typeof o!="string"||hd.test(o))throw Q("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(bl(s))throw Q("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function md(e,t){const r=e[Fo];if(r!==void 0&&typeof r!="boolean")throw Q("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Jm(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw Q("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Ws)throw Q("INVALID_PARAMS",`${t} timeout 不能超过 ${Ws}ms`);return e}}function Zm(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw Q("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Xm(e)>ho)throw Q("INVALID_PARAMS",`network.request data 不能超过 ${ho} 字节`)}function Xm(e){if(typeof e=="string")return Ti(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return Ti(e.toString());try{const t=JSON.stringify(e);return t?Ti(t):0}catch{throw Q("INVALID_PARAMS","network.request data 必须可序列化")}}function eg(e,t){const r=gd(e),n=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(r?.includes("multipart/form-data")||n)throw Q("INVALID_PARAMS",Vm)}function tg(e,t,r){if(t===void 0)return;const n=gd(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)||ng(t))?"form":rg(t)?"json":void 0}function gd(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function rg(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function ng(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ig(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&&og(n.hostname)&&t.add(n.origin)}catch{}return t}function og(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 Js(e){return Object.keys(e.headers).some(Zs)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Zs(t)))}:e}function Zs(e){const t=e.trim().toLowerCase();return Fm.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function sg(e){return e instanceof Error&&e.name==="AbortError"}function ag(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function xt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Q("INVALID_PARAMS",t);return e}function Ti(e){return new TextEncoder().encode(e).length}function Q(e,t){return{code:e,message:t}}function cg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dg(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 ug(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=dg(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function lg(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 pd(e,t){if(e==null)return{};if(!cg(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=ug(e.topicIds),n=lg(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 fg(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function hg(e){try{if(fg(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function ce(e){throw{code:"INVALID_PARAMS",message:e}}function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mo(e,t){return typeof e!="string"||!e.trim()?ce(t):e}function mg(e,t){const r=mo(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?ce(t):r}catch{return ce(t)}}function gg(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function yd(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return ce(`${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 ce(`${t} 缺少有效的小程序分享地址`)}}function pg(e,t){if(!vr(e))return ce("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return ce("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!gg(r))return ce("share.showShareMenu channel 不合法");const n=Ed(e.extra,"share.showShareMenu");return{title:mo(e.title,"share.showShareMenu title 必须是非空字符串"),description:mo(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:yd(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:mg(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Ed(e,t){if(e!==void 0)try{return sd(e)}catch{return ce(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function wd(e,t){return e.invalidMessage&&await K(()=>hg(t.environment),t.operationContext.signal)?ce(e.invalidMessage):e.post}function Xs(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function yg(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Xs(t.windowWidth,0),height:Xs(t.windowHeight,0)}}function go(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?ce(t):r}function ea(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?ce(t):r}function Eg(e){return vr(e)?{left:go(e.left,"share.screenshot rect.left 必须是非负数字"),top:go(e.top,"share.screenshot rect.top 必须是非负数字"),width:ea(e.width,"share.screenshot rect.width 必须是正数"),height:ea(e.height,"share.screenshot rect.height 必须是正数")}:ce("share.screenshot rect 必须是对象")}function wg(e,t){if(e!=null&&!vr(e))return ce("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?ce("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?ce("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?yg(t):Eg(r.rect),...r.delay===void 0?{}:{delay:go(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function Ig(e,t){W(t.operationContext.signal);const r=pg(e,t);let n=pd(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await wd(n,t);return K(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function Mg(e,t){if(W(t.operationContext.signal),e!==void 0&&!vr(e))return ce("share.copyLink 参数必须是对象");const r=Ed(e?.extra,"share.copyLink"),n=yd(t,"share.copyLink",r);return await K(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Ag(e,t,r){W(t.operationContext.signal);const n=pd(vr(e)?e.post:void 0,{method:"share.screenshot"}),i=await wd(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=Ng(),{watermarkTheme:a,...c}=r;let d=!1,l,f;try{d=!0,await K(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),l=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{l?.()}const u=d?await Dg(t.presentation,s,t.operationContext.signal):void 0;if(f.status==="rejected")throw f.error;if(u)throw u;return f.value}function Ng(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Dg(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 Sg(e){let t=Promise.resolve();return{[fn]:(r,n)=>Mg(r,e),[hn]:(r,n)=>Ig(r,e),[mn]:async(r,n)=>{const i=ut(e.operationContext,n.signal);W(i.signal);const o=wg(r,e.presentation),s=t.then(()=>Ag(r,{...e,operationContext:i},o));return t=s.then(()=>{},()=>{}),K(()=>s,i.signal)}}}const ta=new WeakMap;function Id(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return rl(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${bc(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Md(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 l=await n();let f=ta.get(t);f||(f=new Map,ta.set(t,f));const u=f.get(l)??Promise.resolve(),h=async()=>(W(c.signal,{preserveReason:!0}),d(l)),p=u.catch(()=>{}).then(()=>e.lock?e.lock(l,h):h());f.set(l,p);try{return await p}finally{f.get(l)===p&&f.delete(l)}},o=async(c,d,l=!1)=>{const f=mt(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(p=>p.key.startsWith(f)&&p.value!=="").map(p=>p.key.slice(f.length)))];const u=await e.storage.getRaw(xr(c),d);if((u===void 0||u==="")&&!l)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let h;try{h=u?JSON.parse(u):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(h)||h.length>rs||h.some(p=>typeof p!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(p)))throw new Error("本地数据索引异常");return[...new Set(h)]},s=async(c,d)=>{if(e.diagnostics){const u=mt(c,"");return(await e.diagnostics.listRaw(d)).filter(h=>h.key.startsWith(u)&&h.value!=="").map(h=>({...h,key:h.key.slice(u.length)}))}const l=[],f=await o(c,d);for(let u=0;u<f.length;u+=16){W(d.signal,{preserveReason:!0});const h=await Promise.all(f.slice(u,u+16).map(async p=>{const E=await e.storage.getRaw(mt(c,p),d);return E!==void 0&&E!==""?{area:"local",key:p,value:E}:void 0}));for(const p of h)p&&l.push(p)}return l},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,l=>e.storage.getRaw(mt(l,c),d))},set(c,d,l){return a(c),i(l,async f=>{const u=await o(f,l,!0);if(!u.includes(c)&&u.length>=rs)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const h=[...new Set([...u,c])];await e.storage.setRaw(xr(f),JSON.stringify(h),l)}W(l.signal,{preserveReason:!0}),await e.storage.setRaw(mt(f,c),d,l),W(l.signal,{preserveReason:!0})})},list(c){return i(c,d=>s(d,c))},clear(c){return i(c,async d=>{const l=await o(d,c);e.diagnostics||await e.storage.setRaw(xr(d),JSON.stringify(l),c);for(let f=0;f<l.length;f+=16){W(c.signal,{preserveReason:!0});const h=(await Promise.allSettled(l.slice(f,f+16).map(p=>e.storage.setRaw(mt(d,p),"",c)))).find(p=>p.status==="rejected");if(h)throw h.reason}W(c.signal,{preserveReason:!0}),await e.storage.setRaw(xr(d),"[]",c)})}}}function Tg(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 bg=128,Og=/^[A-Za-z0-9_-]+$/;function _g(e){const t=e.scopedStorage??Md({storage:e.storage,resolveScope:()=>Id({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[ur]:async n=>{W(e.operationContext.signal);const i=ra(n,ur,e.storageLimits?.maxKeyLength),o=await K(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:na(o)}},[lr]:async n=>{W(e.operationContext.signal);const i=Ad(n,"storage.setStorage 参数必须是对象"),o=ra(i,lr,e.storageLimits?.maxKeyLength),s=vg(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"?ot("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:na(o),serializedValue:o,bytes:Nd(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function ra(e,t,r=bg){const i=Ad(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw ot("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!Og.test(i))throw ot("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function vg(e,t){let r;try{r=JSON.stringify(e)}catch{throw ot("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw ot("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Nd(r)>t)throw ot("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function na(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Ad(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw ot("INVALID_PARAMS",t);return e}function Nd(e){return new TextEncoder().encode(e).length}function ot(e,t){return{code:e,message:t}}const ia=120;function Be(e){throw{code:"INVALID_PARAMS",message:e}}function Bo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dd(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Be(`${r} 不支持字段: ${n.join(", ")}`)}function Lg(e){if(!Bo(e))return Be("ui.showToast 参数必须是对象");if(Dd(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Be("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>ia)return Be(`ui.showToast message 不能超过 ${ia} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Be("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function Cg(e){return e===void 0?{dismissible:!1}:Bo(e)?(Dd(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Be("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Be("ui.showLoading 参数必须是对象")}function Rg(e){e!==void 0&&(!Bo(e)||Object.keys(e).length)&&Be("ui.hideLoading 不支持参数")}function Pg(e){return{[_n]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.showToast(Lg(t),e.operationContext),e.operationContext.signal)},[vn]:async t=>{W(e.operationContext.signal),await K(()=>e.presentation.showLoading(Cg(t),e.operationContext),e.operationContext.signal)},[Ln]:async t=>{W(e.operationContext.signal),Rg(t),await K(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const kg={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return de(e,"当前用户首页资料接口响应异常")}},xg=3e4;function jg(e,t,r={}){const n=r.ttlMs??xg,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 si(e,kg,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(u){throw t.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):u instanceof ae?g("REQUEST_UNSUPPORTED",u.message):u instanceof Or?g("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof kt?g("REQUEST_FAILED","user home_v2 请求失败"):u instanceof Pt?i&&(u.status===403||u.status===429)?g("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:u.status,...u.retryAfterMs===void 0?{}:{retryAfterMs:u.retryAfterMs}}):g("REQUEST_FAILED",u.message):zg(u)?u:g("REQUEST_FAILED","user home_v2 请求失败")}return Ug(f,"user home_v2")}function l(f){const u=Date.now();if(a?.userId===f&&a.expiresAt>u)return Promise.resolve(a.value);if(c?.userId===f&&c.generation===s)return c.promise;const h=s,p=d().then(E=>(s===h&&(a={userId:f,value:E,expiresAt:Date.now()+n}),E)).finally(()=>{c?.promise===p&&(c=void 0)});return c={userId:f,generation:h,promise:p},p}return{get:l,clear(){s+=1,a=void 0,c=void 0}}}function Ug(e,t){if(!B(e))throw g("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw g(n,r)}if(!B(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function zg(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Hg={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 de(e,"Steam 游戏库接口响应异常")}};function Fg(e,t=no){const r=_l({version:"2",validate:Bg}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):no,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 oa(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 Vg(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 Bg(e){if(!B(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 bt();for(const t of e.gameList){if(!B(t)||!po(t.appid)||!po(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw bt();for(const r of["image","portraitImage","icon"])Gg(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 bt()}return e}function po(e){return typeof e=="number"&&Number.isFinite(e)}function sa(e,t){if(e[t]!==void 0&&!po(e[t]))throw bt()}function Gg(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw bt()}function bt(){return g("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Sd=20,Qg=100,Yg=128,Td=0,bd="weeks",qg=100,$g=new Set(["weeks","all","achieved"]);function Wg(){return{nickname:"",avatar:""}}function Kg(e){const t=jg(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??vc(),i=Fg(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(w,D){const y=JSON.stringify([w,D]);return(!o||o.key!==y)&&(o={key:y,scope:n.createScope(D,n.createScope(w))}),o.scope}function d(){const w=o;o=void 0,w&&n.invalidateScope(w.scope).catch(()=>{}),s.clear()}const l=Fc({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??zc))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let u=0,h=!1;const p=e.account.onChange(()=>{u+=1,t.clear(),l.invalidate(),d()}),E=e.authorization.onEvent((w,D)=>{w==="user_info_authorization_change"&&Object.values(D).some(y=>y==="denied")&&(u+=1,t.clear(),l.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(I(),y.trim()))}).catch(()=>{}))});function T(){if(h||e.operationContext.signal.aborted)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function I(){const w=e.identity.get()?.miniProgramId?.trim();if(!w)throw g("INVALID_STATE","用户能力缺少 canonical 小程序身份");return w}async function v(){T(),await a,T();let w;try{w=await e.account.getCurrentUserId(e.operationContext)}catch(D){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):da(D)?D:g("REQUEST_FAILED","读取小黑盒账号失败")}return typeof w=="string"&&w.trim()?w.trim():void 0}async function S(w,D){const y=await v();if(u!==D||y!==w)throw g("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function P(w,D,y=e.operationContext.signal){try{return await si(e.network,w,D,{...e.operationContext,signal:y,credentials:"heybox-session",...f?{gate:f}:{}})}catch(O){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):O instanceof ae?g("REQUEST_UNSUPPORTED",O.message):O instanceof Or?g("INVALID_RESPONSE","用户接口响应不合法"):O instanceof kt?g("REQUEST_FAILED","用户请求失败"):O instanceof Pt?r&&(O.status===403||O.status===429)?g("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:O.status,...O.retryAfterMs===void 0?{}:{retryAfterMs:O.retryAfterMs}}):g("REQUEST_FAILED",O.message):da(O)?O:g("REQUEST_FAILED","用户请求失败")}}async function V(){I();const w=u,D=await v();if(!D)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[y,O]=await Promise.all([e.authorization.getOrCreateLocalIdentity(D),R(D).catch(()=>Wg())]);return await S(D,w),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:y.appUserId,profile:O,...y.steamId?{steam_id:y.steamId}:{}}}}function R(w){return l.read(w,()=>P(Hc,void 0).then(D=>{const y=aa(D,"账号基础信息");if(y.display_username!==void 0&&typeof y.display_username!="string")throw g("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(y.display_avatar!==void 0&&typeof y.display_avatar!="string")throw g("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:y.display_username??"",avatar:y.display_avatar??""}}))}async function M(w){const D=Jg(w),y=I(),O=u,m=await v();if(!m)return d(),{isLogin:!1,isBound:!1,data:null};const A=await t.get(m);await S(m,O);const _=Od(A.steam_id_info);if(Object.keys(_).length===0)return await n.invalidateScope(c(y,m)).catch(()=>{}),await S(m,O),s.delete(JSON.stringify([y,m])),{isLogin:!0,isBound:!1,data:null};const j=JSON.stringify([y,m]),H=c(y,m),L=oa({...D,steamId:void 0},_),N=_d(_.personal_infomation_open??_.personal_information_open),b=JSON.stringify([L??null,N??null]),C=s.get(j);C&&C.identity!==b&&(await n.invalidateScope(H).catch(()=>{}),await S(m,O));const k={identity:b,scope:n.createScope(b,H)};s.set(j,k);const U=oa(D,_),z=U?i.persistent:i.unresolved,F=n.createScope(U??"unresolved",k.scope),G=async()=>{if(await S(m,O),I()!==y||s.get(j)?.identity!==b)throw g("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},re=await z.read({scope:F,key:Vg({miniProgramId:y,userId:m,effectiveSteamId:U,personalInformationOpen:N,query:D}),signal:e.operationContext.signal,load:async $=>{const J=await P(Hg,{userId:m,...D,personalInformationOpen:N},$);return await G(),rp(aa(J,"Steam 游戏库"),D)}}).catch(async $=>{throw await G(),$});return await G(),{isLogin:!0,isBound:!0,data:re}}return{getInfo:V,getSteamGameList:M,async invalidateSteamGameListCache(){const w=I(),D=u,y=await v();if(!y)return;const O=c(w,y);await Promise.all([i.persistent.invalidateScope(O),i.unresolved.invalidateScope(O)]),t.clear(),s.delete(JSON.stringify([w,y])),await S(y,D)},dispose(){h||(h=!0,u+=1,p(),E(),t.clear(),l.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function Jg(e){if(e==null)return{limit:Sd,offset:Td,sort:bd,includeHidden:!1};if(!B(e))throw Ge("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Ge(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Zg(e.limit),offset:Xg(e.offset),sort:ep(e.sort),includeHidden:tp(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>Yg)throw Ge("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ge("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,qg))}return r}function Zg(e){if(e===void 0)return Sd;if(!Number.isInteger(e)||Number(e)<1)throw Ge("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Qg)}function Xg(e){if(e===void 0)return Td;if(!Number.isInteger(e)||Number(e)<0)throw Ge("user.getSteamGameList offset 必须是非负整数");return Number(e)}function ep(e){if(e===void 0)return bd;if(typeof e!="string"||!$g.has(e))throw Ge("user.getSteamGameList sort 不支持");return e}function tp(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ge("user.getSteamGameList includeHidden 必须是 boolean");return e}function rp(e,t){if(!Array.isArray(e.game_list))throw g("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(np).filter(a=>a!==void 0),n=Bn(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=_d(e.is_me);return s!==void 0&&(o.isMe=s),o}function np(e){const t=Od(e),r=Bn(t.appid),n=Bn(t.steam_appid)??r,i=Go(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};bi(o,"image",t.image),typeof t.vertical_head_image=="string"&&bi(o,"portraitImage",t.vertical_head_image),bi(o,"icon",t.appicon??t.icon),ca(o,"playtimeForever",t.playtime_forever),ca(o,"playtime2Weeks",t.playtime_2weeks);const s=ip(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function aa(e,t){if(!B(e))throw g("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw g(n,r)}if(!B(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Od(e){return B(e)?e:{}}function Go(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function ip(e){return Array.isArray(e)?e.map(Go).filter(Boolean):[]}function Bn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function _d(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function bi(e,t,r){const n=Go(r);n&&Object.assign(e,{[t]:n})}function ca(e,t,r){const n=Bn(r);n!==void 0&&Object.assign(e,{[t]:n})}function Ge(e){return g("INVALID_PARAMS",e)}function da(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}function op(e){return{[dn]:async t=>(ua(t,"user.getInfo"),e.user.getInfo()),[un]:async(t,r)=>{ua(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[ln]:async t=>e.user.getSteamGameList(t)}}function ua(e,t){if(e!==void 0)throw g("INVALID_PARAMS",`${t} 不接收入参`)}function la(e){throw{code:"INVALID_PARAMS",message:e}}function $t(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function vd(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Br(e,t,r){return Math.min(vd(e,t),r)}async function sp(e){try{return vd(await e.getNavigationBarHeight(),0)}catch{return 0}}function ap(e,t,r,n){const i=Br(e.safeArea?.left,0,t),o=Math.max(i,Br(e.safeArea?.right,t,t)),s=Br(e.safeArea?.top,n,r),a=Math.max(s,Br(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function fa(e){const t=e.getViewportMetrics(),r=$t(t.windowWidth,0),n=$t(t.windowHeight,0),i=await sp(e);return{pixelRatio:$t(t.pixelRatio,1),screenWidth:$t(t.screenWidth,r),screenHeight:$t(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:ap(t,r,n,i),screenTop:i}}function cp(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;fa(r.presentation).then(u=>{if(n||r.operationContext.signal.aborted||f!==i)return;const h=JSON.stringify(u);h!==o&&(o=h,r.onViewportChange?.(u))}).catch(()=>{})},c=cm({...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:{[at]:async(f,u)=>c.apply(f,u?.signal),[gn]:async()=>(W(r.operationContext.signal),fa(r.presentation)),[pn]:async f=>{if(W(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return la("viewport.setNavigationBarStyle 参数必须是对象");const u=f.foregroundStyle;if(u!=="light"&&u!=="dark")return la("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await K(()=>r.presentation.setNavigationBarStyle(u,e.operationContext),r.operationContext.signal)}},applyOrientation:(f,u)=>c.apply({orientation:f.mode,fullscreen:f.hideCapsule},u),notifyChange:()=>{o=void 0,a()},dispose:d}}const dp=new Map(Ye.map(e=>[e.method,e]));function Xt(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function up(e){const t=Yu(e);return r=>t(r.requirement,r.method)}function lp(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=l=>{a||(a=!0,n.removeEventListener("abort",d),l())},d=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",d,{once:!0}),i.then(l=>c(()=>o({status:"handled",value:l})),l=>c(()=>s(l)))})}function fp(e){const t=up(e.runtimePermissions),r=Se(e.runtimePermissions);let n=0,i=0,o=0;return{async dispatch(s,a,c){const d=e.now??hp,l=e.onTrace?d():0,f=e.onTrace?`cap_${++n}`:"",u=s===at?++i:void 0;let h;try{if(e.terminalSignal.aborted)throw Xt("RUNTIME_DESTROYED","小程序 Runtime 已终止");il(s,e.effectiveCapabilities);const p=dp.get(s);if(!p)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const E=t(p),T=!E.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!E.allowed&&!T)throw Xt(E.code,E.message,E.data);const I=e.handlers[s];if(!I)throw new Error(`Capability method ${s} 缺少 handler`);u!==void 0&&(h=cd(c.signal));const v=h?{...c,signal:h.signal}:c,S=async()=>{for(const V of e.policies??[]){const R=await V.evaluate({method:s,payload:a,capability:p});if(e.terminalSignal.aborted||h?.signal.aborted)throw ga();if(!R.allowed)throw Xt(R.code,R.message,R.data)}if(e.terminalSignal.aborted||h?.signal.aborted)throw ga();if(u!==void 0){if(dd(a),u<o)throw Xt("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=u}return I(a,v)},P=await lp(()=>h?h.run(S):S(),void 0,c,e.terminalSignal);return ha(e.onTrace,ma(f,s,a,l,P),d),P}catch(p){throw ha(e.onTrace,ma(f,s,a,l,{status:"error",error:p}),d),p}finally{h?.dispose()}}}}function hp(){return typeof performance>"u"?Date.now():performance.now()}function ha(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 ma(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:mp(i.error)}:{},...gp(t,r,i)}}function mp(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function gp(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"&&Ld(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 Ld(e){return typeof e=="object"&&e!==null}function ga(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function pp(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=Ql(e.requestPolicy);let n;if(e.files)try{n=kl(e.files,t)}catch{}const i=vc({store:n}),o=e.onRequestPolicyReport??(r.debugReport?yp:void 0),s=r.enabled?Fl({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Dh(e.files,e.miniProgramDetail),c=Ch({registry:a,picker:e.picker,operationContext:t}),d=Ef({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 l,f,u,h=()=>{},p=()=>{};try{l=cp({operationContext:t,presentation:e.hostPresentation,onDisplayChange:R=>e.eventSink.postEvent("display_change",R),onViewportChange:R=>e.eventSink.postEvent("viewport_change",R)}),f=Kg({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}),h=d.onEvent((R,M)=>e.eventSink.postEvent(R,M)),p=e.hostCompanion?.onSessionEvent?.(R=>{const M=yh(R);!e.terminalSignal.aborted&&M&&e.eventSink.postEvent(M.type,M.payload)})??(()=>{}),u=eh({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const E=_g({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),T=[{name:"auth",handlers:Tf({authorization:d})},{name:"user",handlers:op({user:f,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:Sg({prepareScreenshot:e.prepareScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:l.handlers},{name:"storage",handlers:E.handlers},{name:"network",handlers:Bm({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[sn]:async()=>{throw Xt("CAPABILITY_UNAVAILABLE","当前 Runtime 不支持工作区卡片刷新")}}},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"ui",handlers:Pg({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Mh({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:dm({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:R=>l.applyOrientation({mode:"portrait",hideCapsule:!1},R)}:{}})},{name:"cloud",handlers:u.handlers},{name:"companion",handlers:fh({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],I=Ep(T);let v=!1;const S=()=>{v||(v=!0,e.terminalSignal.removeEventListener("abort",S),l?.dispose(),u?.dispose(),h(),p(),f?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?S():e.terminalSignal.addEventListener("abort",S,{once:!0});const P=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:T,handlers:I,allowsCompanionAttachmentAccess:(R,M)=>P.has(R)&&Ld(M)&&a.isCompanionAttachmentRef(M.target),applyOrientation:l.applyOrientation,notifyViewportChange:l.notifyChange,...E.diagnostics?{storageDiagnostics:E.diagnostics}:{},dispose:S}}catch(E){throw l?.dispose(),u?.dispose(),h(),p(),f?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),E}}function yp(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Ep(e){const t=new Map(Ye.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=Ye.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Ye.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const wp="heybox-mini-dev:";function pa(e){try{return Ip(new URL(e))}catch{return!1}}function Ip(e){return e.protocol===wp}function Mp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Ap(e)}function Ap(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 Np=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Dp(e,t){const r=[],n=Sp(e.environmentInfo,r),i=Jr(n?.appVersion,"host.appVersion",r),o=bp(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:Tp(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:Jr(t.miniProgramId),version:Jr(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function Sp(e,t){if(e!=null){if(Cd(e))return e;t.push("environmentInfo")}}function Tp(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function bp(e,t){if(e==null)return{name:"unknown",version:null};if(!Cd(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=Np.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:Jr(e.version,"operatingSystem.version",t)}}function Jr(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.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MDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function Cp(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:fixed;left:${r.left}px;top:${r.top+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const l=e.createElement("div");l.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 u=e.createElement("img");u.src=a?vp:Op,u.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 p=e.createElement("img");p.src=a?Lp:_p,p.style.cssText="width:12px;height:12px;flex-shrink:0;";const E=e.createElement("span");E.textContent=t?.trim()||"小程序工坊",E.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const 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(p,E),f.append(u,h),l.append(f,T),s.append(l),e.body.append(s);const I=()=>{s.remove(),n.removeEventListener("abort",I)};n.addEventListener("abort",I,{once:!0});try{return await K(()=>Promise.all([u.decode(),p.decode()]),n),await K(()=>new Promise(v=>{let S=o.requestAnimationFrame(()=>{S=o.requestAnimationFrame(()=>{n.removeEventListener("abort",P),v()})});const P=()=>o.cancelAnimationFrame(S);n.addEventListener("abort",P,{once:!0})}),n),I}catch(v){throw I(),v}}const Rp=1,Rd="allow-scripts allow-same-origin",Pp="",kp="no-referrer";function xp(e=Rd){return!e.split(/\s+/).includes("allow-same-origin")}function ya(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const jp=new Set(["javascript:","data:","blob:","file:"]),Ea="xiaoheihe.cn";function Up(e,t=window.location.href,r={}){const n=e.trim();if(!n)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(n)}catch{throw new Error("小程序链接必须是绝对 URL")}if(jp.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!Bp(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function zp(e,t){const r=new URL(e);return r.searchParams.set(vu,t),r.toString()}function Hp(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Fp(r)??Vp(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Fp(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Vp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function wa(e){const t=new URL(e);return Qo(t)?"loopback":Yo(t)?"lan":"production"}function Bp(e,t,r){return Gp(e)||Qo(e)||Yo(e)&&Yp(t,r)}function Gp(e){return e.protocol==="https:"&&Wp(e.hostname)}function Qo(e){return e.protocol==="http:"&&Qp(e.hostname)}function Qp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Yo(e){return e.protocol==="http:"&&qp(e.hostname)}function Yp(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Qo(r)||Yo(r)}catch{return!1}}function qp(e){const t=$p(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function $p(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 Wp(e){return e===Ea||e.endsWith(`.${Ea}`)}const Kp=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"]),Jp=new Set(["url","inline","eval","unknown"]),Zp=/^\/(?:\:segment(?:\/\:segment)*)?$/,Xp=/^[a-f0-9]{64}$/,ey=255,ty=160,ry=256;function ny(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!Kp.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>ry||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Jp.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=iy(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>ty||!Zp.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Xp.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 iy(e){if(e!==void 0&&!(typeof e!="string"||e.length>ey))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const oy=/^(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 sy(e){if(!e?.minimumSdkVersion)throw Z("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=rt(e.minimumSdkVersion),r=e.sdkVersion?rt(e.sdkVersion):void 0;if(!t)throw Z("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw Z("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=rt("0.6.0");if(!r){if(Zr(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw Z("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0)throw Z("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(Zr(r,t)<0)throw Z("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Zr(r,rt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function ay(e,t){if(typeof t!="string"||!rt(t))throw Z("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw Z("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function Pd(e,t){const r=rt(e),n=rt(t);if(!(!r||!n))return Zr(r,n)}function rt(e){const t=oy.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 Zr(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 ci=["android","ios","ohos","windows","macos","linux"],cy="0.9.0",dy=Object.freeze(["android","ios","ohos","windows","macos"]),kd="该小程序暂不支持当前平台",uy="PLATFORM_UNSUPPORTED";function ly(e){return typeof e=="string"&&ci.includes(e)}function fy(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 hy(e){const t=e.manifest;if(!Ey(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Ma(e.sdkVersion)??Ma(t.sdkVersion);return py(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:gy()}const r=xd(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function my(e){const t=fy(e.operatingSystemName);if(!t)return Nt("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Nt("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:ci,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=hy({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Nt("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):Ia(t,s)}if(r.effectivePlatforms===void 0)return Nt("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=xd(r.effectivePlatforms);if("reason"in n)return Nt("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=yy(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return Ia(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function Ia(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Nt("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Nt(e,t={}){return{status:"denied",reason:e,message:kd,...t}}function gy(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:dy,platformsDeclared:!1,policy:"legacy_mobile_default"}}function xd(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(!ly(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(ci.filter(r=>t.has(r)))}}function py(e){if(typeof e!="string"||!e.trim())return!1;const t=Pd(e.trim(),cy);return t!==void 0&&t>=0}function Ma(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function yy(e){return e==="explicit"||e==="legacy_mobile_default"}function Ey(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const wy=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 Iy(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:My(i.pathname),sanitizedPathnameHash:Ay(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function My(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function Ay(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 I=o[T-15],v=o[T-2],S=ve(I,7)^ve(I,18)^I>>>3,P=ve(v,17)^ve(v,19)^v>>>10;o[T]=o[T-16]+S+o[T-7]+P>>>0}let[c,d,l,f,u,h,p,E]=i;for(let T=0;T<64;T+=1){const I=E+(ve(u,6)^ve(u,11)^ve(u,25))+(u&h^~u&p)+wy[T]+o[T]>>>0,v=(ve(c,2)^ve(c,13)^ve(c,22))+(c&d^c&l^d&l);E=p,p=h,h=u,u=f+I>>>0,f=l,l=d,d=c,c=I+v>>>0}[c,d,l,f,u,h,p,E].forEach((T,I)=>{i[I]=i[I]+T>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ve(e,t){return e>>>t|e<<32-t}const Ny=1e4,Oi=2e3,Dy=2,Sy="open-with-native-credential-policy",jd="安全提示",Ud="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class Ty{nonce=ya();runtimeId=ya();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=_c(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??Ny,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??Z("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??Z("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(ky(),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=Z("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.armDocumentRevalidationTimer(this.documentRevalidationGeneration),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=qu(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=sy(t.sdkVersionPolicy);const n=Dp(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=my({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw Uy(this.platformGateDecision);if(this.miniProgramDetail=zy(t),this.effectiveCapabilities=Oc(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),vy(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(Cy(i)),this.launchUrl=i,this.miniProgramSrc=zp(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=Po(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:at,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,ze(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[at])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=pp({account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,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||(Pd(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):Cp(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=fp({handlers:this.capabilityGraph.handlers,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:l})=>{const f={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...l?{network:l}:{}};ze(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new Xu({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(Z("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 _y(t)?t:zd(Z("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 Up(t,r,{allowPrivateNetwork:pa(r)||Aa(r)||await this.isDevRuntime()})}catch(r){throw Z("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??Py)({message:Ud,title:jd,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(wa(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!pa(r)&&!Aa(r)}async closeAfterDevLaunchCancellation(){const t=Z("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{Na(),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(()=>Na())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Pp),this.iframe.setAttribute("referrerpolicy",kp),this.iframe.setAttribute("sandbox",Rd)}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(),ze(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(),ze(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{ay(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(Z("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>=Dy)){this.failRuntime(Z("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Pr,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},Oi),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Pr})}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),this.armDocumentRevalidationTimer(r),t.deferProbe||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.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(Pr,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Pr})}armDocumentRevalidationTimer(t){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(Z("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 文档再验证超时")))},Oi))}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()},Oi))}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===Cu){this.handleCspViolation(t.payload);return}if(t.method!==Lu)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(Z("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Hp(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(Z("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=ny(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){ze(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=Iy(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(Z("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:Rp,launchUrlType:wa(t),networkPolicy:Sy})}failRuntime(t){const r=by(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),ze(this.options.onError,Oy(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,ze(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){ze(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 by(e){const t=Po(e);return Gn(e)&&"cause"in e&&zd(t,e.cause),t}function zd(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function Oy(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function _y(e){return Gn(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Gn(e){return!!e&&typeof e=="object"}function ze(e,t){try{e?.(t)}catch{}}function vy(e,t,r){try{e?.(t,r)}catch{}}function Aa(e){try{const t=new URL(e);return t.protocol==="http:"&&Mp(t.hostname)}catch{return!1}}function Ly(e){try{return new URL(e).origin}catch{return}}function Cy(e){return xp()?"*":Ly(e)}function Ry(e){return`${jd}
|
|
2
2
|
|
|
3
3
|
${Ud}
|
|
4
4
|
|