@heybox/hb-sdk 0.9.6-alpha.13 → 0.9.6-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/THIRD_PARTY_NOTICES.md +472 -48
  3. package/dist/cli-chunks/{artifact-CUNeWo4O.cjs → artifact-DTqf7LjW.cjs} +3 -3
  4. package/dist/cli-chunks/{build-BnUonzjX.cjs → build-BY4DoIBI.cjs} +5 -5
  5. package/dist/cli-chunks/{create-BbpSkT6L.cjs → create-DG-eZzS2.cjs} +1 -1
  6. package/dist/cli-chunks/{dev-Bj4ll4KS.cjs → dev-BeSGi9u8.cjs} +12 -9
  7. package/dist/cli-chunks/{dev-context-zGJh3bl_.cjs → dev-context-7fvQuwt0.cjs} +2 -2
  8. package/dist/cli-chunks/{doctor-CJm6yLwg.cjs → doctor-DcxJh-U3.cjs} +1 -1
  9. package/dist/cli-chunks/{games-M21dEyxU.cjs → games-CbQNW3Z3.cjs} +1 -1
  10. package/dist/cli-chunks/{index-DOEadJGe.cjs → index-NJUh9sVX.cjs} +1 -1
  11. package/dist/cli-chunks/{index-C29Bsipw.cjs → index-lnwfzT8S.cjs} +17 -17
  12. package/dist/cli-chunks/{index.esm-BDnn3rPW.cjs → index.esm-DOXvj-ZK.cjs} +6 -6
  13. package/dist/cli-chunks/{login-sznH9Tub.cjs → login-PYy4XDVv.cjs} +1 -1
  14. package/dist/cli-chunks/{project-vite-C3XGMxuI.cjs → project-vite-Dzd2JLIc.cjs} +1 -1
  15. package/dist/cli-chunks/{remote-ZN1aTL2_.cjs → remote-r0tXpJh6.cjs} +6 -6
  16. package/dist/cli-chunks/{runtime-permission-env-CubbhSAi.cjs → runtime-permission-env-CN2K4GG7.cjs} +2 -2
  17. package/dist/cli-chunks/{skill-MQLZiQHF.cjs → skill-BbrtzJTC.cjs} +2 -2
  18. package/dist/cli-chunks/{version-d8xCNdNj.cjs → version-SpegXNoR.cjs} +1 -1
  19. package/dist/cli.cjs +1 -1
  20. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DdLOxwBk.js +228 -0
  21. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-DeuOZXeW.js +6 -0
  22. package/dist/devtools/browser-dev-host/assets/index-B-2wxdQX.js +567 -0
  23. package/dist/devtools/browser-dev-host/assets/index-ophYZqpX.css +1 -0
  24. package/dist/devtools/browser-dev-host/assets/linux-DwJAcUeD.svg +1 -0
  25. package/dist/devtools/browser-dev-host/index.html +6 -4
  26. package/dist/index.cjs.js +1 -1
  27. package/dist/index.esm.js +1 -1
  28. package/dist/vite.cjs.js +4 -2
  29. package/dist/vite.esm.js +4 -2
  30. package/package.json +5 -6
  31. package/skill/skill.json +4 -4
  32. package/dist/devtools/browser-dev-host/assets/browser-dev-host-OjGtNPTW.js +0 -228
  33. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-Dmzm0ERX.js +0 -6
  34. package/dist/devtools/browser-dev-host/assets/index-BkmmmW8K.css +0 -1
  35. package/dist/devtools/browser-dev-host/assets/index-Dp6vGvaS.js +0 -586
@@ -1,228 +0,0 @@
1
- import{aD as Vf,aG as hr,bT as bt,a7 as ke,a6 as Ws,bc as Ie,bl as ot,ai as gn,aa as Rt,cQ as ps,aN as Gf,a as Qf,A as qf,a9 as Yf,n as Er,m as Tt,k as Wr,C as Wn,l as Ht,q as Po,r as ys,o as Zn,p as Ro,G as Hd,x as Fd,z as $d,E as Vd,D as Gd,F as Qd,w as qd,t as Yd,s as Wd,y as Zd,v as Kd,u as Jd,K as Wf,M as Zf,N as Kf,S as Jf,R as Xf,T as Zs,Q as em,a0 as Xd,a1 as tm,Z as eu,a2 as rm,_ as tu,Y as nm,$ as Ks,X as ru,W as im,U as om,V as sm,a$ as nu,a8 as Js,ac as am,ad as cm,ab as dm,af as um,ae as lm,ag as fm,al as mm,am as hm,aj as gm,ak as pm,ao as Xs,an as ea,aq as ym,ar as Em,as as wm,aK as Im,aM as _m,aJ as Am,aL as Dm,aI as Nm,cb as Mm,bA as hi,d4 as bm,cu as Sm,cL as iu,ay as Tm,aw as Om,az as vm,av as Pm,ax as Rm,au as ta,aB as Ri,aA as ra,aC as Cm,bS as na,a4 as Cn,aF as km,aE as Lm,aH as xm,aQ as Um,aO as jm,aP as Kn,aT as zm,b0 as Bm,a5 as ia,at as Hm,cx as Fm,d8 as $m,bD as Vm,cO as Gm,cP as Qm,b1 as st,di as K,cI as ou,a_ as su,cg as au,cn as qm,O as oa,cd as Ym,aZ as Wm,co as Zm,dc as pn,cB as cu,cD as Km,aU as Jn,b9 as Jm,b$ as Xn,bf as Xm,bw as Es,cr as eh,aY as du,c3 as uu,aW as th,cK as lu,cj as rh,bj as nh,cz as fu,P as ih,be as oh,bg as sh,cf as ah,bd as ch,cJ as dh,da as mu,d9 as hu,cF as uh,aV as Co,ci as lh,j as $t,J as fh,c as mh}from"./desktop-app-launch-Dmzm0ERX.js";function gu(e){if(e.source!=="runtime-private"||e.credentials!=="omit"||e.route!=="game-save"||e.target.kind!=="absolute-url"||e.method!=="GET"||e.redirectPolicy!=="error"||e.data!==void 0||e.params!==void 0||e.headers!==void 0)return!1;try{const t=new URL(e.target.url);return t.protocol==="https:"&&t.hostname==="heybox-beijing-1251007209.cos.ap-beijing.myqcloud.com"&&!t.port&&!t.username&&!t.password&&!t.hash&&/^\/cloud_archive\/[0-9]{1,20}\.zip$/.test(t.pathname)&&t.searchParams.has("q-signature")}catch{return!1}}const hh=/^[A-Za-z0-9_-]{1,64}$/,sa=1e3;function pu(e){return hh.test(e)?e:Eh(e)}function gh(e){return`id_${pu(e.trim())}`}function tr(e,t){return`hb_miniprogram_${e}_${t}`}function yn(e){return`hb_miniprogram_keys_${e}`}const ph="hb_user_game_data_consent_";function yh(e){return`${ph}${e}`}function Eh(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 Bt="heybox:miniprogram",yu=2,Eu="hb_mini_bridge_nonce",wu="sdk.handshake",En="runtime.location.probe",wh="sdk.location.report",Ih="sdk.csp.violation",Iu="operation.progress",_h="companion.session.output",Ah="companion.session.exit",Dh="companion.session.ownershipLost";function Nh(e){return!ct(e)||e.namespace!==Bt||e.version!==1&&e.version!==2||!ve(e.nonce)?!1:e.type==="handshake"?ve(e.id)&&e.method===wu&&e.error===void 0&&Rh(e.payload):e.type==="request"?ve(e.id)&&ve(e.method)&&e.error===void 0:e.type==="response"?ve(e.id)&&(e.method===void 0||ve(e.method))&&(e.error===void 0||Ch(e.error)):e.type==="event"?!ve(e.method)||e.error!==void 0?!1:e.method===Iu?e.version===2&&ve(e.id)&&Ph(e.payload):e.id===void 0||ve(e.id):e.type==="cancel"?e.version===2&&ve(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function ws(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function _u(e){return ct(e)?e.kind==="sandbox"?et(e,["kind"]):e.kind==="directory"&&ve(e.handleId)&&et(e,["kind","handleId"]):!1}function Yt(e){return!ct(e)||e.kind!=="file"?!1:ve(e.handleId)?et(e,["kind","handleId"]):_u(e.root)&&ws(e.relativePath)&&et(e,["kind","root","relativePath"])}function Au(e){return!ct(e)||e.kind!=="directory"?!1:ve(e.handleId)?et(e,["kind","handleId"]):_u(e.root)&&(e.relativePath==="."||ws(e.relativePath))&&et(e,["kind","root","relativePath"])}function Mh(e){return ct(e)&&e.kind==="file"&&ve(e.name)&&kh(e.mode)&&Yt(e.ref)&&et(e,["kind","name","mode","ref"])}const Du=20,aa=["type","mimeType","size","width","height","previewUrl","file"];function bh(e){return e===void 0?!0:!(!ct(e)||!et(e,["source","mediaType","maxCount"])||e.source!==void 0&&e.source!=="album"&&e.source!=="camera"||e.mediaType!==void 0&&e.mediaType!=="image"&&e.mediaType!=="video"&&e.mediaType!=="all"||e.maxCount!==void 0&&(!Lh(e.maxCount,1,Du)||e.source==="camera"&&e.maxCount!==1))}function Nu(e){if(!ct(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!et(e,t?[...aa,"durationMs"]:aa)||!ve(e.mimeType)||!Ot(e.size)||!ca(e.width)||!ca(e.height)||!ve(e.previewUrl)||!Th(e.file)?!1:t?Ot(e.durationMs):!0}function Sh(e){if(!Array.isArray(e)||e.length<1||e.length>Du)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!Nu(e[t]))return!1;return!0}function Th(e){return!Mh(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&ve(e.ref.handleId)}function Mu(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function Oh(e){return!ct(e)||!Ot(e.loaded)||typeof e.lengthComputable!="boolean"||!et(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Ot(e.total)&&e.loaded<=e.total:e.total===void 0}function vh(e){return ct(e)?e.phase==="downloading"?Ot(e.loaded)&&(e.total===void 0||Ot(e.total)&&e.loaded<=e.total)&&et(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Ot(e.processed)&&Ot(e.total)&&e.processed<=e.total&&et(e,["phase","processed","total"]):!1}function Ph(e){return Oh(e)||vh(e)}function Rh(e){return ct(e)&&ve(e.href)&&typeof e.userAgent=="string"&&ve(e.sdkVersion)}function Ch(e){return ct(e)&&ve(e.code)&&typeof e.message=="string"}function kh(e){return e==="read"||e==="readwrite"}function Ot(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ca(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Lh(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function ve(e){return typeof e=="string"&&e.length>0}function et(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Zt=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards","user_game_data"],Is=[{key:"gameSaves",name:"游戏存档",description:"已废弃,将在 SDK 0.10.0 移除;新接入使用 user.games。",access:"declaration",risk:"high",config:{},methods:["gameSaves.list","gameSaves.sync","gameSaves.getFile","gameSaves.readParsedData"],conditions:["SDK < 0.10.0-0 保留兼容入口,保留原合同,不增加本版逐资源确认;需要有效 Steam 登录和宿主支持。"]},{key:"userInfo",name:"用户信息",description:"登录小程序并读取当前用户的授权信息。",access:"declaration",risk:"medium",config:{},methods:["auth.login","user.getInfo"],conditions:["继续执行黑盒登录、用户授权和可信手势规则。"]},{key:"steamLibrary",name:"Steam 游戏库",description:"读取当前用户授权的 Steam 游戏库。",access:"declaration",risk:"high",config:{},methods:["user.getSteamGameList"],conditions:["继续执行账号绑定和数据可用性规则。"]},{key:"share",name:"分享",description:"使用小程序分享、分享菜单和截图能力。",access:"declaration",risk:"medium",config:{},methods:["share.copyLink","share.showShareMenu","share.screenshot","share.screenshotLong"],conditions:["继续执行分享参数校验和 Host 支持检查。"]},{key:"storage",name:"键值存储",description:"读写按小程序隔离的简单键值数据。",access:"declaration",risk:"medium",config:{},methods:["storage.getStorage","storage.setStorage"],conditions:["仅用于简单键值存储,不包含文件系统。"]},{key:"cloud_storage",name:"云端存储",description:"读写按小程序和当前登录用户隔离的云端键值数据。",access:"declaration",risk:"medium",config:{},methods:["cloud.storage.getStorage","cloud.storage.setStorage","cloud.storage.removeItem","cloud.storage.getKeys"],conditions:["云端存储按登录用户隔离并受容量配额限制。"]},{key:"filesystem",name:"文件系统",description:"访问小程序沙盒文件和用户选择的外部文件。",access:"declaration",risk:"high",config:{},methods:["network.download","network.upload","files.pickFiles","files.pickDirectory","files.saveFile","file.create","file.remove","file.exists","file.readText","file.writeText","file.readBytes","file.writeBytes","file.stat","directory.create","directory.remove","directory.exists","directory.list"],conditions:["外部文件继续要求有效的用户选择、会话句柄和匹配的读写模式。"]},{key:"media",name:"媒体",description:"通过系统图库或相机选择图片、视频。",access:"declaration",risk:"high",config:{},methods:["media.pick"],conditions:["图库授权范围仅限本次用户选择的媒体,不包含任意文件或沙盒访问权;继续执行可信手势、Host 能力与会话资源规则。"]},{key:"clipboard",name:"剪贴板",description:"向系统剪贴板写入文本。",access:"declaration",risk:"medium",config:{},methods:["device.setClipboard"],conditions:["继续执行文本长度和 Host 支持限制。"]},{key:"leaderboard",name:"排行榜",description:"读写小程序云排行榜。",access:"declaration",risk:"medium",config:{},methods:["cloud.leaderboard.submit","cloud.leaderboard.getList","cloud.leaderboard.getCurrentUserEntry","cloud.leaderboard.deleteCurrentUserEntry","cloud.leaderboard.getInfo"],conditions:["排行榜必须已创建,用户和资源规则保持不变。"]},{key:"network",name:"网络",description:"通过 network 模块请求或下载外部资源。",access:"platform-approval",risk:"high",config:{useOfficialDomain:{type:"boolean",required:!1,default:!1,description:"是否申请访问小黑盒官方域名。"}},methods:["network.request","network.download","network.upload"],conditions:["声明后仍需平台批准,并继续执行网络安全策略。"]},{key:"companion",name:"桌面辅助应用",description:"下载、准备并运行随当前小程序版本发布的受管桌面程序。",access:"platform-approval",risk:"high",config:{},methods:["companion.getInfo","companion.getPreparationStatus","companion.prepare","companion.cancelPreparation","companion.getActiveSession","companion.launch","companion.session.write","companion.session.closeStdin","companion.session.terminate","companion.session.ackOutput","companion.openAttachment","companion.showNotification"],conditions:["声明后仍需平台批准,并继续执行可信用户手势、Host 能力和当前版本 Manifest 校验。"]},{key:"appProtocol",name:"应用协议执行",description:"执行任意小黑盒客户端协议。",access:"platform-approval",risk:"high",config:{},methods:["device.executeProtocol"],conditions:["最高危险权限:批准后该入口可执行任意协议,并绕过其他 SDK 能力权限及专用授权流程。"]},{key:"workspaceCards",name:"工作区卡片",description:"在已绑定游戏的桌面工作区展示受审核卡片。",access:"platform-approval",risk:"high",config:{},methods:["workspaceCards.requestRefresh"],conditions:["需平台批准、Host 支持与有效执行租约;不隐式授予网络或存储权限。"]},{key:"user_game_data",name:"游戏资料",description:"在精确资源声明范围内读取当前用户的游戏资料:明日方舟角色/养成与抽卡,以及黑神话悟空、任务栏英雄、影之刃零的云存档解析结果与文件。",access:"declaration",risk:"high",config:{resources:{type:"resource-map",required:!0,items:hr,description:"精确资源声明对象;每项必须填写 1~30 个 Unicode 码点的 purpose,不接受通配符或未开放资源。"}},methods:Vf,conditions:["逐项声明资源与用途,读取前需用户许可;未取得许可不查询个人来源。","文件与解析结果分别许可;本次许可仅当前实例有效,持久许可保存在本机。","同步会将原存档上传至小黑盒,向小程序交付原文件仍需 `save_files` 许可。","平台取数不授予小程序 `network` 权限;已交付的数据副本无法撤回。"]}];new Set(Zt);const xh=30;function Uh(e){if(typeof e!="string")throw new Error("purpose 必须是字符串");const t=e.trim(),r=Array.from(t);if(r.length<1||r.length>xh)throw new Error("purpose 去除首尾空白后必须为 1~30 个 Unicode 码点");if(r.some(n=>{const i=n.codePointAt(0);return i>=55296&&i<=57343}))throw new Error("purpose 包含非法 Unicode 字符");return t}function tn(e){return bu(e,!1)}function jh(e){return bu(e,!0)}function bu(e,t){if(!da(e))throw new Error("resources 必须是资源声明对象;每项资源必须填写 purpose");const r={};for(const n of Object.keys(e).sort()){const i=e[n];if(!da(i)||Object.keys(i).length!==1||!Object.prototype.hasOwnProperty.call(i,"purpose"))throw new Error(`resources.${n} 必须且只能包含 purpose`);let o;try{o=Uh(i.purpose)}catch(s){throw new Error(`resources.${n}: ${s.message}`)}if(!bt(n)){if(t&&/^game\.[a-z0-9_]+\.[a-z0-9_.]+$/.test(n))continue;throw new Error(`resources 包含未开放资源:${n}`)}r[n]={purpose:o}}return r}function zh(e){return hr.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function da(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Su(e,t,r,n){return JSON.stringify(["user-game-data-purpose-v1",e,t,r,n])}const Bh=new Set(Zt);function Hh(e){return Bh.has(e)}function Ve(e){if(!xr(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(!xr(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),!!Hh(o)){if(o==="network"){const s=n.config;if(!xr(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(o==="user_game_data"){const s=n.config;if(!xr(s))return{valid:!1,permissions:{}};try{const a=jh(s.resources);r[o]={key:o,status:n.status,config:{resources:a}}}catch{return{valid:!1,permissions:{}}}continue}if(n.config!==null&&n.config!==void 0&&(!xr(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 xr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const kn=["network","companion","appProtocol"];function Tu(e){if(!Ur(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>kn.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Ur(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(!Ur(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(!Ur(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Ur(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>kn.indexOf(n.key)-kn.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Fh(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Ve(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of kn)!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 _s(e){const t=Ve(e.runtimePermissions),r=Tu(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of Zt)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:Is.some(a=>a.key===s&&a.access==="declaration")?n[s]={key:s,status:"enabled",config:$h(s,e.declaredPermissions)}:s==="network"&&n.network&&(n.network.config.useOfficialDomain=n.network.status==="enabled"&&n.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(r.valid)for(const s of r.grant.entries)e.declaredPermissions[s.key]?.enabled!==!0||n[s.key]?.status==="enabled"||(n[s.key]=s,i.push(s.key));const o=Ou(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:Zt.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function $h(e,t){const r=Is.find(i=>i.key===e);if(!r)return{};const n={};for(const[i,o]of Object.entries(r.config))o.type==="resource-map"&&(n[i]=i==="resources"?tn(t[e]?.resources):{});return n}function Ou(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ur(e,t){return Ou(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const _r=["identity","profile","steam_account"],Vh=/^[a-z][a-z0-9-]{0,31}$/,vu=["COMPANION_UNSUPPORTED","COMPANION_PREVIEW_UNSUPPORTED","COMPANION_NOT_DECLARED","COMPANION_TARGET_UNSUPPORTED","COMPANION_NOT_PREPARED","COMPANION_PREPARATION_CANCELLED","COMPANION_DOWNLOAD_FAILED","COMPANION_DESCRIPTOR_UNAVAILABLE","COMPANION_ARCHIVE_INVALID","COMPANION_INTEGRITY_FAILED","COMPANION_ENTRYPOINT_INVALID","COMPANION_USER_CANCELLED","COMPANION_ELEVATION_DENIED","COMPANION_OS_BLOCKED","COMPANION_LAUNCH_FAILED","COMPANION_SESSION_VERSION_MISMATCH","COMPANION_SESSION_OWNERSHIP_LOST","COMPANION_SESSION_EXITED","COMPANION_PIPE_CLOSED","COMPANION_OUTPUT_LIMIT","COMPANION_PROCESS_CRASHED","COMPANION_ATTACHMENT_NOT_FOUND","COMPANION_NOTIFICATION_UNAVAILABLE","COMPANION_TERMINATE_FAILED"];var ua;function Ae(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);const d=s.prototype,u=Object.keys(d);for(let l=0;l<u.length;l++){const f=u[l];f in a||(a[f]=d[f].bind(a))}}const i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(a){var c;const d=r?.Parent?new o:this;n(d,a),(c=d._zod).deferred??(c.deferred=[]);for(const u of d._zod.deferred)u();return d}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class Zr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(ua=globalThis).__zod_globalConfig??(ua.__zod_globalConfig={});const la=globalThis.__zod_globalConfig;function Cr(e){return e&&Object.assign(la,e),la}function Gh(e,t){return typeof t=="bigint"?t.toString():t}function Qh(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Pu(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const fa=Symbol("evaluating");function Ge(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==fa)return n===void 0&&(n=fa,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}const Ru="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function qh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ma(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yh(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function rt(e){return{}}function Wh(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Zh={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Qr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Kh(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Cu(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function wn(e){return typeof e=="string"?e:e?.message}function cn(e,t,r){const n=e.message?e.message:wn(e.inst?._zod.def?.error?.(e))??wn(t?.error?.(e))??wn(r.customError?.(e))??wn(r.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}const ku=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Gh,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Jh=Ae("$ZodError",ku),gi=Ae("$ZodError",ku,{Parent:Error}),Xh=e=>(t,r,n,i)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Zr;if(s.issues.length){const a=new(i?.Err??e)(s.issues.map(c=>cn(c,o,Cr())));throw Ru(a,i?.callee),a}return s.value},eg=Xh(gi),tg=e=>async(t,r,n,i)=>{const o=n?{...n,async:!0}:{async:!0};let s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(i?.Err??e)(s.issues.map(c=>cn(c,o,Cr())));throw Ru(a,i?.callee),a}return s.value},rg=tg(gi),ng=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new Zr;return o.issues.length?{success:!1,error:new(e??Jh)(o.issues.map(s=>cn(s,i,Cr())))}:{success:!0,data:o.value}},Lu=ng(gi),ig=e=>async(t,r,n)=>{const i=n?{...n,async:!0}:{async:!0};let o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>cn(s,i,Cr())))}:{success:!0,data:o.value}},xu=ig(gi),og=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},sg=/^-?\d+$/,ag=/^-?\d+(?:\.\d+)?$/,cg=/^null$/i,pi=Ae("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Uu={number:"number",bigint:"bigint",object:"date"},dg=Ae("$ZodCheckLessThan",(e,t)=>{pi.init(e,t);const r=Uu[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ug=Ae("$ZodCheckGreaterThan",(e,t)=>{pi.init(e,t);const r=Uu[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),lg=Ae("$ZodCheckNumberFormat",(e,t)=>{pi.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,o]=Zh[t.format];e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,a.minimum=i,a.maximum=o,r&&(a.pattern=sg)}),e._zod.check=s=>{const a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),fg=Ae("$ZodCheckStringFormat",(e,t)=>{var r,n;pi.init(e,t),e._zod.onattach.push(i=>{const o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),mg=Ae("$ZodCheckRegex",(e,t)=>{fg.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),hg={major:4,minor:4,patch:3},dt=Ae("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=hg;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const i of n)for(const o of i._zod.onattach)o(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(s,a,c)=>{let d=Qr(s),u;for(const l of a){if(l._zod.def.when){if(Kh(s)||!l._zod.def.when(s))continue}else if(d)continue;const f=s.issues.length,h=l._zod.check(s);if(h instanceof Promise&&c?.async===!1)throw new Zr;if(u||h instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await h,s.issues.length!==f&&(d||(d=Qr(s,f)))});else{if(s.issues.length===f)continue;d||(d=Qr(s,f))}}return u?u.then(()=>s):s},o=(s,a,c)=>{if(Qr(s))return s.aborted=!0,s;const d=i(a,n,c);if(d instanceof Promise){if(c.async===!1)throw new Zr;return d.then(u=>e._zod.parse(u,c))}return e._zod.parse(d,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){const d=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return d instanceof Promise?d.then(u=>o(u,s,a)):o(d,s,a)}const c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Zr;return c.then(d=>i(d,n,a))}return i(c,n,a)}}Ge(e,"~standard",()=>({validate:i=>{try{const o=Lu(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return xu(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),gg=Ae("$ZodString",(e,t)=>{dt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??og(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ju=Ae("$ZodNumber",(e,t)=>{dt.init(e,t),e._zod.pattern=e._zod.bag.pattern??ag,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),pg=Ae("$ZodNumberFormat",(e,t)=>{lg.init(e,t),ju.init(e,t)}),yg=Ae("$ZodNull",(e,t)=>{dt.init(e,t),e._zod.pattern=cg,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),Eg=Ae("$ZodNever",(e,t)=>{dt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function ha(e,t,r){e.issues.length&&t.issues.push(...Cu(r,e.issues)),t.value[r]=e.value}const wg=Ae("$ZodArray",(e,t)=>{dt.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const o=[];for(let s=0;s<i.length;s++){const a=i[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(d=>ha(d,r,s))):ha(c,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function ei(e,t,r,n,i,o){const s=r in n;if(e.issues.length){if(i&&o&&!s)return;t.issues.push(...Cu(r,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?s&&(t.value[r]=void 0):t.value[r]=e.value}function Ig(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=Wh(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function _g(e,t,r,n,i,o){const s=[],a=i.keySet,c=i.catchall._zod,d=c.def.type,u=c.optin==="optional",l=c.optout==="optional";for(const f in t){if(f==="__proto__"||a.has(f))continue;if(d==="never"){s.push(f);continue}const h=c.run({value:t[f],issues:[]},n);h instanceof Promise?e.push(h.then(m=>ei(m,r,f,t,u,l))):ei(h,r,f,t,u,l)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>r):r}const Ag=Ae("$ZodObject",(e,t)=>{if(dt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}const n=Qh(()=>Ig(t));Ge(e._zod,"propValues",()=>{const a=t.shape,c={};for(const d in a){const u=a[d]._zod;if(u.values){c[d]??(c[d]=new Set);for(const l of u.values)c[d].add(l)}}return c});const i=qh,o=t.catchall;let s;e._zod.parse=(a,c)=>{s??(s=n.value);const d=a.value;if(!i(d))return a.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),a;a.value={};const u=[],l=s.shape;for(const f of s.keys){const h=l[f],m=h._zod.optin==="optional",E=h._zod.optout==="optional",N=h._zod.run({value:d[f],issues:[]},c);N instanceof Promise?u.push(N.then(A=>ei(A,a,f,d,m,E))):ei(N,a,f,d,m,E)}return o?_g(u,d,a,c,n.value,e):u.length?Promise.all(u).then(()=>a):a}});function ga(e,t,r,n){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const i=e.filter(o=>!Qr(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>cn(s,n,Cr())))}),t)}const Dg=Ae("$ZodUnion",(e,t)=>{dt.init(e,t),Ge(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Ge(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Ge(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),Ge(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>Pu(i.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let o=!1;const s=[];for(const a of t.options){const c=a._zod.run({value:n.value,issues:[]},i);if(c instanceof Promise)s.push(c),o=!0;else{if(c.issues.length===0)return c;s.push(c)}}return o?Promise.all(s).then(a=>ga(a,n,e,i)):ga(s,n,e,i)}}),Ng=Ae("$ZodLiteral",(e,t)=>{if(dt.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?ma(n):n?ma(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,i)=>{const o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}});function pa(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Mg=Ae("$ZodOptional",(e,t)=>{dt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ge(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ge(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Pu(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const i=r.value,o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>pa(s,i)):pa(o,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),bg=Ae("$ZodLazy",(e,t)=>{dt.init(e,t),Ge(e._zod,"innerType",()=>{const r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),Ge(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Ge(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Ge(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Ge(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)});function Sg(e,t){return new e({type:"string",...rt()})}function Tg(e,t){return new e({type:"number",checks:[],...rt()})}function Og(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...rt()})}function vg(e,t){return new e({type:"null",...rt()})}function Pg(e,t){return new e({type:"never",...rt()})}function se(e,t){return new dg({check:"less_than",...rt(),value:e,inclusive:!0})}function ae(e,t){return new ug({check:"greater_than",...rt(),value:e,inclusive:!0})}function ce(e,t){return new mg({check:"string_format",format:"regex",...rt(),pattern:e})}Cr({jitless:!0});function Rg(e){if(e.schema_version!==1||!/^[a-f0-9]{32}$/.test(e.session_id)||!Number.isSafeInteger(e.revision)||e.revision<1||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(e.sdk_version)||!e.declared_permissions||typeof e.declared_permissions!="object"||Array.isArray(e.declared_permissions)||!Array.isArray(e.platforms)||e.platforms.some(r=>!["android","ios","ohos","windows","macos","linux"].includes(r))||new Set(e.platforms).size!==e.platforms.length)throw new Error("开发快照无效");const t={};for(const r of Zt){const n=e.declared_permissions[r];if(n){if(typeof n.enabled!="boolean")throw new Error("开发权限声明无效");if(r==="network"){t[r]={enabled:n.enabled,useOfficialDomain:n.useOfficialDomain===!0};continue}if(r==="user_game_data"){t[r]={enabled:n.enabled,resources:tn(n.resources)};continue}t[r]={enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!Zt.includes(r)))throw new Error("开发权限声明无效");if(e.companion_manifest_sha256!==void 0&&!/^[a-f0-9]{64}$/.test(e.companion_manifest_sha256))throw new Error("开发产物摘要无效");return JSON.stringify({schema_version:1,session_id:e.session_id,revision:e.revision,sdk_version:e.sdk_version,declared_permissions:t,platforms:[...e.platforms].sort(),...e.companion_manifest_sha256?{companion_manifest_sha256:e.companion_manifest_sha256}:{}})}function Cg(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return Rg(t)===e?t:void 0}catch{return}}const ya={$defs:{ArkProfile:{type:"object",properties:{uid:{type:"string"},name:{type:"string"},level:{type:"number"},avatar:{$ref:"#/$defs/ArkPlayerAvatar"},characterCount:{type:"number"},totalCharacterCount:{type:"number"},mainStageProgress:{type:"string"},rogueLevel:{type:"number"},campaignFullKillCount:{type:"number"},tag:{type:"string"},observedAt:{anyOf:[{type:"string"},{type:"number"}]},lastOnlineTs:{anyOf:[{type:"string"},{type:"number"}]},registerTs:{anyOf:[{type:"string"},{type:"number"}]},changeTime:{anyOf:[{type:"string"},{type:"number"}]},operators:{type:"array",items:{$ref:"#/$defs/ArkOperator"}}},required:["uid","name","level","characterCount","totalCharacterCount","mainStageProgress","rogueLevel","campaignFullKillCount","tag"],additionalProperties:!1},ArkPlayerAvatar:{type:"object",properties:{url:{type:"string"},type:{type:"string"},id:{type:"string"}},required:["url","type","id"],additionalProperties:!1},ArkOperator:{type:"object",properties:{characterId:{type:"string"},name:{type:"string"},profession:{type:"string"},evolvePhase:{type:"number"},potentialRank:{type:"number"}},required:["characterId","name","profession","evolvePhase","potentialRank"],additionalProperties:!1},ArkGachaAnalysis:{type:"object",properties:{uid:{type:"string"},year:{type:"number"},total:{type:"number"},srCount:{type:"number"},upCount:{type:"number"},missCount:{type:"number"},careerEvaluation:{type:"string"},careerIsLucky:{anyOf:[{const:!1},{const:!0}]},pools:{type:"array",items:{$ref:"#/$defs/ArkGachaPoolStat"}},records:{type:"array",items:{$ref:"#/$defs/ArkGachaAnalysisRecord"}},luckyLottery:{type:"array",items:{type:"number"}}},required:["uid","year","total","srCount","upCount","missCount","careerEvaluation","careerIsLucky","pools","records","luckyLottery"],additionalProperties:!1},ArkGachaPoolStat:{type:"object",properties:{poolId:{type:"string"},totalCost:{type:"number"},ssrCount:{type:"number"},ssrCost:{type:"number"},records:{type:"array",items:{$ref:"#/$defs/ArkGachaAnalysisRecord"}}},required:["poolId","totalCost","ssrCount","ssrCost","records"],additionalProperties:!1},ArkGachaAnalysisRecord:{type:"object",properties:{name:{type:"string"},timestamp:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},diff:{type:"number"},negativeDiff:{type:"number"},tag:{type:"string"},missUp:{anyOf:[{const:!1},{const:!0}]}},required:["name","timestamp","diff","negativeDiff","tag","missUp"],additionalProperties:!1},GachaRecord:{type:"object",properties:{id:{type:"string"},name:{type:"string"},pool:{type:"string"},rarity:{type:"number"},timestamp:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["id","name","pool","rarity","timestamp"],additionalProperties:!1},BlackMythWukongSave:{type:"object",properties:{level:{type:"number"},newGamePlusCount:{type:"number"},gameTotalTime:{type:"number"},playerDeathCount:{type:"number"},totalMoney:{type:"string"},meditationList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},monsterCollectionList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},returnPointList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},activatedWeaponIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},activatedEquipIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},magicArtifactList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},soulSkillIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},huluIdLits:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},wineIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},wineIdPartnerList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},cropIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},recipeIdList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},wearedWaeponId:{type:"string"},wearedMagicArtifact:{type:"number"},wearedSoulSkill:{type:"number"},wearedHead:{type:"number"},wearedUpware:{type:"number"},wearedArm:{type:"number"},wearedFoot:{type:"number"},wearedHulu:{type:"number"},wearedAccessoryList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},spellQishu:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},spellShenfa:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},spellHaomao:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},spellBianshen:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},bossRushBossgroup:{$ref:"#/$defs/BlackMythWukongBossRushData"},bossRushRefight:{$ref:"#/$defs/BlackMythWukongBossRefightData"}},required:[],additionalProperties:!1},BlackMythWukongBossRushData:{type:"object",properties:{bossGroups:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongBossRushRecord"}}]}},required:[],additionalProperties:!1},BlackMythWukongBossRushRecord:{type:"object",properties:{bossGroupId:{type:"number"},isPassed:{anyOf:[{const:!1},{const:!0}]},bestRecords:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongBattleRecord"}}]},encounterBossIndex:{type:"number"},battleCount:{type:"number"}},required:[],additionalProperties:!1},BlackMythWukongBattleRecord:{type:"object",properties:{battleId:{type:"string"},battleData:{$ref:"#/$defs/BlackMythWukongBattleData"}},required:[],additionalProperties:!1},BlackMythWukongBattleData:{type:"object",properties:{totalTime:{type:"number"},score:{type:"number"},debuffList:{anyOf:[{type:"null"},{type:"array",items:{type:"number"}}]},targetId:{type:"number"},archiveTime:{type:"string"},roleBase:{$ref:"#/$defs/BlackMythWukongRoleBase"},battleStyleInfo:{$ref:"#/$defs/BlackMythWukongBattleStyleInfo"},damageInfo:{$ref:"#/$defs/BlackMythWukongDamageInfo"}},required:[],additionalProperties:!1},BlackMythWukongRoleBase:{type:"object",properties:{level:{type:"number"},atk:{type:"number"},hpMax:{type:"number"},staminaMax:{type:"number"},mpMax:{type:"number"}},required:[],additionalProperties:!1},BlackMythWukongBattleStyleInfo:{type:"object",properties:{spellList:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongCast"}}]},fabaoInfo:{$ref:"#/$defs/BlackMythWukongCast"},soulInfo:{$ref:"#/$defs/BlackMythWukongCast"},itemCount:{type:"number"},wineCount:{type:"number"},rollCount:{type:"number"},defuseCount:{type:"number"},fourPeCount:{type:"number"}},required:[],additionalProperties:!1},BlackMythWukongCast:{type:"object",properties:{castId:{type:"number"},castCount:{type:"number"}},required:[],additionalProperties:!1},BlackMythWukongDamageInfo:{type:"object",properties:{totalDamage:{anyOf:[{type:"string"},{type:"number"}]},hightestDamage:{anyOf:[{type:"string"},{type:"number"}]},criticalDmgRate:{type:"number"},totalBeDamaged:{anyOf:[{type:"string"},{type:"number"}]},criticalDmgTotal:{anyOf:[{type:"string"},{type:"number"}]},elemDotDmgTotal:{anyOf:[{type:"string"},{type:"number"}]},elemDotDmgRate:{type:"number"}},required:[],additionalProperties:!1},BlackMythWukongBossRefightData:{type:"object",properties:{bossList:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongBossRefightRecord"}}]}},required:[],additionalProperties:!1},BlackMythWukongBossRefightRecord:{type:"object",properties:{bossId:{type:"number"},passedMaxLevel:{type:"number"},lastChallengeLevel:{type:"number"},bestRecords:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongBattleRecord"}}]},refightStatisticsList:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/BlackMythWukongRefightStatistic"}}]}},required:[],additionalProperties:!1},BlackMythWukongRefightStatistic:{type:"object",properties:{challengeLevel:{type:"number"},battleCount:{type:"number"}},required:[],additionalProperties:!1},TaskBarHeroSave:{type:"object",properties:{update_time:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},game_version:{type:"string"},account_version:{type:"string"},play_time:{type:"number"},last_saved_time:{type:"string"},common:{$ref:"#/$defs/TaskBarHeroCommon"},summary:{$ref:"#/$defs/TaskBarHeroSummary"},heroes:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroHero"}}]},rune_save_data:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroRune"}}]},pets:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroPet"}}]},attributes:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroAttribute"}}]},inventory_slots:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroItemSlot"}}]},stash_slots:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroItemSlot"}}]},item_instances:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroItemInstance"}}]},values:{$ref:"#/$defs/TaskBarHeroValueSummary"}},required:["update_time","game_version","account_version","play_time","last_saved_time","common","summary","heroes","rune_save_data","pets","attributes","inventory_slots","stash_slots","item_instances","values"],additionalProperties:!1},TaskBarHeroCommon:{type:"object",properties:{max_completed_stage:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},current_stage_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},current_stage_wave:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},arranged_hero_keys:{anyOf:[{type:"null"},{type:"array",items:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}}]},arranged_pet_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["max_completed_stage","current_stage_key","current_stage_wave","arranged_hero_keys","arranged_pet_key"],additionalProperties:!1},TaskBarHeroSummary:{type:"object",properties:{max_hero_level:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},learned_rune_count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},unlocked_hero:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},total_hero:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},item_count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},inventory_slots:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},stash_slots:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["max_hero_level","learned_rune_count","unlocked_hero","total_hero","item_count","inventory_slots","stash_slots"],additionalProperties:!1},TaskBarHeroHero:{type:"object",properties:{hero_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},hero_level:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},is_unlock:{anyOf:[{const:!1},{const:!0}]},hero_exp:{type:"number"},ability_point:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},allocated_hero_ability_point:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},equipped_item_ids:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},equipped_skill_keys:{anyOf:[{type:"null"},{type:"array",items:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}}]},unlocked_attribute_group_keys:{anyOf:[{type:"null"},{type:"array",items:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}}]}},required:["hero_key","hero_level","is_unlock","hero_exp","ability_point","allocated_hero_ability_point","equipped_item_ids","equipped_skill_keys","unlocked_attribute_group_keys"],additionalProperties:!1},TaskBarHeroRune:{type:"object",properties:{rune_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},level:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["rune_key","level"],additionalProperties:!1},TaskBarHeroPet:{type:"object",properties:{pet_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},is_unlock:{anyOf:[{const:!1},{const:!0}]}},required:["pet_key","is_unlock"],additionalProperties:!1},TaskBarHeroAttribute:{type:"object",properties:{key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},level:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["key","level"],additionalProperties:!1},TaskBarHeroItemSlot:{type:"object",properties:{index:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},item_unique_id:{type:"string"},is_unlock:{anyOf:[{const:!1},{const:!0}]},is_unlocked_by_rune:{anyOf:[{const:!1},{const:!0}]}},required:["index","item_unique_id","is_unlock","is_unlocked_by_rune"],additionalProperties:!1},TaskBarHeroItemInstance:{type:"object",properties:{item_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},unique_id:{type:"string"},is_chaotic:{anyOf:[{const:!1},{const:!0}]},is_blocked:{anyOf:[{const:!1},{const:!0}]},is_server_pending_item:{anyOf:[{const:!1},{const:!0}]},enchant_count:{anyOf:[{type:"null"},{type:"array",items:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}}]},enchant_data:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/TaskBarHeroEnchantData"}}]},item_get_source_type:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},decoration_applied_total_count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},engraving_applied_total_count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},inscription_applied_total_count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["item_key","unique_id","is_chaotic","is_blocked","is_server_pending_item","enchant_count","enchant_data","item_get_source_type","decoration_applied_total_count","engraving_applied_total_count","inscription_applied_total_count"],additionalProperties:!1},TaskBarHeroEnchantData:{type:"object",properties:{stat_mod_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},tier:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},value:{type:"number"},recipe_type:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},mod_type:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},material_key:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},stat_type:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["stat_mod_key","tier","value","recipe_type","mod_type","material_key","stat_type"],additionalProperties:!1},TaskBarHeroValueSummary:{type:"object",properties:{market_value:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},price_state:{type:"string"},currency:{type:"string"}},required:["market_value","price_state","currency"],additionalProperties:!1},PhantomBladeZeroSave:{type:"object",properties:{defaultSlot:{type:"string"},slots:{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroSaveSlot"}}},required:["defaultSlot","slots"],additionalProperties:!1},PhantomBladeZeroSaveSlot:{type:"object",properties:{slot:{type:"string"},head:{$ref:"#/$defs/PhantomBladeZeroSlotHead"},firstClear:{$ref:"#/$defs/PhantomBladeZeroSlotFirstClear"},progress:{$ref:"#/$defs/PhantomBladeZeroSlotProgress"},combat:{$ref:"#/$defs/PhantomBladeZeroSlotCombat"},achievements:{$ref:"#/$defs/PhantomBladeZeroSlotAchievementSummary"},bosses:{$ref:"#/$defs/PhantomBladeZeroSlotBossSummary"},collectibles:{$ref:"#/$defs/PhantomBladeZeroSlotCollectibles"},quest_details:{anyOf:[{type:"null"},{$ref:"#/$defs/PhantomBladeZeroQuestDetails"}]},inventory_details:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroInventoryItem"}}]},detail:{$ref:"#/$defs/PhantomBladeZeroSlotDetail"}},required:["slot","head","firstClear","progress","combat","achievements","bosses","collectibles","quest_details","inventory_details","detail"],additionalProperties:!1},PhantomBladeZeroSlotHead:{type:"object",properties:{saveTime:{type:"string"},currentLevel:{type:"string"},cycle:{type:"string"},difficulty:{$ref:"#/$defs/PhantomBladeZeroSlotDifficulty"}},required:["saveTime","currentLevel","cycle","difficulty"],additionalProperties:!1},PhantomBladeZeroSlotDifficulty:{type:"object",properties:{raw:{type:"number"},name:{type:"string"}},required:["raw","name"],additionalProperties:!1},PhantomBladeZeroSlotFirstClear:{type:"object",properties:{clearDate:{$ref:"#/$defs/PhantomBladeZeroUnavailableValue"},cycles:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroClearanceRecord"}}]}},required:["clearDate","cycles"],additionalProperties:!1},PhantomBladeZeroUnavailableValue:{type:"object",properties:{value:{type:"null"},reason:{type:"string"}},required:["value","reason"],additionalProperties:!1},PhantomBladeZeroClearanceRecord:{type:"object",properties:{Cycle:{anyOf:[{type:"null"},{type:"number"}]},Ending:{type:"number"},Difficulty:{type:"number"},GameTime:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},Completion:{type:"number"},DiedTimes:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["Ending","Difficulty","GameTime","Completion","DiedTimes"],additionalProperties:!1},PhantomBladeZeroSlotProgress:{type:"object",properties:{playTimeSeconds:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},playTime:{type:"string"},lastLaunch:{$ref:"#/$defs/PhantomBladeZeroUnavailableValue"},narrativePercentage:{type:"number"},chapter:{type:"string"},remainingDays:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["playTimeSeconds","playTime","lastLaunch","narrativePercentage","chapter","remainingDays"],additionalProperties:!1},PhantomBladeZeroSlotCombat:{type:"object",properties:{loadout:{$ref:"#/$defs/PhantomBladeZeroSlotLoadout"},totalDeaths:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},cycleDeaths:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},bossKillTotal:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},currentMainWeapon:{anyOf:[{type:"null"},{$ref:"#/$defs/PhantomBladeZeroNamedItem"}]},mainWeapon:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},currentShaqi:{anyOf:[{type:"null"},{$ref:"#/$defs/PhantomBladeZeroNamedItem"}]},shaqi:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"}},required:["totalDeaths","cycleDeaths","bossKillTotal","mainWeapon","shaqi"],additionalProperties:!1},PhantomBladeZeroSlotLoadout:{type:"object",properties:{states:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroLoadoutState"}}]},main_weapons:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},shaqi_weapons:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},accessory_ids:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},top_medicine:{type:"string"},bottom_medicine:{type:"string"},current_weapon_index:{type:"number"},current_shaqi_weapon_index:{type:"number"}},required:["main_weapons","shaqi_weapons","accessory_ids","top_medicine","bottom_medicine","current_weapon_index","current_shaqi_weapon_index"],additionalProperties:!1},PhantomBladeZeroLoadoutState:{type:"object",properties:{category:{type:"string"},id:{type:"string"},level:{type:"number"},soul_forged:{anyOf:[{const:!1},{const:!0}]},reincarnation_count:{type:"number"}},required:["category","id"],additionalProperties:!1},PhantomBladeZeroNamedItem:{type:"object",properties:{id:{type:"string"},name:{type:"string"}},required:["id","name"],additionalProperties:!1},PhantomBladeZeroCollectionCount:{type:"object",properties:{unknown:{anyOf:[{type:"string"},{type:"number"}]},done:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},total:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["done","total"],additionalProperties:!1},PhantomBladeZeroSlotAchievementSummary:{type:"object",properties:{unlocked:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},total:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},reason:{type:"string"}},required:["unlocked","total","reason"],additionalProperties:!1},PhantomBladeZeroSlotBossSummary:{type:"object",properties:{groups:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroBossGroup"}}]}},required:["groups"],additionalProperties:!1},PhantomBladeZeroBossGroup:{type:"object",properties:{map:{type:"string"},mapName:{type:"string"},count:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},bosses:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroBoss"}}]}},required:["map","mapName","count","bosses"],additionalProperties:!1},PhantomBladeZeroBoss:{type:"object",properties:{id:{type:"string"},classPath:{type:"string"},map:{type:"string"},mapName:{type:"string"},encountered:{anyOf:[{const:!1},{const:!0}]},killed:{anyOf:[{const:!1},{const:!0}]},kill:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},attempt:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},bestTimeMs:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},records:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroBossRecord"}}]}},required:["id","classPath","map","mapName","encountered","killed","kill","attempt","bestTimeMs","records"],additionalProperties:!1},PhantomBladeZeroBossRecord:{type:"object",properties:{cycle:{type:"string"},diff:{type:"string"},diffName:{type:"string"},kill:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},attempt:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},bestTimeMs:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["cycle","diff","diffName","kill","attempt","bestTimeMs"],additionalProperties:!1},PhantomBladeZeroSlotCollectibles:{type:"object",properties:{overall:{$ref:"#/$defs/PhantomBladeZeroCollectionSummary"},craneBellCount:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},byBigMap:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroBigMapProgress"}}]},currentChapter:{$ref:"#/$defs/PhantomBladeZeroChapterProgress"}},required:["overall","craneBellCount","byBigMap","currentChapter"],additionalProperties:!1},PhantomBladeZeroCollectionSummary:{type:"object",properties:{bell:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},weapon:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},shaqi:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},accessory:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},medicine:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},challenge:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},hupo:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},heishi:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"},flower:{$ref:"#/$defs/PhantomBladeZeroCollectionCount"}},required:["bell","weapon","shaqi","accessory","medicine","challenge","hupo","heishi","flower"],additionalProperties:!1},PhantomBladeZeroBigMapProgress:{type:"object",properties:{unknown:{anyOf:[{type:"string"},{type:"number"}]},mapID:{type:"string"},name:{type:"string"},pct:{type:"number"},done:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},total:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},subMaps:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]}},required:["mapID","name","pct","done","total","subMaps"],additionalProperties:!1},PhantomBladeZeroChapterProgress:{type:"object",properties:{unknown:{anyOf:[{type:"string"},{type:"number"}]},mapID:{type:"string"},pct:{type:"number"},done:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},total:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},reason:{type:"string"}},required:["mapID","pct","done","total","reason"],additionalProperties:!1},PhantomBladeZeroQuestDetails:{type:"object",properties:{CurrentMainQuestPath:{type:"string"},CurrentTutorialQuestPath:{type:"string"},TrackedQuestPath:{type:"string"},TrackedBranchID:{type:"string"},TrackedTaskPointID:{type:"string"},ManualTrackingOptOut:{anyOf:[{const:!1},{const:!0}]},NarrativeSavedQuests:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroQuest"}}]}},required:["CurrentMainQuestPath","CurrentTutorialQuestPath","TrackedQuestPath","TrackedBranchID","TrackedTaskPointID","ManualTrackingOptOut","NarrativeSavedQuests"],additionalProperties:!1},PhantomBladeZeroQuest:{type:"object",properties:{QuestClass:{type:"string"},QuestCompletion:{type:"string"},QuestBranches:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroQuestBranch"}}]},CompletedBranches:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},ReachedStateNames:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]}},required:["QuestClass","QuestCompletion","QuestBranches","CompletedBranches","ReachedStateNames"],additionalProperties:!1},PhantomBladeZeroQuestBranch:{type:"object",properties:{BranchID:{type:"string"},TasksProgress:{anyOf:[{type:"null"},{type:"array",items:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}}]},BranchType:{type:"string"}},required:["BranchID","TasksProgress","BranchType"],additionalProperties:!1},PhantomBladeZeroInventoryItem:{type:"object",properties:{id:{type:"string"},amount:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]}},required:["id","amount"],additionalProperties:!1},PhantomBladeZeroSlotDetail:{type:"object",properties:{bell:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroBellDetail"}}]},weapon:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroItemDetail"}}]},shaqi:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroItemDetail"}}]},accessory:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroItemDetail"}}]},medicine:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroItemDetail"}}]},challenge:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroChallengeDetail"}}]},hupo:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroWorldItemDetail"}}]},heishi:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroWorldItemDetail"}}]},flower:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroItemDetail"}}]},achievements:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroAchievementDetail"}}]}},required:["bell","weapon","shaqi","accessory","medicine","challenge","hupo","heishi","flower","achievements"],additionalProperties:!1},PhantomBladeZeroBellDetail:{type:"object",properties:{unknown:{anyOf:[{const:!1},{const:!0}]},id:{type:"string"},done:{anyOf:[{const:!1},{const:!0}]},equip:{anyOf:[{const:!1},{const:!0}]}},required:["id","done","equip"],additionalProperties:!1},PhantomBladeZeroItemDetail:{type:"object",properties:{level:{type:"number"},soul_forged:{anyOf:[{const:!1},{const:!0}]},reincarnation_count:{type:"number"},unknown:{anyOf:[{const:!1},{const:!0}]},id:{type:"string"},name:{type:"string"},done:{anyOf:[{const:!1},{const:!0}]},equip:{anyOf:[{const:!1},{const:!0}]},locs:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroLocation"}}]}},required:["id","name","done","equip","locs"],additionalProperties:!1},PhantomBladeZeroLocation:{type:"object",properties:{map:{type:"string"},mapName:{type:"string"},x:{type:"number"},y:{type:"number"},z:{type:"number"}},required:["map","mapName","x","y","z"],additionalProperties:!1},PhantomBladeZeroChallengeDetail:{type:"object",properties:{key:{type:"string"},unknown:{anyOf:[{const:!1},{const:!0}]},index:{anyOf:[{type:"integer",minimum:-9007199254740991,maximum:9007199254740991},{type:"string",pattern:"^-?(0|[1-9][0-9]*)$"}]},guids:{anyOf:[{type:"null"},{type:"array",items:{type:"string"}}]},done:{anyOf:[{const:!1},{const:!0}]},locs:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroLocation"}}]}},required:["index","guids","done","locs"],additionalProperties:!1},PhantomBladeZeroWorldItemDetail:{type:"object",properties:{key:{type:"string"},unknown:{anyOf:[{const:!1},{const:!0}]},id:{type:"string"},saveGuid:{type:"string"},mobDomain:{type:"string"},done:{anyOf:[{const:!1},{const:!0}]},locs:{anyOf:[{type:"null"},{type:"array",items:{$ref:"#/$defs/PhantomBladeZeroLocation"}}]}},required:["id","saveGuid","mobDomain","done","locs"],additionalProperties:!1},PhantomBladeZeroAchievementDetail:{type:"object",properties:{id:{type:"string"},name:{type:"string"},desc:{type:"string"},grade:{type:"string"},hidden:{anyOf:[{const:!1},{const:!0}]},done:{anyOf:[{const:!1},{const:!0}]}},required:["id","name","desc","grade","hidden","done"],additionalProperties:!1},UserGameDataSaveFilePage:{type:"object",properties:{items:{type:"array",items:{$ref:"#/$defs/UserGameDataSaveInfo"}},hasMore:{const:!1}},required:["items","hasMore"],additionalProperties:!1},UserGameDataSaveInfo:{type:"object",properties:{saveId:{type:"string"},createdAt:{type:"string"},files:{type:"array",items:{$ref:"#/$defs/UserGameDataSaveFileInfo"}}},required:["saveId","createdAt","files"],additionalProperties:!1},UserGameDataSaveFileInfo:{type:"object",properties:{fileId:{type:"string"},name:{type:"string"},sizeBytes:{type:"number"},modifiedAt:{type:"string"}},required:["fileId","name","sizeBytes","modifiedAt"],additionalProperties:!1}},contracts:{"ark.profile":{$ref:"#/$defs/ArkProfile"},"ark.gacha-analysis":{$ref:"#/$defs/ArkGachaAnalysis"},"ark.gacha-record-page":{type:"object",properties:{items:{type:"array",items:{$ref:"#/$defs/GachaRecord"}},nextCursor:{type:"string"},hasMore:{anyOf:[{const:!1},{const:!0}]},total:{type:"number"}},required:["items","hasMore"],additionalProperties:!1},"black_myth_wukong.save":{$ref:"#/$defs/BlackMythWukongSave"},"task_bar_hero.save":{$ref:"#/$defs/TaskBarHeroSave"},"phantom_blade_zero.save":{$ref:"#/$defs/PhantomBladeZeroSave"},"save-file-page":{$ref:"#/$defs/UserGameDataSaveFilePage"}}},wt=Ae("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");dt.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>eg(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Lu(e,r,n),e.parseAsync=async(r,n)=>rg(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>xu(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>Yh(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),kg=Ae("ZodMiniString",(e,t)=>{gg.init(e,t),wt.init(e,t)});function P(e){return Sg(kg)}const zu=Ae("ZodMiniNumber",(e,t)=>{ju.init(e,t),wt.init(e,t)});function $(e){return Tg(zu)}const Lg=Ae("ZodMiniNumberFormat",(e,t)=>{pg.init(e,t),zu.init(e,t)});function de(e){return Og(Lg)}const xg=Ae("ZodMiniNull",(e,t)=>{yg.init(e,t),wt.init(e,t)});function te(e){return vg(xg)}const Ug=Ae("ZodMiniNever",(e,t)=>{Eg.init(e,t),wt.init(e,t)});function jg(e){return Pg(Ug)}const zg=Ae("ZodMiniArray",(e,t)=>{wg.init(e,t),wt.init(e,t)});function J(e,t){return new zg({type:"array",element:e,...rt()})}const Bg=Ae("ZodMiniObject",(e,t)=>{Ag.init(e,t),wt.init(e,t),Ge(e,"shape",()=>t.shape)});function oe(e,t){return new Bg({type:"object",shape:e,catchall:jg(),...rt()})}const Hg=Ae("ZodMiniUnion",(e,t)=>{Dg.init(e,t),wt.init(e,t)});function v(e,t){return new Hg({type:"union",options:e,...rt()})}const Fg=Ae("ZodMiniLiteral",(e,t)=>{Ng.init(e,t),wt.init(e,t)});function le(e,t){return new Fg({type:"literal",values:Array.isArray(e)?e:[e],...rt()})}const $g=Ae("ZodMiniOptional",(e,t)=>{Mg.init(e,t),wt.init(e,t)});function V(e){return new $g({type:"optional",innerType:e})}const Vg=Ae("ZodMiniLazy",(e,t)=>{bg.init(e,t),wt.init(e,t)});function q(e){return new Vg({type:"lazy",getter:e})}const Y={ArkProfile:oe({uid:P(),name:P(),level:$(),avatar:V(q(()=>Y.ArkPlayerAvatar)),characterCount:$(),totalCharacterCount:$(),mainStageProgress:P(),rogueLevel:$(),campaignFullKillCount:$(),tag:P(),observedAt:V(v([P(),$()])),lastOnlineTs:V(v([P(),$()])),registerTs:V(v([P(),$()])),changeTime:V(v([P(),$()])),operators:V(J(q(()=>Y.ArkOperator)))}),ArkPlayerAvatar:oe({url:P(),type:P(),id:P()}),ArkOperator:oe({characterId:P(),name:P(),profession:P(),evolvePhase:$(),potentialRank:$()}),ArkGachaAnalysis:oe({uid:P(),year:$(),total:$(),srCount:$(),upCount:$(),missCount:$(),careerEvaluation:P(),careerIsLucky:v([le(!1),le(!0)]),pools:J(q(()=>Y.ArkGachaPoolStat)),records:J(q(()=>Y.ArkGachaAnalysisRecord)),luckyLottery:J($())}),ArkGachaPoolStat:oe({poolId:P(),totalCost:$(),ssrCount:$(),ssrCost:$(),records:J(q(()=>Y.ArkGachaAnalysisRecord))}),ArkGachaAnalysisRecord:oe({name:P(),timestamp:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),diff:$(),negativeDiff:$(),tag:P(),missUp:v([le(!1),le(!0)])}),GachaRecord:oe({id:P(),name:P(),pool:P(),rarity:$(),timestamp:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),BlackMythWukongSave:oe({level:V($()),newGamePlusCount:V($()),gameTotalTime:V($()),playerDeathCount:V($()),totalMoney:V(P()),meditationList:V(v([te(),J($())])),monsterCollectionList:V(v([te(),J($())])),returnPointList:V(v([te(),J($())])),activatedWeaponIdList:V(v([te(),J(P())])),activatedEquipIdList:V(v([te(),J($())])),magicArtifactList:V(v([te(),J($())])),soulSkillIdList:V(v([te(),J($())])),huluIdLits:V(v([te(),J($())])),wineIdList:V(v([te(),J($())])),wineIdPartnerList:V(v([te(),J($())])),cropIdList:V(v([te(),J($())])),recipeIdList:V(v([te(),J($())])),wearedWaeponId:V(P()),wearedMagicArtifact:V($()),wearedSoulSkill:V($()),wearedHead:V($()),wearedUpware:V($()),wearedArm:V($()),wearedFoot:V($()),wearedHulu:V($()),wearedAccessoryList:V(v([te(),J($())])),spellQishu:V(v([te(),J($())])),spellShenfa:V(v([te(),J($())])),spellHaomao:V(v([te(),J($())])),spellBianshen:V(v([te(),J($())])),bossRushBossgroup:V(q(()=>Y.BlackMythWukongBossRushData)),bossRushRefight:V(q(()=>Y.BlackMythWukongBossRefightData))}),BlackMythWukongBossRushData:oe({bossGroups:V(v([te(),J(q(()=>Y.BlackMythWukongBossRushRecord))]))}),BlackMythWukongBossRushRecord:oe({bossGroupId:V($()),isPassed:V(v([le(!1),le(!0)])),bestRecords:V(v([te(),J(q(()=>Y.BlackMythWukongBattleRecord))])),encounterBossIndex:V($()),battleCount:V($())}),BlackMythWukongBattleRecord:oe({battleId:V(P()),battleData:V(q(()=>Y.BlackMythWukongBattleData))}),BlackMythWukongBattleData:oe({totalTime:V($()),score:V($()),debuffList:V(v([te(),J($())])),targetId:V($()),archiveTime:V(P()),roleBase:V(q(()=>Y.BlackMythWukongRoleBase)),battleStyleInfo:V(q(()=>Y.BlackMythWukongBattleStyleInfo)),damageInfo:V(q(()=>Y.BlackMythWukongDamageInfo))}),BlackMythWukongRoleBase:oe({level:V($()),atk:V($()),hpMax:V($()),staminaMax:V($()),mpMax:V($())}),BlackMythWukongBattleStyleInfo:oe({spellList:V(v([te(),J(q(()=>Y.BlackMythWukongCast))])),fabaoInfo:V(q(()=>Y.BlackMythWukongCast)),soulInfo:V(q(()=>Y.BlackMythWukongCast)),itemCount:V($()),wineCount:V($()),rollCount:V($()),defuseCount:V($()),fourPeCount:V($())}),BlackMythWukongCast:oe({castId:V($()),castCount:V($())}),BlackMythWukongDamageInfo:oe({totalDamage:V(v([P(),$()])),hightestDamage:V(v([P(),$()])),criticalDmgRate:V($()),totalBeDamaged:V(v([P(),$()])),criticalDmgTotal:V(v([P(),$()])),elemDotDmgTotal:V(v([P(),$()])),elemDotDmgRate:V($())}),BlackMythWukongBossRefightData:oe({bossList:V(v([te(),J(q(()=>Y.BlackMythWukongBossRefightRecord))]))}),BlackMythWukongBossRefightRecord:oe({bossId:V($()),passedMaxLevel:V($()),lastChallengeLevel:V($()),bestRecords:V(v([te(),J(q(()=>Y.BlackMythWukongBattleRecord))])),refightStatisticsList:V(v([te(),J(q(()=>Y.BlackMythWukongRefightStatistic))]))}),BlackMythWukongRefightStatistic:oe({challengeLevel:V($()),battleCount:V($())}),TaskBarHeroSave:oe({update_time:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),game_version:P(),account_version:P(),play_time:$(),last_saved_time:P(),common:q(()=>Y.TaskBarHeroCommon),summary:q(()=>Y.TaskBarHeroSummary),heroes:v([te(),J(q(()=>Y.TaskBarHeroHero))]),rune_save_data:v([te(),J(q(()=>Y.TaskBarHeroRune))]),pets:v([te(),J(q(()=>Y.TaskBarHeroPet))]),attributes:v([te(),J(q(()=>Y.TaskBarHeroAttribute))]),inventory_slots:v([te(),J(q(()=>Y.TaskBarHeroItemSlot))]),stash_slots:v([te(),J(q(()=>Y.TaskBarHeroItemSlot))]),item_instances:v([te(),J(q(()=>Y.TaskBarHeroItemInstance))]),values:q(()=>Y.TaskBarHeroValueSummary)}),TaskBarHeroCommon:oe({max_completed_stage:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_key:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_wave:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),arranged_hero_keys:v([te(),J(v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),arranged_pet_key:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroSummary:oe({max_hero_level:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),learned_rune_count:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unlocked_hero:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total_hero:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_count:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inventory_slots:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stash_slots:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroHero:oe({hero_key:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),hero_level:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:v([le(!1),le(!0)]),hero_exp:$(),ability_point:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),allocated_hero_ability_point:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),equipped_item_ids:v([te(),J(P())]),equipped_skill_keys:v([te(),J(v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),unlocked_attribute_group_keys:v([te(),J(v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))])}),TaskBarHeroRune:oe({rune_key:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroPet:oe({pet_key:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:v([le(!1),le(!0)])}),TaskBarHeroAttribute:oe({key:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroItemSlot:oe({index:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_unique_id:P(),is_unlock:v([le(!1),le(!0)]),is_unlocked_by_rune:v([le(!1),le(!0)])}),TaskBarHeroItemInstance:oe({item_key:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unique_id:P(),is_chaotic:v([le(!1),le(!0)]),is_blocked:v([le(!1),le(!0)]),is_server_pending_item:v([le(!1),le(!0)]),enchant_count:v([te(),J(v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),enchant_data:v([te(),J(q(()=>Y.TaskBarHeroEnchantData))]),item_get_source_type:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),decoration_applied_total_count:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),engraving_applied_total_count:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inscription_applied_total_count:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroEnchantData:oe({stat_mod_key:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),tier:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),value:$(),recipe_type:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),mod_type:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),material_key:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stat_type:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroValueSummary:oe({market_value:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),price_state:P(),currency:P()}),PhantomBladeZeroSave:oe({defaultSlot:P(),slots:J(q(()=>Y.PhantomBladeZeroSaveSlot))}),PhantomBladeZeroSaveSlot:oe({slot:P(),head:q(()=>Y.PhantomBladeZeroSlotHead),firstClear:q(()=>Y.PhantomBladeZeroSlotFirstClear),progress:q(()=>Y.PhantomBladeZeroSlotProgress),combat:q(()=>Y.PhantomBladeZeroSlotCombat),achievements:q(()=>Y.PhantomBladeZeroSlotAchievementSummary),bosses:q(()=>Y.PhantomBladeZeroSlotBossSummary),collectibles:q(()=>Y.PhantomBladeZeroSlotCollectibles),quest_details:v([te(),q(()=>Y.PhantomBladeZeroQuestDetails)]),inventory_details:v([te(),J(q(()=>Y.PhantomBladeZeroInventoryItem))]),detail:q(()=>Y.PhantomBladeZeroSlotDetail)}),PhantomBladeZeroSlotHead:oe({saveTime:P(),currentLevel:P(),cycle:P(),difficulty:q(()=>Y.PhantomBladeZeroSlotDifficulty)}),PhantomBladeZeroSlotDifficulty:oe({raw:$(),name:P()}),PhantomBladeZeroSlotFirstClear:oe({clearDate:q(()=>Y.PhantomBladeZeroUnavailableValue),cycles:v([te(),J(q(()=>Y.PhantomBladeZeroClearanceRecord))])}),PhantomBladeZeroUnavailableValue:oe({value:te(),reason:P()}),PhantomBladeZeroClearanceRecord:oe({Cycle:V(v([te(),$()])),Ending:$(),Difficulty:$(),GameTime:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),Completion:$(),DiedTimes:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotProgress:oe({playTimeSeconds:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),playTime:P(),lastLaunch:q(()=>Y.PhantomBladeZeroUnavailableValue),narrativePercentage:$(),chapter:P(),remainingDays:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCombat:oe({loadout:V(q(()=>Y.PhantomBladeZeroSlotLoadout)),totalDeaths:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),cycleDeaths:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bossKillTotal:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),currentMainWeapon:V(v([te(),q(()=>Y.PhantomBladeZeroNamedItem)])),mainWeapon:q(()=>Y.PhantomBladeZeroCollectionCount),currentShaqi:V(v([te(),q(()=>Y.PhantomBladeZeroNamedItem)])),shaqi:q(()=>Y.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroSlotLoadout:oe({states:V(v([te(),J(q(()=>Y.PhantomBladeZeroLoadoutState))])),main_weapons:v([te(),J(P())]),shaqi_weapons:v([te(),J(P())]),accessory_ids:v([te(),J(P())]),top_medicine:P(),bottom_medicine:P(),current_weapon_index:$(),current_shaqi_weapon_index:$()}),PhantomBladeZeroLoadoutState:oe({category:P(),id:P(),level:V($()),soul_forged:V(v([le(!1),le(!0)])),reincarnation_count:V($())}),PhantomBladeZeroNamedItem:oe({id:P(),name:P()}),PhantomBladeZeroCollectionCount:oe({unknown:V(v([P(),$()])),done:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotAchievementSummary:oe({unlocked:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:P()}),PhantomBladeZeroSlotBossSummary:oe({groups:v([te(),J(q(()=>Y.PhantomBladeZeroBossGroup))])}),PhantomBladeZeroBossGroup:oe({map:P(),mapName:P(),count:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bosses:v([te(),J(q(()=>Y.PhantomBladeZeroBoss))])}),PhantomBladeZeroBoss:oe({id:P(),classPath:P(),map:P(),mapName:P(),encountered:v([le(!1),le(!0)]),killed:v([le(!1),le(!0)]),kill:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),records:v([te(),J(q(()=>Y.PhantomBladeZeroBossRecord))])}),PhantomBladeZeroBossRecord:oe({cycle:P(),diff:P(),diffName:P(),kill:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCollectibles:oe({overall:q(()=>Y.PhantomBladeZeroCollectionSummary),craneBellCount:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),byBigMap:v([te(),J(q(()=>Y.PhantomBladeZeroBigMapProgress))]),currentChapter:q(()=>Y.PhantomBladeZeroChapterProgress)}),PhantomBladeZeroCollectionSummary:oe({bell:q(()=>Y.PhantomBladeZeroCollectionCount),weapon:q(()=>Y.PhantomBladeZeroCollectionCount),shaqi:q(()=>Y.PhantomBladeZeroCollectionCount),accessory:q(()=>Y.PhantomBladeZeroCollectionCount),medicine:q(()=>Y.PhantomBladeZeroCollectionCount),challenge:q(()=>Y.PhantomBladeZeroCollectionCount),hupo:q(()=>Y.PhantomBladeZeroCollectionCount),heishi:q(()=>Y.PhantomBladeZeroCollectionCount),flower:q(()=>Y.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroBigMapProgress:oe({unknown:V(v([P(),$()])),mapID:P(),name:P(),pct:$(),done:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),subMaps:v([te(),J(P())])}),PhantomBladeZeroChapterProgress:oe({unknown:V(v([P(),$()])),mapID:P(),pct:$(),done:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:P()}),PhantomBladeZeroQuestDetails:oe({CurrentMainQuestPath:P(),CurrentTutorialQuestPath:P(),TrackedQuestPath:P(),TrackedBranchID:P(),TrackedTaskPointID:P(),ManualTrackingOptOut:v([le(!1),le(!0)]),NarrativeSavedQuests:v([te(),J(q(()=>Y.PhantomBladeZeroQuest))])}),PhantomBladeZeroQuest:oe({QuestClass:P(),QuestCompletion:P(),QuestBranches:v([te(),J(q(()=>Y.PhantomBladeZeroQuestBranch))]),CompletedBranches:v([te(),J(P())]),ReachedStateNames:v([te(),J(P())])}),PhantomBladeZeroQuestBranch:oe({BranchID:P(),TasksProgress:v([te(),J(v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),BranchType:P()}),PhantomBladeZeroInventoryItem:oe({id:P(),amount:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotDetail:oe({bell:v([te(),J(q(()=>Y.PhantomBladeZeroBellDetail))]),weapon:v([te(),J(q(()=>Y.PhantomBladeZeroItemDetail))]),shaqi:v([te(),J(q(()=>Y.PhantomBladeZeroItemDetail))]),accessory:v([te(),J(q(()=>Y.PhantomBladeZeroItemDetail))]),medicine:v([te(),J(q(()=>Y.PhantomBladeZeroItemDetail))]),challenge:v([te(),J(q(()=>Y.PhantomBladeZeroChallengeDetail))]),hupo:v([te(),J(q(()=>Y.PhantomBladeZeroWorldItemDetail))]),heishi:v([te(),J(q(()=>Y.PhantomBladeZeroWorldItemDetail))]),flower:v([te(),J(q(()=>Y.PhantomBladeZeroItemDetail))]),achievements:v([te(),J(q(()=>Y.PhantomBladeZeroAchievementDetail))])}),PhantomBladeZeroBellDetail:oe({unknown:V(v([le(!1),le(!0)])),id:P(),done:v([le(!1),le(!0)]),equip:v([le(!1),le(!0)])}),PhantomBladeZeroItemDetail:oe({level:V($()),soul_forged:V(v([le(!1),le(!0)])),reincarnation_count:V($()),unknown:V(v([le(!1),le(!0)])),id:P(),name:P(),done:v([le(!1),le(!0)]),equip:v([le(!1),le(!0)]),locs:v([te(),J(q(()=>Y.PhantomBladeZeroLocation))])}),PhantomBladeZeroLocation:oe({map:P(),mapName:P(),x:$(),y:$(),z:$()}),PhantomBladeZeroChallengeDetail:oe({key:V(P()),unknown:V(v([le(!1),le(!0)])),index:v([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),guids:v([te(),J(P())]),done:v([le(!1),le(!0)]),locs:v([te(),J(q(()=>Y.PhantomBladeZeroLocation))])}),PhantomBladeZeroWorldItemDetail:oe({key:V(P()),unknown:V(v([le(!1),le(!0)])),id:P(),saveGuid:P(),mobDomain:P(),done:v([le(!1),le(!0)]),locs:v([te(),J(q(()=>Y.PhantomBladeZeroLocation))])}),PhantomBladeZeroAchievementDetail:oe({id:P(),name:P(),desc:P(),grade:P(),hidden:v([le(!1),le(!0)]),done:v([le(!1),le(!0)])}),UserGameDataSaveFilePage:oe({items:J(q(()=>Y.UserGameDataSaveInfo)),hasMore:le(!1)}),UserGameDataSaveInfo:oe({saveId:P(),createdAt:P(),files:J(q(()=>Y.UserGameDataSaveFileInfo))}),UserGameDataSaveFileInfo:oe({fileId:P(),name:P(),sizeBytes:$(),modifiedAt:P()})},Gg=new Map([["ark.profile",q(()=>Y.ArkProfile)],["ark.gacha-analysis",q(()=>Y.ArkGachaAnalysis)],["ark.gacha-record-page",oe({items:J(q(()=>Y.GachaRecord)),nextCursor:V(P()),hasMore:v([le(!1),le(!0)]),total:V($())})],["black_myth_wukong.save",q(()=>Y.BlackMythWukongSave)],["task_bar_hero.save",q(()=>Y.TaskBarHeroSave)],["phantom_blade_zero.save",q(()=>Y.PhantomBladeZeroSave)],["save-file-page",q(()=>Y.UserGameDataSaveFilePage)]]);function Qg(e,t){return Gg.get(e)?.safeParse(t).success??!1}function qg(e){const t=ya.contracts[e];if(!t)throw new Error("未知资料 schema");function r(n){if(Object.prototype.hasOwnProperty.call(n,"const"))return n.const;if(n.$ref)return r(ya.$defs[n.$ref.slice(8)]);if(n.anyOf)return r(n.anyOf[0]);switch(n.type){case"string":return n.pattern?"0":"";case"number":case"integer":return 0;case"boolean":return!1;case"null":return null;case"array":return n.prefixItems?n.prefixItems.map(r):[];case"object":return Object.fromEntries((n.required??[]).map(i=>[i,r(n.properties[i])]));default:throw new Error("未知资料类型")}}return r(t)}const Yg=32*1024*1024,Wg=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Zg(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:Yg},i);return Kg(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Kg(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:Jg(t,ep(e,"content-type"))}}function Jg(e,t){Xg(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new ke("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!Wg.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function Xg(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new ke(`Host network response 不支持 charset=${t}`)}function ep(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function W(e){return typeof e=="function"}function Ea(e){return(...t)=>{throw ot(e)}}function Re(e){return async(...t)=>{throw ot(e)}}const tp=(e,t)=>{},rp=()=>()=>{};function np(e){const t={request:W(e.network?.request)?e.network.request.bind(e.network):Re("network.request")},r={...W(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:W(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):Re("account.getCurrentUserId"),ensureAuthenticated:W(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Re("account.ensureAuthenticated"),onChange:W(e.account?.onChange)?e.account.onChange.bind(e.account):rp},n={...e.storage?.withLock?{withLock:e.storage.withLock.bind(e.storage)}:{},getRaw:W(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Re("storage.getRaw"),setRaw:W(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Re("storage.setRaw")},i={...W(e.presentation?.showSteamLoginRequired)?{showSteamLoginRequired:e.presentation.showSteamLoginRequired.bind(e.presentation)}:{},...W(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...W(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:W(e.presentation?.close)?e.presentation.close.bind(e.presentation):Re("presentation.close"),reload:W(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Re("presentation.reload"),openAppPage:W(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Re("presentation.openAppPage"),openWindow:W(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Re("presentation.openWindow"),getViewportMetrics:W(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Ea("presentation.getViewportMetrics"),getNavigationBarHeight:W(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Ea("presentation.getNavigationBarHeight"),setNavigationBarStyle:W(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Re("presentation.setNavigationBarStyle"),showShareMenu:W(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Re("presentation.showShareMenu"),setScreenshotChromeHidden:W(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):tp,supportsLongScreenshot:e.presentation?.supportsLongScreenshot===!0,captureAndShare:W(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Re("presentation.captureAndShare"),showAppreciation:W(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw Ie("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:W(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Re("presentation.showToast"),showLoading:W(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Re("presentation.showLoading"),hideLoading:W(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Re("presentation.hideLoading"),vibrate:W(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Re("presentation.vibrate"),setClipboard:W(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Re("presentation.setClipboard")},o=W(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,W(e.companion?.[c])?e.companion[c].bind(e.companion):Re(`companion.${c}`)]));W(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const a={invoke:W(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):Re("protocol.invoke")};return{network:t,...e.workspaceCards?{workspaceCards:e.workspaceCards}:{},account:r,storage:n,presentation:i,companion:s,protocol:a,...e.files===void 0?{}:{files:e.files},...e.picker===void 0?{}:{picker:e.picker},...e.media===void 0?{}:{media:e.media},...e.transfer===void 0?{}:{transfer:e.transfer},...e.scopedStorage?{scopedStorage:e.scopedStorage}:{},...o?{storageDiagnostics:o}:{}}}function ip(e,t={}){const r=op(e.files?.sandbox),n=W(e.picker?.pickFiles)&&W(e.picker?.pickDirectory),i=W(e.picker?.saveFile),o=r||n||i||W(e.companion?.openAttachment),s=r?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":W(e.account?.getAccountKey),"account.getCurrentUserId":W(e.account?.getCurrentUserId),"account.ensureAuthenticated":W(e.account?.ensureAuthenticated),"account.onChange":W(e.account?.onChange),"network.request":W(e.network?.request),"network.stream":W(e.transfer?.network.open)&&W(e.transfer?.network.release),"network.upload":W(e.transfer?.upload?.upload),"files.sandbox":r,"files.external":n,"files.save":i,"files.access":o,"files.removeFile":W(s?.remove),"files.removeDirectory":W(e.files?.sandbox.remove),"files.transfer":W(e.transfer?.files.writeResource),"media.pick":W(e.media?.pick),"storage.getRaw":W(e.scopedStorage?.get)||W(e.storage?.getRaw),"storage.setRaw":W(e.scopedStorage?.set)||W(e.storage?.setRaw),"presentation.close":W(e.presentation?.close),"presentation.reload":W(e.presentation?.reload),"presentation.openAppPage":W(e.presentation?.openAppPage),"presentation.applyOrientation":W(e.presentation?.applyOrientation),"presentation.openWindow":W(e.presentation?.openWindow),"presentation.getViewportMetrics":W(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":W(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":W(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":W(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":W(e.presentation?.captureAndShare),"presentation.showAppreciation":W(e.presentation?.showAppreciation),"presentation.showToast":W(e.presentation?.showToast),"presentation.showLoading":W(e.presentation?.showLoading),"presentation.hideLoading":W(e.presentation?.hideLoading),"presentation.vibrate":W(e.presentation?.vibrate),"presentation.setClipboard":W(e.presentation?.setClipboard),"workspaceCards.requestRefresh":W(e.workspaceCards?.requestRefresh),"companion.getInfo":W(e.companion?.getInfo),"companion.getPreparationStatus":W(e.companion?.getPreparationStatus),"companion.prepare":W(e.companion?.prepare),"companion.cancelPreparation":W(e.companion?.cancelPreparation),"companion.getActiveSession":W(e.companion?.getActiveSession),"companion.launch":W(e.companion?.launch),"companion.session.write":W(e.companion?.write),"companion.session.closeStdin":W(e.companion?.closeStdin),"companion.session.terminate":W(e.companion?.terminate),"companion.session.ackOutput":W(e.companion?.ackOutput),"companion.openAttachment":W(e.companion?.openAttachment),"companion.showNotification":W(e.companion?.showNotification),"protocol.invoke":W(e.protocol?.invoke),"presentation.confirmDataPermission":t.hasUserDataPresentation===!0,"presentation.openDataPermissions":t.hasUserDataSettings===!0}}function op(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&W(t.file)&&W(t.directory)&&W(t.create)&&W(t.stat)&&W(t.list)}function wa(e,t){return t?.[e]!==!1}function sp(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function Bu(e,t={}){const r={};for(const n of Object.keys(Ws)){const o=Ws[n].every(a=>e[a]),s=!sp(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=wa(n,t.callerCapabilities)&&wa(n,t.hostCapabilities)&&o&&s}return r}function Hu(e={},t={}){const r=ip(e,t),n=Bu(r,t);return{ports:np(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function be(e,t,r){if(!t||t===e.signal)return r===void 0?e:{...e,requestId:r};const n=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):ap(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function ap(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 cp(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 dp=4,up=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],lp=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),fp=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],mp=["/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 hp(e,t){const r=yp(e);return r===null||Ia(r,fp)?!0:t&&Ia(r,mp)}function gp(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return up.some(r=>t===r||t.endsWith(`.${r}`))}function pp(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||lp.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function yp(e){let t=e;for(let r=0;r<dp;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return _a(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return _a(t)}function Ia(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function _a(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Ep(e){if(typeof e!="string"||e!==e.trim()||e.length>253)return;const t=e.toLowerCase();if(!(!t.includes(".")||/^\d+(?:\.\d+)*$/.test(t))&&t.split(".").every(r=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(r))&&!(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")))return t}function Fu(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw Ci("网络策略格式无效");const t=e,r=t.entries===void 0?[]:t.entries;if(!Number.isSafeInteger(t.revision)||t.revision<1||t.enforcement!=="approved_domains"&&t.enforcement!=="restricted"||!Array.isArray(r)||r.length>20)throw Ci("网络策略格式无效");const n=new Set;for(const i of r){const o=Ep(i&&typeof i=="object"?i.domain:void 0);if(!o)throw Ci("网络策略包含无效域名");n.add(o)}return Object.freeze({revision:t.revision,enforcement:t.enforcement,entries:Object.freeze([...n].sort().map(i=>Object.freeze({domain:i})))})}function Ci(e){return Object.assign(new TypeError(e),{code:"NETWORK_POLICY_INVALID"})}function Ln(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function pe(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:Ln()}const Aa=new WeakMap,In=new Map;function $u(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return gh(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${pu(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Vu(e){const t=e.coordinationKey??e.storage;let r;const n=()=>r??=Promise.resolve().then(e.resolveScope).catch(c=>{throw r=void 0,c}),i=async(c,d)=>{const u=await n();let l=Aa.get(t);l||(l=new Map,Aa.set(t,l));const f=l.get(u)??Promise.resolve(),h=async()=>(pe(c.signal,{preserveReason:!0}),d(u)),m=f.catch(()=>{}).then(()=>e.lock?e.lock(u,h):h());l.set(u,m);try{return await m}finally{l.get(u)===m&&l.delete(u)}},o=async(c,d,u=!1)=>{const l=tr(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(m=>m.key.startsWith(l)&&m.value!=="").map(m=>m.key.slice(l.length)))];const f=await e.storage.getRaw(yn(c),d);if((f===void 0||f==="")&&!u)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let h;try{h=f?JSON.parse(f):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(h)||h.length>sa||h.some(m=>typeof m!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(m)))throw new Error("本地数据索引异常");return[...new Set(h)]},s=async(c,d)=>{if(e.diagnostics){const f=tr(c,"");return(await e.diagnostics.listRaw(d)).filter(h=>h.key.startsWith(f)&&h.value!=="").map(h=>({...h,key:h.key.slice(f.length)}))}const u=[],l=await o(c,d);for(let f=0;f<l.length;f+=16){pe(d.signal,{preserveReason:!0});const h=await Promise.all(l.slice(f,f+16).map(async m=>{const E=await e.storage.getRaw(tr(c,m),d);return E!==void 0&&E!==""?{area:"local",key:m,value:E}:void 0}));for(const m of h)m&&u.push(m)}return u},a=c=>{if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw Object.assign(new Error("storage key 不合法"),{code:"INVALID_REQUEST"})};return{get(c,d){return a(c),i(d,u=>e.storage.getRaw(tr(u,c),d))},set(c,d,u){return a(c),i(u,async l=>{const f=await o(l,u,!0);if(!f.includes(c)&&f.length>=sa)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const h=[...new Set([...f,c])];await e.storage.setRaw(yn(l),JSON.stringify(h),u)}pe(u.signal,{preserveReason:!0}),await e.storage.setRaw(tr(l,c),d,u),pe(u.signal,{preserveReason:!0})})},list(c){return i(c,d=>s(d,c))},clear(c){return i(c,async d=>{const u=await o(d,c);e.diagnostics||await e.storage.setRaw(yn(d),JSON.stringify(u),c);for(let l=0;l<u.length;l+=16){pe(c.signal,{preserveReason:!0});const h=(await Promise.allSettled(u.slice(l,l+16).map(m=>e.storage.setRaw(tr(d,m),"",c)))).find(m=>m.status==="rejected");if(h)throw h.reason}pe(c.signal,{preserveReason:!0}),await e.storage.setRaw(yn(d),"[]",c)})}}}function Gu(e,t){if(typeof navigator<"u"&&navigator.locks)return new Promise((n,i)=>{navigator.locks.request(`hb-miniprogram-storage:${e}`,()=>t().then(n,i)).catch(i)});const r=(In.get(e)??Promise.resolve()).catch(()=>{}).then(t);return In.set(e,r),r.finally(()=>{In.get(e)===r&&In.delete(e)})}const Da=15e3,wp=32*1024*1024,Na="data-hb-preview-capture-device",ki="data-hb-preview-capture-ancestor",Ma="data-hb-preview-capture-surface",ba=64,Ip=1024;function _p(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??Da;if(!Number.isFinite(n)||n<=0||n>Da)throw He("INVALID_CAPTURE_LEASE","截图租约无效");let i;function o(d,u,l){d.attributes.push({element:u,name:l,previous:u.getAttribute(l)}),u.setAttribute(l,d.token)}function s(d){const u=i;if(!u||u.token!==d)return!1;const l=a(u),f=!!u.style?.isConnected;i=void 0,clearTimeout(u.timer),u.removeAbort?.(),u.removeResize?.(),u.observer?.disconnect(),u.style?.remove(),u.bounds?.remove();for(const{element:h,name:m,previous:E}of u.attributes)h.getAttribute(m)===d&&(E===null?h.removeAttribute(m):h.setAttribute(m,E));return u.overlay.remove(),f&&(r.scrollX!==u.scroll.x||r.scrollY!==u.scroll.y)&&r.scrollTo(u.scroll.x,u.scroll.y),l}function a(d){const{viewport:u,target:l,rect:f}=d;if(!l?.isConnected||!f||Date.now()>=d.expiresAt||r.innerWidth!==u.width||r.innerHeight!==u.height||r.devicePixelRatio!==u.devicePixelRatio)return!1;const h=l.getBoundingClientRect();return["left","top","width","height"].every(m=>Math.abs(h[m]-f[m])<.01)}async function c(d,u){if(u?.throwIfAborted(),!Number.isFinite(d.deadlineAt)||Date.now()>=d.deadlineAt)throw He("PREVIEW_TIMEOUT","截图操作已超时");if(d.scope==="workbench"||!Object.hasOwn(gn,d.scope))throw He("INVALID_CAPTURE_SCOPE","设备像素截图仅支持 device、screen 或 app");if(!d.operationId||d.operationId.length>128)throw He("INVALID_OPERATION","截图操作标识无效");if(!d.previewImage.startsWith("data:image/png;base64,")||d.previewImage.length>wp)throw He("INVALID_CAPTURE_IMAGE","共享窗口冻结图无效或过大");if(i)throw He("PREVIEW_BUSY","已有设备截图正在执行");const l=t.querySelectorAll(gn.device);if(l.length!==1)throw He("DEVICE_NOT_UNIQUE","设备画面不唯一或尚未创建");const f=l[0],h=d.scope==="device"?f:t.querySelector(gn[d.scope]);if(!h||h!==f&&!f.contains(h))throw He("CAPTURE_TARGET_UNAVAILABLE","截图内容尚未创建");const m=f.getBoundingClientRect();if(!(m.width>0&&m.height>0))throw He("CAPTURE_TARGET_UNAVAILABLE","设备画面当前不可见");const E=t.createElement("img");E.alt="",E.setAttribute("aria-hidden","true"),E.setAttribute("data-hb-preview-capture-freeze",""),E.style.cssText=`position:fixed;left:0;top:0;width:${r.innerWidth}px;height:${r.innerHeight}px;max-width:none;max-height:none;margin:0;border:0;padding:0;z-index:2147483647;pointer-events:auto;user-select:none;`,E.addEventListener("wheel",j=>j.preventDefault(),{passive:!1}),E.addEventListener("touchmove",j=>j.preventDefault(),{passive:!1});const N=Math.min(Date.now()+n,d.deadlineAt),A={operationId:d.operationId,token:r.crypto.randomUUID(),overlay:E,attributes:[],scroll:{x:r.scrollX,y:r.scrollY},viewport:{width:r.innerWidth,height:r.innerHeight,devicePixelRatio:r.devicePixelRatio},expiresAt:N};i=A,A.timer=setTimeout(()=>s(A.token),Math.max(0,N-Date.now()));const R=()=>s(A.token);u?.addEventListener("abort",R,{once:!0}),A.removeAbort=()=>u?.removeEventListener("abort",R);const y=()=>{const{viewport:j}=A;(r.innerWidth!==j.width||r.innerHeight!==j.height||r.devicePixelRatio!==j.devicePixelRatio)&&s(A.token)};r.addEventListener("resize",y),A.removeResize=()=>r.removeEventListener("resize",y);const T=()=>{if(u?.throwIfAborted(),i!==A||Date.now()>=N)throw He("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{E.src=d.previewImage,await E.decode(),T();const j=A.token,I=`[${Na}="${j}"]`,_=r.getComputedStyle(f),w=new r.DOMMatrixReadOnly(_.transform==="none"?void 0:_.transform),S=Math.atan2(w.b,w.a),b=f.querySelector(".desktop-window__surface"),U=b?b.offsetWidth:Number.parseFloat(_.width),D=b?b.offsetHeight:Number.parseFloat(_.height),M=_.backgroundColor,O=r.getComputedStyle(t.body).backgroundColor,z=ye=>!ye||ye==="transparent"||ye==="rgba(0, 0, 0, 0)",x=z(M)?z(O)?"#fff":O:M;if(!(U>0&&D>0))throw He("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");T(),t.body.append(E),o(A,f,Na),b&&o(A,b,Ma);for(let ye=f.parentElement;ye;ye=ye.parentElement)o(A,ye,ki);const L=t.createElement("style");A.style=L;const k=`
2
- [${ki}="${j}"] {overflow:visible!important;scrollbar-width:none!important;}
3
- [${ki}="${j}"]::-webkit-scrollbar {display:none!important;}
4
- [${Ma}="${j}"] {transform:none!important;transition:none!important;}
5
- `,H=(ye,Oe,Me=0,Pe=0)=>`${I} {position:absolute!important;left:${ye}px!important;top:${Oe}px!important;width:${U}px!important;height:${D}px!important;transform:translate(${Me}px,${Pe}px) rotate(${S}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${x}!important;}`;L.textContent=k+H(0,0),T(),t.head.append(L);const F=f.getBoundingClientRect(),G=t.querySelector(gn.app),Z=G&&f.contains(G)?G.getBoundingClientRect():void 0,g=Z&&Z.width>0&&Z.height>0?Z:void 0,C=g?Math.floor(r.innerWidth-1-(g.left-F.left)):r.innerWidth+64,B=g?Math.floor(r.innerHeight-1-(g.top-F.top)):32,Q=C-F.left,X=B-F.top;T(),L.textContent=k+H(Q,X);const ne=f.getBoundingClientRect();L.textContent=k+H(Q,X,C-ne.left,B-ne.top),T();const ie=h.getBoundingClientRect(),ue=Math.floor(rr(ie.left+r.scrollX)),Ee=Math.floor(rr(ie.top+r.scrollY)),he={x:ue,y:Ee,width:Math.ceil(rr(ie.right+r.scrollX))-ue,height:Math.ceil(rr(ie.bottom+r.scrollY))-Ee};if(!(he.width>0&&he.height>0)||he.x<0||he.y<0)throw He("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(g&&G){const ye=G.getBoundingClientRect();if(!(ye.left<r.innerWidth&&ye.top<r.innerHeight&&ye.right>0&&ye.bottom>0))throw He("CAPTURE_LAYOUT_INVALID","无法保持 iframe 的最小绘制区域");const Oe=f.getBoundingClientRect(),Me=Math.floor(rr(Oe.left))-1,Pe=Math.floor(rr(Oe.top))-1,je=r.innerWidth-Me,Ut=r.innerHeight-Pe;if(Me<0||Pe<0||je<=0||Ut<=0||je>ba||Ut>ba||je*Ut>Ip)throw He("CAPTURE_LAYOUT_INVALID","无法在有界角部保持完整设备绘制,请改用 --scale css");E.style.clipPath=`polygon(0 0,100% 0,100% ${Pe}px,${Me}px ${Pe}px,${Me}px 100%,0 100%)`,E.setAttribute("data-hb-preview-capture-corner",JSON.stringify({x:Me,y:Pe,width:je,height:Ut}))}const ge=t.createElement("div");if(ge.setAttribute("aria-hidden","true"),ge.style.cssText=`position:absolute;left:${he.x+he.width+2}px;top:${he.y+he.height+2}px;width:1px;height:1px;pointer-events:none;opacity:0;`,A.bounds=ge,T(),t.body.append(ge),A.target=h,A.rect=ie,await Ap(r,u),T(),!a(A))throw He("CAPTURE_LAYOUT_INVALID","截图准备期间布局发生变化,请重新截图");A.observer=new r.ResizeObserver(()=>{i===A&&!a(A)&&s(A.token)});for(const{element:ye}of A.attributes)A.observer.observe(ye);return{token:j,clip:he,devicePixelRatio:r.devicePixelRatio,expiresAt:N}}catch(j){throw s(A.token),j}}return{prepare:c,restore:s,cancel:d=>i?.operationId!==d?!1:(s(i.token),!0),dispose:()=>{i&&s(i.token)}}}function Ap(e,t){return new Promise((r,n)=>{let i=e.requestAnimationFrame(()=>{i=e.requestAnimationFrame(s)});const o=()=>{e.cancelAnimationFrame(i),t?.removeEventListener("abort",o),n(t?.reason)};function s(){t?.removeEventListener("abort",o),r()}t?.addEventListener("abort",o,{once:!0}),t?.aborted&&o()})}function He(e,t){return Object.assign(new Error(t),{name:"PreviewError",code:e})}function rr(e){const t=Math.round(e);return Math.abs(e-t)<.001?t:e}Rt.map(e=>e.method);function Sa(e){return e instanceof ke?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function fe(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Ln());let n;try{n=e()}catch(i){return Promise.reject(Sa(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Ln())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(Ln()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(Sa(d))))})}async function Dp(e,t,r){pe(r);const i=e.ownerDocument.defaultView;if(!i||!e.isConnected)throw new Error("长图容器不可用");const o=e.getAttribute("style"),s=i.scrollX,a=i.scrollY,c=e.getBoundingClientRect().width,d=()=>{o===null?e.removeAttribute("style"):e.setAttribute("style",o),i.scrollTo(s,a)};try{e.style.setProperty("width",`${c}px`,"important"),e.style.setProperty("height",`${t.top+t.height}px`,"important"),e.style.setProperty("min-height","0","important"),e.style.setProperty("max-height","none","important"),i.scrollTo(0,0),await fe(()=>new Promise(l=>i.requestAnimationFrame(()=>i.requestAnimationFrame(()=>l()))),r);const u=e.getBoundingClientRect();if(u.height+1<t.top+t.height||u.width+1<t.left+t.width||u.left<0||u.top<0)throw new Error("宿主布局无法容纳长图");for(let l=e.parentElement;l;l=l.parentElement){const f=i.getComputedStyle(l),h=l.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(f.overflowY)&&(u.top+t.top<h.top-1||u.top+t.top+t.height>h.bottom+1))throw new Error("宿主布局无法容纳长图:祖先容器存在纵向裁剪")}return{rect:{...t,left:t.left+u.left,top:t.top+u.top},restore:d}}catch(u){throw d(),u}}function Np(e,t,r,n=1e4){const i=new AbortController;return new Promise((o,s)=>{let a=!1;const c=l=>{a||(a=!0,clearTimeout(u),r.signal.removeEventListener("abort",d),i.abort(l),s(l))},d=()=>{i.abort(),c({code:"NETWORK_POLICY_CHANGED",message:"网络策略初始化已取消"})},u=setTimeout(()=>c({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 网络策略初始化超时"}),n);if(r.signal.addEventListener("abort",d,{once:!0}),r.signal.aborted){d();return}Promise.resolve().then(()=>e.activate(t,{signal:i.signal})).then(l=>{if(typeof l!="function"){c({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 未完成严格网络策略初始化"});return}if(a){try{l()}catch{}return}a=!0,clearTimeout(u),o(()=>{r.signal.removeEventListener("abort",d),i.abort(),l()})},c)})}function Qu(e,t){return Mp(t)??bp(e.pathname)}function Mp(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function bp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const Sp=1,qu="allow-scripts allow-same-origin",Tp="",Op="no-referrer";function vp(e=qu){return!e.split(/\s+/).includes("allow-same-origin")}function Ta(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Pp=new Set(["javascript:","data:","blob:","file:"]),Oa="xiaoheihe.cn";function Rp(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(Pp.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!kp(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Cp(e,t){const r=new URL(e);return r.searchParams.set(Eu,t),r.toString()}function Yu(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Qu(n,r);return i.pathname.startsWith(o)}catch{return!1}}function va(e){const t=new URL(e);return As(t)?"loopback":Ds(t)?"lan":"production"}function kp(e,t,r){return Lp(e)||As(e)||Ds(e)&&Up(t,r)}function Lp(e){return e.protocol==="https:"&&Bp(e.hostname)}function As(e){return e.protocol==="http:"&&xp(e.hostname)}function xp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Ds(e){return e.protocol==="http:"&&jp(e.hostname)}function Up(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return As(r)||Ds(r)}catch{return!1}}function jp(e){const t=zp(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function zp(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 Bp(e){return e===Oa||e.endsWith(`.${Oa}`)}function Hp(e){let t,r=!1,n=!1;const i=new URL(e.launchUrl).origin,o=s=>{const a=s.data;if(n||!e.iframe.contentWindow||s.source!==e.iframe.contentWindow||s.origin!==i||a?.type!=="hb-sdk:dev-document"||a.nonce!==e.nonce||typeof a.documentId!="string"||!/^[a-f0-9]{32}$/.test(a.documentId)||typeof a.href!="string"||a.href.length>8192||!Yu(e.launchUrl,a.href,e.locationBasePath))return;const c=new URL(a.href);if(!(c.username||c.password||c.searchParams.get(Eu)!==e.nonce)){if(a.phase==="leaving"){a.documentId===t&&!r&&(r=!0,e.onLeaving());return}if(a.phase==="boot"){if(t!==void 0&&t!==a.documentId&&a.navigationType==="reload"){n=!0,e.onReload(c.href);return}r&&t===a.documentId&&e.onResume(),t=a.documentId,r=!1}}};return window.addEventListener("message",o),()=>{window.removeEventListener("message",o)}}function Wu(e){const t=Ve(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 Fp(e){const t=Ve(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 $p(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Vp=1e3;function Gp(e,t=$p()){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<=Vp}const Qp="runtime.gate.probe",Zu=new Set(Rt.map(e=>e.method));class qp{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=yu;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.getWorkspaceCardLaunchContext=t.getWorkspaceCardLaunchContext,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,this.onDevUploadSession=t.onDevUploadSession,this.handleMessage=this.onMessage.bind(this),this.handleUserInteraction=this.onUserInteraction.bind(this),this.dispatcher=t.dispatcher,this.environmentInfo=t.environmentInfo,this.targetOrigin=t.targetOrigin||"*"}get protocolVersion(){return this.handshaken?this.bridgeVersion:void 0}start(){if(!(this.started||this.destroyed)){this.started=!0,window.addEventListener("message",this.handleMessage);for(const t of["pointerdown","touchend","mousedown","keydown"])window.addEventListener(t,this.handleUserInteraction,!0)}}setTargetOrigin(t){this.targetOrigin=t||"*"}destroy(){if(this.destroyed)return;const t=this.started;this.destroyed=!0,this.started=!1,this.handshaken=!1;try{t&&this.postMessage({namespace:Bt,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:Bt,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Bt,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Bt,version:2,nonce:this.nonce,type:"event",id:t,method:Iu,payload:r})}onMessage(t){if(!this.started||this.destroyed)return;if(this.onDevUploadSession&&this.iframe.contentWindow&&t.source===this.iframe.contentWindow&&t.data?.type==="hb-sdk:dev-upload-session"){const n=t.data.deviceSessionId;if(typeof n=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(n))try{this.onDevUploadSession(n)}catch{}return}if(!this.isTrustedMiniProgramMessage(t))return;const r=t.data;if(r.type==="handshake"){this.handleHandshake(r,t.origin);return}if(r.type==="request"){let n=!1;try{n=Gp(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&&Nh(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:Bt,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:wu,payload:{environment:this.environmentInfo,...this.getWorkspaceCardLaunchContext?{workspaceCardLaunchContext:this.getWorkspaceCardLaunchContext()}:{}}}),this.postEvent("ready",{timestamp:Date.now()}),o?this.onReady?.(n):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===Qp){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,Ie("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Zu.has(t.method)){this.postResponse(t,void 0,Ie("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,Ie("INVALID_PARAMS","bridge request id 重复"));return}const n=new AbortController;this.operations.set(t.id,n);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{requestId:t.id,postEvent:this.postEvent.bind(this),postProgress:o=>{this.operations.get(t.id)===n&&this.postProgress(t.id,o)},signal:n.signal,trustedUserGesture:r});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==n)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==n)return;const o=ps(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:Bt,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!Yp(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 Yp(e){return typeof e=="string"&&Zu.has(e)}function p(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ns(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw p("FILE_IO_FAILED","当前环境缺少安全随机数能力");try{const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}catch{throw p("FILE_IO_FAILED","无法生成安全文件标识")}}function Ku(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):ko,remove:o?s=>e.remove(s):Xu,read:s=>e.read(s),...typeof e.readPrefix=="function"?{readPrefix:(s,a)=>e.readPrefix(s,a)}:{},write:i?(s,a)=>e.write(s,a):ko,stat:s=>e.stat(s)})}function Ju(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=>Ku(e.file(a),n,{allowRemove:o}),directory:a=>Ju(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):ko,remove:s?(a,c)=>e.remove(a,c):Xu,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function ko(){return Promise.reject(p("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Xu(){return Promise.reject(p("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Wp=new Set(["REQUEST_CANCELLED","REQUEST_TIMEOUT","RUNTIME_DESTROYED","USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","USER_DATA_PERMISSION_STATE_INVALID","USER_DATA_SOURCE_NOT_LINKED","USER_DATA_SOURCE_LOGIN_REQUIRED","USER_GAME_DATA_UNAVAILABLE","USER_GAME_DATA_INVALID_RESPONSE","METHOD_FORBIDDEN","FILE_PICKER_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_ENCODING_INVALID","DIRECTORY_LIST_LIMIT_EXCEEDED","DIRECTORY_NOT_EMPTY","FILE_IO_FAILED"]),Zp={REQUEST_CANCELLED:"文件操作已取消",REQUEST_TIMEOUT:"文件操作超时",RUNTIME_DESTROYED:"小程序已关闭",USER_DATA_PERMISSION_STORAGE_UNAVAILABLE:"无法读取本地用户数据许可",USER_DATA_PERMISSION_STATE_INVALID:"本地用户数据许可状态异常,已停止访问",USER_DATA_SOURCE_NOT_LINKED:"请先在小黑盒关联对应游戏账号",USER_DATA_SOURCE_LOGIN_REQUIRED:"请先在小黑盒更新游戏来源登录",USER_GAME_DATA_UNAVAILABLE:"游戏资料暂不可用,请稍后重试",USER_GAME_DATA_INVALID_RESPONSE:"游戏资料响应异常,请稍后重试",METHOD_FORBIDDEN:"当前 Host 未开放该文件能力",FILE_PICKER_CANCELLED:"已取消文件选择",FILE_ACCESS_REVOKED:"文件授权已失效",FILE_ACCESS_DENIED:"当前文件授权不允许此操作",FILE_NOT_FOUND:"文件不存在",DIRECTORY_NOT_FOUND:"目录不存在",FILE_ALREADY_EXISTS:"文件已存在",DIRECTORY_ALREADY_EXISTS:"目录已存在",FILE_TYPE_MISMATCH:"文件类型不匹配",FILE_TOO_LARGE:"文件超过大小限制",FILE_QUOTA_EXCEEDED:"文件配额已用尽",FILE_ENCODING_INVALID:"文件编码不合法",DIRECTORY_LIST_LIMIT_EXCEEDED:"目录项数量超过限制",DIRECTORY_NOT_EMPTY:"目录不为空",FILE_IO_FAILED:"文件操作失败"};function Ar(e){const t=Ms(e),r=t&&Wp.has(t)?p(t,Zp[t]??"文件操作失败"):p("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function It(e){try{return e()}catch(t){throw Ar(t)}}function Ms(e){try{if(!re(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Pa=1024;class bs{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new bs(void 0,this.miniProgramDetail)}dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareFile(t,r,n),[o]=this.registerMany([i]);return _n(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=It(()=>{if(!Array.isArray(t))throw p("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw p("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>Pa)throw p("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw p("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>_n(a.handle,{kind:"file",handleId:s[c]}))}revokeFiles(t){for(const r of t)this.handles.get(r)?.handle.kind==="file"&&this.handles.delete(r)}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[o]=this.registerMany([i]);return Ca(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Yt(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!Yt(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}isUserDataDownloadRef(t){return!Yt(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="download"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Jp(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=rn(r.relativePath);Li(n.origin,i);const o=this.prepareFile(It(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Xp(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==="."?".":rn(r.relativePath);Li(n.origin,i);const o=this.prepareDirectory(i==="."?n.hostHandle:It(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return La(t),_n(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),It(()=>{if(!Array.isArray(r))throw p("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw p("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw p("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&re(a)&&typeof a.name=="string"&&el(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return It(()=>{if(re(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return _n(n.handle,Ra(t.ref,n.handle.name))}if(re(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return Ca(n.handle,Kp(t.ref,n.handle.name))}throw p("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=dn(r);Li(t.origin,n);const i=this.prepareFile(It(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:Ra(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw p("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return It(()=>{La(t);const i=n??t.mode;return ka(t.mode,i),{handle:Ku(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return It(()=>{ry(t,i);const o=n??t.mode;return ka(t.mode,o),{handle:Ju(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Pa)throw p("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Ns();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw p("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!ey(t))throw p("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw p("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw p("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw ot("files.sandbox");return this.prepareDirectory(It(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw p("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw ot("files")}}function rn(e){if(!ws(e))throw p("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Li(e,t){if(e==="sandbox"&&el(t))throw p("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function el(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function dn(e,t="文件名"){const r=rn(e);if(r.includes("/"))throw p("INVALID_PARAMS",`${t} 只能是 basename`);return r}function Ra(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:rn(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Kp(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:rn(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function _n(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function Ca(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function ka(e,t){if(t==="readwrite"&&e!=="readwrite")throw p("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Jp(e){return Yt(e)||tl(),e}function Xp(e){return Au(e)||tl(),e}function tl(){throw p("INVALID_PARAMS","文件引用不合法")}function ey(e){return/^[0-9a-f]{32}$/.test(e)}function ty(e){return re(e)&&e.kind==="file"&&typeof e.name=="string"&&(e.mode==="read"||e.mode==="readwrite")&&typeof e.create=="function"&&typeof e.read=="function"&&typeof e.write=="function"&&typeof e.stat=="function"}function La(e){if(!ty(e))throw p("FILE_IO_FAILED","Host 返回了无效 File handle");dn(e.name,"Host File name")}function ry(e,t=!1){if(!re(e)||e.kind!=="directory"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.file!="function"||typeof e.directory!="function"||typeof e.create!="function"||typeof e.stat!="function"||typeof e.list!="function")throw p("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw p("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&dn(e.name,"Host Directory name")}const ny=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),iy=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),oy=new Set(["range","if-range","a-im"]),sy=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"]),ay=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,An={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class cy{constructor(t){this.signal=t}phase="initial";transition(t){if(An[t]<=An[this.phase])throw p("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(An[this.phase]<An.committed&&this.signal.aborted)throw il()}normalizeHostError(t,r){return this.throwIfCancelled(),Ts(t,r,this.signal)}}async function rl(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw ot("network.download");const o=be(r.operationContext,t.signal),s=new cy(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await fy(e,i,o)}catch(u){throw s.normalizeHostError(u,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(u){throw s.normalizeHostError(u,"network")}let d=!1;try{s.throwIfCancelled(),s.transition("validate");const u=hy(c);gy(c,u);const l=py(c.status,u);if(e.maxBytes!==void 0&&l.expectedBytes!==void 0&&l.expectedBytes>e.maxBytes)throw p("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const f=my(e,a,u,i);let h=0;const m=uy(l.expectedBytes,e.maxBytes);Ui(t,xi(0,l));const E={...o,onProgress(R){!Number.isSafeInteger(R)||R<h||m!==void 0&&R>m||(h=R,Ui(t,xi(h,l)))}};s.transition("transfer"),d=!0;let N;try{N=await n.files.writeResource(f.hostHandle,c.body,{mode:f.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...l.expectedBytes===void 0?{}:{expectedBytes:l.expectedBytes}},E)}catch(R){throw s.normalizeHostError(R,"transfer")}s.transition("committed"),h=dy(N,l,h,e.maxBytes),Ui(t,xi(h,l));const A=i.describeFile(f.handle,f.ref);return s.transition("completed"),A}finally{d||ly(n.network,c.body)}}function dy(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 uy(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function ly(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function fy(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Lo(i.handle.mode),await Dy(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Lo(n.handle.mode),await Ny(n.handle,r),{kind:"directory",...n}}function my(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Ey(e,r),o=n.deriveFile(t,i);return Lo(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function hy(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 p("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!re(e.headers))throw p("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!ny.has(r)||!Array.isArray(n)||n.length===0)throw p("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw p("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function gy(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw p("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:Ay(t,iy)});if((t["content-range"]?.length??0)>0)throw p("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function py(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw p("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw p("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw p("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=yy(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 yy(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function xi(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Ui(e,t){try{e.postProgress(t)}catch{}}function Ey(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=wy(i);if(o&&xn(o))return o}for(const i of r){const o=Iy(i);if(o&&xn(o))return o}if(e.suggestedName!==void 0)return Ss(e.suggestedName);const n=_y(e.url);return n&&xn(n)?n:"download.bin"}function wy(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 Iy(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 _y(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Ss(e){try{dn(e,"suggestedName")}catch{throw p("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!xn(e))throw p("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function xn(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||ay.test(e))}function Ay(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Dy(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw nl()}catch(r){throw Ts(r,"file",t.signal)}}async function Ny(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw nl()}catch(r){throw Ts(r,"file",t.signal)}}function Lo(e){if(e!=="readwrite")throw p("FILE_ACCESS_DENIED","下载目标只允许读取")}const My={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 Ts(e,t,r){if(r.aborted)return il();const n=by(e);if(n&&sy.has(n)){const o=p(n,My[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?p("DOWNLOAD_TIMEOUT","下载网络请求超时"):p("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?p("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):p("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function by(e){return re(e)&&typeof e.code=="string"?e.code:void 0}function nl(){return p("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function il(){return p("DOWNLOAD_CANCELLED","下载已取消")}function Sy(e){if(!e)return;const t=Object.keys(e).find(r=>oy.has(r.trim().toLowerCase()));if(t)throw p("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const xa=8*1024*1024,Ty=32*1024*1024;function Os(e){const t=new Map;let r=0;const n={signal:new AbortController().signal,lifecycle:"cleanup"},i=a=>a.remove(n).catch(()=>{}),o=async a=>{const c=t.get(a);c&&(t.delete(a),r-=c.size,await i(c.target))};e.signal.addEventListener("abort",()=>{for(const a of t.keys())o(a)},{once:!0});const s=a=>{if(e.signal.aborted||a.signal.aborted)throw p("DOWNLOAD_CANCELLED","存档下载已取消")};return{release:o,sizeOf:a=>t.get(a)?.size,async download(a,c,d){const u=a.file;if(!u||typeof u.file_id!="string"||typeof u.name!="string"||typeof u.size_bytes!="number"||!Number.isSafeInteger(u.size_bytes)||u.size_bytes<0||typeof a.download_url!="string"||typeof a.expires_at!="number"||!Number.isSafeInteger(a.expires_at))throw p("INVALID_RESPONSE","存档下载描述无效");if(u.size_bytes>xa)throw p("FILE_TOO_LARGE","存档文件超过 8 MiB");const l={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:a.download_url},timeout:6e4};if(!gu(l)||new URL(a.download_url).pathname!==`/cloud_archive/${u.file_id}.zip`||a.expires_at<=Date.now())throw p("INVALID_RESPONSE","存档下载地址无效");s(d);const f=Math.min(xa,Ty-r);if(f<=0)throw p("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达上限");const h=e.files.sandbox.file(`.hb-game-saves/${Ns()}.zip`);if(!h.remove)throw p("REQUEST_UNSUPPORTED","宿主不支持私有存档清理");r+=f;let m=!1;try{await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},d),await h.create({recursive:!0,exclusive:!0},d);const E=e.registry.createTransferScope();try{const y=E.registerFile(h,"game-save","readwrite");await rl({request:l,url:new URL(a.download_url),to:y.ref,targetKind:"file",maxBytes:f},{...d,trustedUserGesture:!1,postEvent:()=>{},postProgress:()=>{}},{transfer:e.transfer,fileRegistry:E,operationContext:d})}finally{E.dispose()}s(d);const N=(await h.stat(d)).size;if(!Number.isSafeInteger(N)||N<0||N>f)throw p("FILE_TOO_LARGE","存档实际大小超过限额");await c(d),s(d);const A=async()=>{throw p("FILE_ACCESS_DENIED","存档文件只读")},R={kind:"file",mode:"read",name:u.name,create:A,write:A,async read(y){s(y),await c(y);const T=await h.read(y);try{if(s(y),await c(y),T.byteLength!==N)throw p("INVALID_RESPONSE","私有存档副本长度不匹配");return T}catch(j){throw T.fill(0),j}},async stat(y){return s(y),await c(y),await h.stat(y),s(y),await c(y),{kind:"file",size:N,...typeof u.modified_at=="number"&&Number.isSafeInteger(u.modified_at)?{modifiedAt:u.modified_at}:{}}}};return r-=f-N,t.set(R,{target:h,size:N}),m=!0,R}finally{m||(r-=f,await i(h))}}}}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 vy(e){if(!e?.minimumSdkVersion)throw Ie("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=Vt(e.minimumSdkVersion),r=e.sdkVersion?Vt(e.sdkVersion):void 0;if(!t)throw Ie("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw Ie("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=Vt("0.6.0");if(!r){if(Un(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw Ie("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0&&e.allowPublicPrerelease!==!0)throw Ie("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(Un(r,t)<0)throw Ie("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Un(r,Vt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Py(e,t){if(typeof t!="string"||!Vt(t))throw Ie("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw Ie("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function vs(e,t){const r=Vt(e),n=Vt(t);if(!(!r||!n))return Un(r,n)}function Vt(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 Un(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],o=t.prerelease[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}function Ry(e){return{[Gf]:async(t,r)=>{const n=be(e.operationContext,r.signal);if(pe(n.signal),t!==void 0)throw p("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw p("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const o=e.presentation.showAppreciation;if(!o)throw p("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await fe(()=>o({name:i.name,author:i.author},n),n.signal)}}}function nr(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Ua(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function ol(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,N){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:E,type:N})).catch(()=>{})}catch{}}function u(E){const N=r.get(E);if(!N)throw new Error("Unknown runtime cache scope");return N}function l(E,N){return E.flatMap((A,R)=>{const y=JSON.stringify(E.slice(0,R+1));return[JSON.stringify([y]),JSON.stringify([y,N])]})}function f(E,N){return JSON.stringify(l(E,N).map(A=>n.get(A)??0))}async function h(E,N){const A=u(E),R=JSON.stringify([JSON.stringify(A),...N?[N]:[]]),y=(n.get(R)??0)+1;n.set(R,y),i.add(R);for(const T of a)T(A,N);if(!e.store){i.delete(R),d(N??"*","invalidation");return}try{await e.store.invalidate(A,N)}catch(T){throw d(N??"*","storage_error"),T}n.get(R)===y&&i.delete(R),d(N??"*","invalidation")}function m(E){if(c)throw new Error("Runtime cache manager disposed");const N=o.get(E.namespace);if(N){if(N.sourceCodec!==E.codec||N.definition.codec.version!==E.codec.version||JSON.stringify(N.definition.policy)!==JSON.stringify(E.policy))throw new Error("Conflicting runtime cache namespace");return N.cache}if(!E.namespace||!E.codec.version)throw new Error("Invalid runtime cache definition");const A=Object.freeze({...E.policy}),R=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)}),y=E.namespace;for(const L of[A.ttlMs,A.memoryMaxEntries,A.diskMaxEntries,A.diskMaxBytes,A.maxEntryBytes])if(!Number.isFinite(L)||L<0)throw new Error("Invalid runtime cache policy");const T=new Map,j=new Map,I=new Map;let _=!1;function w(L,k,H){if(c||_||L.aborted||f(k,y)!==H)throw nr()}function S(L){return A.ttlMs>0&&A.persistence==="memory-and-disk"&&!!e.store&&!l(L,y).some(k=>i.has(k))}function b(L,k,H){const F=t();return L.envelopeVersion===1&&JSON.stringify(L.address)===JSON.stringify(k)&&Ua(L.revisions,H)&&L.payload.byteLength<=A.maxEntryBytes&&Number.isFinite(L.cachedAt)&&Number.isFinite(L.expiresAt)&&L.cachedAt<=F&&L.cachedAt>=0&&L.expiresAt>L.cachedAt&&Math.min(L.expiresAt,L.cachedAt+A.ttlMs)>F}function U(L,k,H,F,G){if(!(A.ttlMs<=0||A.memoryMaxEntries<1)){for(const[Z,g]of T)Math.min(g.entry.expiresAt,g.entry.cachedAt+A.ttlMs)<=t()&&T.delete(Z);for(T.delete(L);T.size>=Math.floor(A.memoryMaxEntries);){const Z=T.keys().next();if(Z.done)break;T.delete(Z.value)}T.set(L,{entry:k,value:H,epoch:F,persistent:G})}}async function D(L,k,H,F){const G={namespace:y,codecVersion:R.version,scopeIds:k,key:L.key},Z=JSON.stringify(G);let g=[],C=S(k);if(C)try{g=await e.store.readRevisions(k,y)}catch{C=!1,d(y,"storage_error")}w(F.signal,k,H);async function B(){if(!C)return!0;try{return Ua(g,await e.store.readRevisions(k,y))}catch{return C=!1,d(y,"storage_error"),!1}}const Q=T.get(Z);if(A.ttlMs>0&&Q&&Q.epoch===H&&b(Q.entry,G,g)&&Q.persistent===C&&await B())return w(F.signal,k,H),d(y,"memory_hit"),Q.value;if(T.delete(Z),C){let ie,ue;try{ie=await e.store.read(G,A.maxEntryBytes),ie&&b(ie,G,g)?ue=R.decode(ie.payload):ie=void 0}catch{ie=void 0,d(y,"storage_error")}if(w(F.signal,k,H),ie&&await B())return w(F.signal,k,H),U(Z,ie,ue,H,!0),d(y,"disk_hit"),ue}d(y,"miss");const X=R.validate(await L.load(F.signal));w(F.signal,k,H);const ne=R.clone(X);if(!await B()&&C)throw nr();if(w(F.signal,k,H),A.ttlMs>0){const ie=t();let ue;try{ue=R.encode(ne)}catch{return ne}const Ee={envelopeVersion:1,address:G,revisions:C?g:[],cachedAt:ie,expiresAt:ie+A.ttlMs,payload:ue};if(C&&ue.byteLength<=A.maxEntryBytes){let he=!0,ge=!1;try{he=await e.store.publish(Ee,A),ge=he}catch{d(y,"storage_error")}if(w(F.signal,k,H),!he)throw nr();ge&&d(y,"published")}w(F.signal,k,H),U(Z,Ee,ne,H,C)}return ne}async function M(L){if(c||_||L.signal?.aborted)return Promise.reject(nr());const k=u(L.scope),H=f(k,y);let F;if(S(k)){const C=new AbortController;I.set(C,k);const B=()=>C.abort();L.signal?.addEventListener("abort",B,{once:!0});let Q=()=>{};try{F=await Promise.race([e.store.readRevisions(k,y),new Promise((X,ne)=>{const ie=()=>ne(nr());C.signal.addEventListener("abort",ie,{once:!0}),Q=()=>C.signal.removeEventListener("abort",ie)})])}catch{C.signal.aborted||d(y,"storage_error")}finally{Q(),I.delete(C),L.signal?.removeEventListener("abort",B)}}w(L.signal??new AbortController().signal,k,H);const G=JSON.stringify([k,L.key,H,F]);let Z=j.get(G);if(Z?.controller.signal.aborted&&(Z=void 0),!Z){const C=new AbortController;Z={ids:k,controller:C,waiters:0,promise:Promise.resolve(void 0)};const B=Z;B.promise=D(L,k,H,C).finally(()=>{j.get(G)===B&&j.delete(G)}),j.set(G,B)}const g=Z;return g.waiters+=1,new Promise((C,B)=>{let Q=!1;function X(ie){Q||(Q=!0,L.signal?.removeEventListener("abort",ne),g.controller.signal.removeEventListener("abort",ne),g.waiters-=1,g.waiters===0&&g.controller.abort(),ie())}function ne(){X(()=>B(nr()))}L.signal?.addEventListener("abort",ne,{once:!0}),g.controller.signal.addEventListener("abort",ne,{once:!0}),g.promise.then(ie=>X(()=>{try{w(L.signal??new AbortController().signal,k,H),C(R.clone(ie))}catch(ue){B(ue)}}),ie=>X(()=>B(ie)))})}function O(L,k){if(k&&k!==y)return;const H=F=>L.every((G,Z)=>F[Z]===G);for(const[F,G]of T)H(G.entry.address.scopeIds)&&T.delete(F);for(const[F,G]of j)H(G.ids)&&(G.controller.abort(),j.delete(F));for(const[F,G]of I)H(G)&&F.abort()}function z(){if(!_){_=!0,T.clear();for(const L of I.keys())L.abort();I.clear();for(const L of j.values())L.controller.abort();j.clear(),s.delete(z),a.delete(O),o.get(y)?.cache===x&&o.delete(y)}}const x={read:M,invalidateScope:L=>h(L,y),dispose:z};return s.add(z),a.add(O),o.set(y,{definition:{namespace:y,codec:R,policy:A},sourceCodec:E.codec,cache:x}),x}return{createScope(E,N){if(c||!E)throw new Error("Invalid runtime cache scope");const A=Object.freeze({});return r.set(A,[...N?u(N):[],E]),A},register:m,invalidateScope:E=>h(E),dispose(){if(!c){c=!0;for(const E of[...s])E();o.clear(),n.clear(),i.clear()}}}}function Cy(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 ky=".hb-runtime-cache-v1",Ly=1e3,ji=64*1024,ir=1e3,xy=2048,jr=32*1024*1024,Uy=1024,jn=new TextEncoder,ja=new TextDecoder("utf-8",{fatal:!0});function zr(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Dn(e){const t=await globalThis.crypto.subtle.digest("SHA-256",jn.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function ut(e,t){return JSON.stringify(e)===JSON.stringify(t)}function za(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function jy(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function Ba(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function zy(e,t){const r=e.sandbox.directory(ky),n=r.directory("revisions"),i=r.directory("entries");for(const D of[r,n,i,i.directory("capability-check")])Ba(D,["directory","file","create","stat","list","remove"]),Ba(D.file("capability-check"),["create","stat","read","write","remove"]);const o=new AbortController,s=()=>o.abort();t.signal.aborted?s():t.signal.addEventListener("abort",s,{once:!0});const a={...t,signal:o.signal};let c=Promise.resolve(),d;function u(D){d=D,o.abort(),t.signal.removeEventListener("abort",s)}function l(D){if(jy(D))throw u(D),D}function f(){if(d)throw d;if(a.signal.aborted)throw zr()}function h(D,M=a.signal){const O=c.then(()=>{if(M.aborted)throw d??zr();return f(),D()},()=>{if(M.aborted)throw d??zr();return f(),D()}).catch(k=>{throw l(k),k});if(c=O.catch(()=>{}),M.aborted)return Promise.reject(d??zr());let z=()=>{};const x=new Promise((k,H)=>{const F=()=>H(d??zr());M.addEventListener("abort",F,{once:!0}),z=()=>M.removeEventListener("abort",F)}),L=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},Ly);return Promise.race([O,x]).finally(()=>{clearTimeout(L),z()})}async function m(){f(),await n.create({recursive:!0,exclusive:!1},a),f(),await i.create({recursive:!0,exclusive:!1},a),f()}async function E(D,M){const O=n.file(`${await Dn([D,M??null])}.revision`);await A(O);let z=!1;try{await O.create({recursive:!1,exclusive:!0},a),z=!0}catch(k){l(k),f()}if(z){const k=za();return await O.write(jn.encode(k),a),f(),k}const x=await O.stat(a);if(x.size<1||x.size>128)throw new Error("缓存 revision 文件损坏");const L=ja.decode(await O.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(L))throw new Error("缓存 revision 文件损坏");return f(),L}async function N(D){const M=await D.list({limit:ir},a);if(M.length>=ir)throw new Error("缓存目录超过治理上限");return M}async function A(D){try{await D.stat(a);return}catch(O){if(!Nn(O))throw O}if((await N(n)).length>=ir-1)throw new Error("缓存 metadata 超过治理上限")}async function R(D,M){await m();const O=[];for(let z=0;z<D.length;z+=1){const x=D.slice(0,z+1);O.push(await E(x),await E(x,M))}return O}async function y(D){return r.directory(`entries/${await Dn([D.namespace,D.codecVersion,D.scopeIds])}`)}async function T(D){return(await y(D)).file(`${await Dn(D.key)}.cache`)}async function j(D,M){const O=await D.stat(a);if(O.size<5||O.size>M+ji+4)throw new Error("缓存条目超过大小限制");const z=await D.read(a);if(f(),z.length!==O.size)throw new Error("缓存条目读取不完整");const x=new DataView(z.buffer,z.byteOffset,z.byteLength).getUint32(0);if(x<1||x>ji||x+4>z.length)throw new Error("缓存信封损坏");const L=JSON.parse(ja.decode(z.subarray(4,x+4))),k=z.slice(x+4);if(L.envelopeVersion!==1||!L.address||!Array.isArray(L.address.scopeIds)||!L.address.scopeIds.every(H=>typeof H=="string")||typeof L.address.namespace!="string"||typeof L.address.codecVersion!="string"||typeof L.address.key!="string"||!Array.isArray(L.revisions)||L.revisions.length!==L.address.scopeIds.length*2||!L.revisions.every(H=>typeof H=="string"&&H.length>0)||!Number.isSafeInteger(L.cachedAt)||!Number.isSafeInteger(L.expiresAt)||L.cachedAt<0||L.expiresAt<=L.cachedAt||L.payloadBytes!==k.length||k.length>M)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:L.address,revisions:L.revisions,cachedAt:L.cachedAt,expiresAt:L.expiresAt,payload:k}}async function I(D){if(!D.remove)throw new Error("Host 不支持缓存文件删除");await D.remove(a)}async function _(D){try{if((await D.file.stat(a)).size!==D.size)return!1;const M=await j(D.file,jr);return!ut(M.address,D.entry.address)||!ut(M.revisions,D.entry.revisions)||M.cachedAt!==D.entry.cachedAt||M.expiresAt!==D.entry.expiresAt||!ut(await w(M.payload),await w(D.entry.payload))?!1:(await I(D.file),!0)}catch(M){if(Nn(M))return!0;throw M}}async function w(D){const M=await globalThis.crypto.subtle.digest("SHA-256",D);return Array.from(new Uint8Array(M),O=>O.toString(16).padStart(2,"0")).join("")}async function S(){const D=await N(n);let M=0;for(const L of D)if(L.kind==="file"&&(M+=(await L.stat(a)).size,M>jr))throw new Error("缓存扫描超过字节上限");const O=[];let z=0,x=M;for(const L of await N(i)){if(L.kind!=="directory")throw new Error("缓存目录结构损坏");for(const k of await N(L)){if(k.kind!=="file"||++z>xy)throw new Error("缓存文件超过治理上限");const H=(await k.stat(a)).size;if(x+=H,x>jr)throw new Error("缓存扫描超过字节上限");try{const F=await j(k,jr);O.push({file:k,entry:F,size:(await k.stat(a)).size,bucketName:L.name})}catch(F){l(F),f(),Nn(F)||await I(k)}}}return{entries:O,metadataBytes:M}}async function b(){for(const D of await N(i))if(D.kind==="directory"&&D.remove&&(await N(D)).length===0)try{await D.remove({recursive:!1},a)}catch(M){l(M),f()}}function U(D){const{payload:M,...O}=D,z=jn.encode(JSON.stringify({...O,payloadBytes:M.length}));if(z.length>ji)throw new Error("缓存信封过大");const x=new Uint8Array(4+z.length+M.length);return new DataView(x.buffer).setUint32(0,z.length),x.set(z,4),x.set(M,z.length+4),x}return{readRevisions:(D,M)=>h(()=>R(D,M)),read:(D,M)=>h(async()=>{f();const O=await T(D);let z;try{z=await j(O,M)}catch(x){if(f(),Nn(x))return;throw x}if(!(!ut(z.address,D)||z.expiresAt<=Date.now())&&ut(z.revisions,await R(D.scopeIds,D.namespace)))return z}),publish:(D,M)=>h(async()=>{f();const{address:O}=D;if(!ut(D.revisions,await R(O.scopeIds,O.namespace)))return!1;const z=U(D);if(D.payload.length>M.maxEntryBytes||z.length>M.diskMaxBytes||M.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await m();const x=await y(O),L=await T(O),k=await S(),H=[],F=new Map;for(const g of k.entries){if(g.bucketName===x.name&&g.file.name===L.name)continue;const C=JSON.stringify([g.entry.address.scopeIds,g.entry.address.namespace]);let B=F.get(C);if(B||(B=await R(g.entry.address.scopeIds,g.entry.address.namespace),F.set(C,B)),g.entry.expiresAt<=Date.now()||!ut(g.entry.revisions,B)){if(!await _(g))throw new Error("缓存治理期间条目已变化")}else H.push(g)}H.sort((g,C)=>g.entry.cachedAt-C.entry.cachedAt);function G(){const g=H.filter(C=>C.bucketName===x.name);return H.length+1>Uy||z.length+k.metadataBytes+H.reduce((C,B)=>C+B.size,0)>jr||g.length+1>Math.min(M.diskMaxEntries,ir-1)||z.length+g.reduce((C,B)=>C+B.size,0)>M.diskMaxBytes}for(;G();){const g=H.filter(Q=>Q.bucketName===x.name),B=g.length+1>Math.min(M.diskMaxEntries,ir-1)||z.length+g.reduce((Q,X)=>Q+X.size,0)>M.diskMaxBytes?g[0]:H[0];if(!B||!await _(B))throw new Error("缓存容量不足或条目已变化");H.splice(H.indexOf(B),1)}await b();const Z=await N(i);if(!Z.some(g=>g.name===x.name)&&Z.length>=ir-1)throw new Error("缓存目录超过治理上限");if(await x.create({recursive:!0,exclusive:!1},a),!ut(D.revisions,await R(O.scopeIds,O.namespace)))return!1;try{await L.create({recursive:!1,exclusive:!0},a)}catch(g){l(g),await L.stat(a)}return await L.write(z,a),f(),ut(D.revisions,await R(O.scopeIds,O.namespace))}),invalidate:(D,M)=>h(async()=>{await m();const O=n.file(`${await Dn([D,M??null])}.revision`);await A(O);try{await O.create({recursive:!1,exclusive:!0},a)}catch(z){l(z),await O.stat(a)}await O.write(jn.encode(za()),a),f();try{const{entries:z}=await S();for(const x of z){if(M!==void 0&&x.entry.address.namespace!==M||!D.every((k,H)=>x.entry.address.scopeIds[H]===k))continue;const L=await R(x.entry.address.scopeIds,x.entry.address.namespace);ut(x.entry.revisions,L)||await _(x)}await b()}catch(z){l(z),f()}})}}function Nn(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const By="RATE_LIMITED_BY_RUNTIME",Hy="RATE_LIMITED",sl=20,al=40,cl=150,dl=20,ul=1e4,ll=45e3,fl=1,Fy=300*1e3,$y=64;function or(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Vy(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Gy(e={}){const t=e.now??Date.now,r=Vy(e.coalesceWindowMs,cl),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,or(e.budget?.ratePerSecond,sl)),burst:Math.max(1,Math.floor(or(e.budget?.burst,al)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(or(e.loopDetection?.maxCalls,dl))),windowMs:Math.max(1,Math.floor(or(e.loopDetection?.windowMs,ul)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(or(e.circuitBreaker?.failureThreshold,fl))),openMs:Math.max(1,Math.floor(or(e.circuitBreaker?.openMs,ll)))},s=new Map,a=new Map,c=new Set,d=new Map,u=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},l={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let f=!1;function h(_){try{e.onReport?.(_)}catch{}}function m(_,w){if(!i)return{exceeded:!1,count:0};const S=a.get(_)??[],b=w-i.windowMs;let U=0;for(;U<S.length&&S[U]<=b;)U+=1;U>0&&S.splice(0,U);const D=S.length>=i.maxCalls;return D||(S.push(w),S.length>i.maxCalls+1&&S.splice(0,S.length-(i.maxCalls+1))),a.set(_,S),{exceeded:D,count:S.length}}function E(_){if(!n)return!0;const w=Math.max(0,_-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+w*n.ratePerSecond),u.updatedAt=_,u.tokens<1?!1:(u.tokens-=1,!0)}function N(_){if(!n)return 0;const w=Math.max(0,_-u.updatedAt)/1e3,S=Math.min(n.burst,u.tokens+w*n.ratePerSecond);return Math.max(0,Math.ceil((1-S)/n.ratePerSecond*1e3))}function A(_,w,S,b,U){if(!o)return;const D=d.get(w),M=(D?.open?0:D?.failures??0)+1;if(M<o.failureThreshold){d.set(w,{open:!1,openedAt:0,openMs:0,failures:M});return}const O=Math.min(Math.max(o.openMs,b),Fy);d.set(w,{open:!0,openedAt:U,openMs:O,failures:M}),l.circuitOpened+=1,h({type:"circuit_opened",capability:_,endpointId:w,status:S,openMs:O,timestamp:U})}function R(_){const w=d.get(_);w&&!w.open&&d.delete(_)}function y(_){for(const[w,S]of s)!S.pending&&S.expiresAt<=_&&s.delete(w);for(;s.size>=$y;){const w=[...s].find(([,S])=>!S.pending);if(!w)break;s.delete(w[0])}}function T(_,w){if(_===void 0)return;const S=s.get(_);S?.promise===w&&(S.pending=!1)}function j(_,w){if(_===void 0)return;s.get(_)?.promise===w&&s.delete(_)}async function I(_){if(f)return _.load();const w=t();if(o){const D=d.get(_.endpointId);if(D?.open){const M=D.openedAt+D.openMs-w;if(M>0)throw l.circuitRejected+=1,h({type:"circuit_rejected",capability:_.capability,endpointId:_.endpointId,retryAfterMs:M,timestamp:w}),Yy("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:_.endpointId,retryAfterMs:M});d.delete(_.endpointId)}}const S=m(_.endpointId,w);S.exceeded&&i?c.has(_.endpointId)||(c.add(_.endpointId),h({type:"loop_detected",capability:_.capability,endpointId:_.endpointId,count:S.count,windowMs:i.windowMs,timestamp:w})):c.delete(_.endpointId);const b=r>0?_.coalesceKey:void 0;if(b!==void 0){const D=s.get(b);if(D&&(D.pending||D.expiresAt>w))return l.coalesced+=1,h({type:"coalesced",capability:_.capability,endpointId:_.endpointId,timestamp:w}),D.promise;D&&s.delete(b)}if(S.exceeded&&i)throw l.loopRejected+=1,Ha("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:_.capability,endpointId:_.endpointId,count:S.count,windowMs:i.windowMs});if(!E(w)){l.budgetRejected+=1;const D=N(w);throw h({type:"budget_exhausted",capability:_.capability,endpointId:_.endpointId,retryAfterMs:D,timestamp:w}),Ha("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:_.capability,endpointId:_.endpointId,retryAfterMs:D})}b!==void 0&&y(w);const U=_.load().then(D=>(T(b,U),R(_.endpointId),D),D=>{j(b,U);const M=Qy(D);throw M!==void 0&&A(_.capability,_.endpointId,M,qy(D),w),D});return b!==void 0&&s.set(b,{endpointId:_.endpointId,promise:U,expiresAt:w+r,pending:!0}),U}return{execute:I,invalidateCoalescing(_){if(_===void 0){s.clear();return}for(const[w,S]of s)_.includes(S.endpointId)&&s.delete(w)},snapshot(){return{...l,openCircuits:[...d.entries()].filter(([,_])=>_.open).map(([_])=>_)}},dispose(){f||(f=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function Qy(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 qy(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 Ha(e,t){return{code:By,message:e,data:t}}function Yy(e,t){return{code:Hy,message:e,data:t}}const ml=3e4,hl=6e4,xo=1440*60*1e3;function Wy(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??ml)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??hl)):0,steamGameListTtlMs:t?Zy(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:sl,burst:al},coalesceWindowMs:r?.coalesceWindowMs??cl,loopDetection:r?.loopDetection??{maxCalls:dl,windowMs:ul},circuitBreaker:r?.circuitBreaker??{failureThreshold:fl,openMs:ll}}}}function Zy(e){return e===void 0||!Number.isFinite(e)?xo:Math.max(0,Math.floor(e))}function Ky(e){return typeof e=="object"&&e!==null}function Te(e,t){const r=e.data;if(!Ky(r)||typeof r.status!="string")throw new Error(t);return r}const gl={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Jy={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.public.detail.get",method:"GET",path:"/user_miniprogram/public/detail",query(e){return{mini_program_id:e.mini_program_id,...e.miniprogram_version?{miniprogram_version:e.miniprogram_version}:{},...e.preview_token?{preview_token:e.preview_token}:{},...e.local_dev_launch_token?{local_dev_launch_token:e.local_dev_launch_token}:{},...e.entry?{entry:e.entry}:{},...e.h_src_parent?{h_src_parent:e.h_src_parent}:{},...e.extra!==void 0?{extra:e.extra}:{}}},parse(e,t){return Te(e,"工坊小程序详情加载失败")}};function un(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Xy(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function eE(e){const t=Te(e,"小程序登录授权接口响应异常"),r=t.result,n={};if(r.login_code&&typeof r.login_code=="object"){const i=r.login_code;n.loginCode={code:i.code,expiresIn:i.expires_in,scopes:i.scopes||[]}}return r.consent_challenge&&typeof r.consent_challenge=="object"&&(n.consentChallenge=Xy(r.consent_challenge)),{...t,result:n}}const tE={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=>({...un(e.runtimeContext),challenge:e.challenge}),parse:e=>Te(e,"小程序授权取消接口响应异常")},rE={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=>un(e.runtimeContext),parse:e=>Te(e,"小程序授权撤销接口响应异常")},nE={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=>un(e.runtimeContext),parse(e){const t=Te(e,"小程序隔离身份接口响应异常"),r=typeof t.result.steam_id=="string"&&t.result.steam_id.trim()?t.result.steam_id.trim():void 0;return{...t,result:{appUserId:t.result.app_user_id,...r?{steamId:r}:{}}}}},iE={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=>({...un(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>eE(e)},oE={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=>({...un(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=Te(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},sE=64;function pl(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??sE)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(l){for(const[f,h]of i)h.expiresAt<=l&&i.delete(f)}function d(l,f,h){if(a||t<=0||h!==s)return;const m=n();for(c(m),i.delete(l);i.size>=r;){const E=i.keys().next();if(E.done)break;i.delete(E.value)}i.set(l,{expiresAt:m+t,value:f})}function u(l,f){if(a)return f();if(t>0){const N=i.get(l);if(N&&N.expiresAt>n())return Promise.resolve(N.value);N&&i.delete(l)}const h=o.get(l);if(h)return h;const m=s,E=f().then(N=>(d(l,N,m),N)).finally(()=>{o.get(l)===E&&o.delete(l)});return o.set(l,E),E}return{read:u,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function aE(e,t){return t?e?"server":"local":"legacy"}function cE(e,t){if(e==="local")throw p("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const dE=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],uE=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),lE=/authorization|cookie|pkey|password|secret|token/i,yl=/authorization|cookie|pkey|token|password|secret/i;function lt(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function fE(e){for(const t of Object.keys(e))if(!uE.has(t))throw new ke(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of dE)if(Object.prototype.hasOwnProperty.call(e,t)&&lt(e,t)!==void 0)throw new ke(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(lt(e,"bodyEncoding")!==void 0&&lt(e,"bodyEncoding")!=="json"&&lt(e,"bodyEncoding")!=="form")throw new ke("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(lt(e,"failurePresentation")!==void 0&&lt(e,"failurePresentation")!=="none")throw new ke("endpoint failurePresentation 必须为 none");if(lt(e,"auth")!==void 0&&lt(e,"auth")!=="none"&&lt(e,"auth")!=="optional"&&lt(e,"auth")!=="required")throw new ke("endpoint auth 必须为 none、optional 或 required")}function ti(e){if(Array.isArray(e))return e.map(ti);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))lE.test(n)||(r[n]=ti(i));return r}function Fa(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))yl.test(r)||(t[r]=n);return t}function mE(e){if(!e)return;const t=Object.keys(e).find(r=>yl.test(r));if(t)throw new ke(`endpoint 禁止声明 credential-bearing header: ${t}`)}class ln extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;retryAfterMs;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,Object.defineProperty(this,"responseData",{value:t.responseData,enumerable:!1}),t.retryAfterMs!==void 0&&(this.retryAfterMs=t.retryAfterMs),Object.setPrototypeOf(this,new.target.prototype)}}const $a=1440*60*1e3,hE=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function gE(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,$a):void 0}if(!hE.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,$a):void 0}function pE(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 El(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class Dr extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,El(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class fn extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,El(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function yE(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:ti(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Fa(o),method:e.method,metadata:{endpointId:e.id},query:ti(n),timeout:e.timeout,url:r},data:a.data,headers:Fa(a.headers)||{},status:a.status,statusText:a.statusText}}async function yi(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(fE(t),typeof t.id!="string"||!t.id)throw new ke("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new ke("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new ke("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;mE(a);const c=async()=>{let l;try{l=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 ke?h:new Dr({endpointId:t.id,cause:h})}if(l.status<200||l.status>=300)throw new ln({endpointId:t.id,status:l.status,responseData:l.data,retryAfterMs:gE(l.headers)});const f=yE(t,r,i,o,s,a,n,l);if(t.parse)try{return await t.parse(f,r)}catch(h){throw new fn({endpointId:t.id,cause:h})}return f.data},d=n.gate;if(!d)return c();const u=pE(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const EE=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),wE=new Set(_r),Ps="steam_account",wl=new Set(_r.filter(e=>e!==Ps)),IE=1e3;function _E(e){const t=new Set,r=pl({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??ml))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??aE(e.networkEnabled===!0,c),u=e.requestPolicyEnabled!==!1,l=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function f(){if(!c&&!e.authorizationContext)return{};if(!e.authorizationContext)throw p("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let k;try{k=await e.authorizationContext.get(e.operationContext)}catch(F){throw jo(F)?zi(F.code,F.message,F):zi("REQUEST_FAILED","读取 Runtime auth context 失败",F)}if(k.steamAccount!==c||k.userDataMode!==d)throw p("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const H=k.token.trim();if(!H)throw p("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:H}}const h=e.account.onChange(k=>{if(m(),E("heybox_app_login_change",k?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),k&&e.account.getAccountKey){const H=i;j().then(F=>{!o&&i===H&&E("heybox_app_login_change",F)}).catch(()=>{})}});function m(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function E(k,H){k==="user_info_authorization_change"&&SE(H)&&r.invalidate();for(const F of t)try{F(k,H)}catch{}}function N(){const k=e.identity.get()?.miniProgramId?.trim();if(!k)throw p("INVALID_STATE","当前能力缺少 canonical 小程序身份");return k}function A(){if(o||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function R(){A();let k;try{k=await e.account.getCurrentUserId(e.operationContext)}catch(H){throw qa(H,e.operationContext.signal,"读取小黑盒账号失败")}return typeof k=="string"&&k.trim()?k.trim():void 0}async function y(k,H){const F=await R();if(i!==H||F!==k)throw p("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function T(k,H,F=N()){if(!e.account.getAccountKey)throw p("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let G;try{G=await e.account.getAccountKey(F,k,e.operationContext)}catch{throw A(),p("REQUEST_FAILED","读取本地账号标识失败")}if(await y(k,H),N()!==F)throw p("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof G!="string"||!G.trim())throw p("INVALID_RESPONSE","Host 返回了无效的账号标识");return G}async function j(){const k=N(),H=i,F=await R();if(A(),i!==H)throw p("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return F?{isHeyboxAppLoggedIn:!0,accountKey:await T(F,H,k)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function I(k){A();try{await e.account.ensureAuthenticated({trustedUserGesture:k,reason:"runtime_auth",signal:e.operationContext.signal})}catch(F){throw qa(F,e.operationContext.signal,"小黑盒登录失败")}const H=await R();if(!H)throw p("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return H}async function _(k,H,F=e.operationContext.signal){try{if(F.aborted)throw Uo();return await bE(yi(e.network,k,H,{...e.operationContext,credentials:"heybox-session",signal:F,...l?{gate:l}:{}}),F)}catch(G){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):G instanceof ke?p("REQUEST_UNSUPPORTED",G.message):G instanceof fn?p("INVALID_RESPONSE","授权接口响应不合法"):G instanceof Dr?p("REQUEST_FAILED","授权请求失败"):G instanceof ln?u&&(G.status===403||G.status===429)?p("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:G.status,...G.retryAfterMs===void 0?{}:{retryAfterMs:G.retryAfterMs}}):p("REQUEST_FAILED",G.message):jo(G)?G:p("REQUEST_FAILED","授权请求失败")}}async function w(k,H){await _(tE,{runtimeContext:{miniProgramId:k,...await f()},challenge:H}).catch(()=>{})}function S(k){const H=async()=>{const G=Ga(e.operationContext.signal);a=G;try{return await k(G.signal)}finally{a===G&&(a=void 0),G.abort()}},F=s.then(H,H);return s=F.then(()=>{},()=>{}),F}async function b(k,H,F,G,Z){if(!F)throw await w(k,H.challenge),p("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await w(k,H.challenge),p("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return S(async g=>{await y(G,Z);const C=await U(k,H.displayedScopes,g);await y(G,Z);let B;try{B=await e.authPresentation.confirmAuthorization({miniProgramId:k,scopes:H.displayedScopes,...C,signal:g})}catch(X){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await y(G,Z),await w(k,H.challenge),zi("REQUEST_FAILED","授权确认界面执行失败",X))}if(await y(G,Z),B.status!=="granted")throw await w(k,H.challenge),p("AUTHORIZATION_CANCELLED","用户取消授权");const Q=NE(B.grantedScopes,H.displayedScopes,c);if(!Q.includes("identity"))throw await w(k,H.challenge),p("AUTHORIZATION_CANCELLED","用户拒绝授权");return Q})}async function U(k,H,F){const G=Ga(F),Z=setTimeout(()=>G.abort(),IE);try{const g=ME(e.miniProgramPresentation),[C,B]=await Promise.all([g?Promise.resolve(g):D(k,G.signal),H.includes("profile")?M(G.signal):Promise.resolve(void 0)]);return{...C?{miniProgram:C}:{},...B?{userProfile:B}:{}}}finally{clearTimeout(Z),G.abort()}}async function D(k,H){try{const F=e.identity.get()?.version?.trim(),G=await _(Jy,{mini_program_id:k,...F?{miniprogram_version:F}:{}},H),Z=sr(G,"小程序公开资料"),g=gr(Z.name),C=gr(Z.icon_url);return g||C?{...g?{name:g}:{},...C?{avatarUrl:C}:{}}:void 0}catch{return}}async function M(k){try{const H=await _(gl,void 0,k),F=sr(H,"账号基础信息"),G=gr(F.display_username),Z=gr(F.display_avatar);return G||Z?{...G?{nickname:G}:{},...Z?{avatar:Z}:{}}:void 0}catch{return}}async function O(k,H){if(cE(d,"auth.login"),!c&&k.includes(Ps))throw p("INVALID_PARAMS","auth.login 参数不合法");const F=N(),G=await I(H),Z=i,g=await _(iE,{runtimeContext:{miniProgramId:F,...await f()},scopes:k});await y(G,Z);const C=sr(g,"小程序登录"),B=Qa(C,"loginCode"),Q=Qa(C,"consentChallenge");if(B===Q)throw p("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let X;if(B)X=Va(C.loginCode,c);else{const ie=AE(C.consentChallenge,c),ue=await b(F,ie,H,G,Z);await y(G,Z);const Ee=await _(oE,{runtimeContext:{miniProgramId:F,...await f()},challenge:ie.challenge,selectedScopes:ue});if(await y(G,Z),X=Va(sr(Ee,"小程序登录确认"),c),X.scopes.some(he=>!ue.includes(he)))throw p("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ie of X.scopes)n.add(ie);r.invalidate();const ne=e.account.getAccountKey?await T(G,Z,F):void 0;return E("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...ne===void 0?{}:{accountKey:ne}}),E("user_info_authorization_change",Bi(n,c)),{...X,...ne===void 0?{}:{accountKey:ne}}}async function z(k,H){const F=i,G=await _(nE,{runtimeContext:{miniProgramId:H,...await f()}});await y(k,F);const Z=DE(sr(G,"用户本地身份"),c);for(const g of c?_r:wl)n.add(g);return E("user_info_authorization_change",Bi(n,c)),Z}function x(k){A();const H=N(),F=`${k}\0${H}\0${i}\0${c}`;return r.read(F,()=>z(k,H))}async function L(k){if(!k)throw p("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const H=N(),F=i,G=await R();if(!G)throw p("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const Z=await _(rE,{runtimeContext:{miniProgramId:H,...await f()}});await y(G,F),sr(Z,"用户授权撤销"),m(),E("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:j,login:O,async confirmGameSaves(k){if(!k)throw p("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw p("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const H=N(),F=await I(k),G=i;await S(async Z=>{await y(F,G);const g=await U(H,["identity"],Z),C=await e.authPresentation.confirmAuthorization({miniProgramId:H,scopes:["identity","game_saves"],...g,signal:Z});if(await y(F,G),C.status!=="granted"||!C.grantedScopes.includes("game_saves")||!C.grantedScopes.includes("identity"))throw p("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:x,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Bi(n,c),revoke:L,onEvent(k){return t.add(k),()=>t.delete(k)},dispose(){o||(o=!0,m(),r.dispose(),h(),t.clear())}}}function zi(e,t,r){const n=p(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function sr(e,t){if(!re(e))throw p("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":EE.has(r)?r:"REQUEST_FAILED";throw p(n,r)}if(!re(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Va(e,t){if(!re(e))throw p("INVALID_RESPONSE","login code 必须是对象");const r=ri(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 p("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function AE(e,t){if(!re(e))throw p("INVALID_RESPONSE","授权 challenge 必须是对象");const r=ri(e.requestedScopes,"challenge requestedScopes",t),n=ri(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 p("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function DE(e,t){if(!re(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw p("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw p("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 NE(e,t,r){const n=ri(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw p("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function gr(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function ME(e){const t=gr(e?.name),r=gr(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Ga(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 bE(e,t){return t.aborted?Promise.reject(Uo()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Uo()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Uo(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function ri(e,t,r){const n=r?wE:wl;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw p("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Bi(e,t){const r=t?_r:_r.filter(n=>n!==Ps);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function Qa(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function SE(e){return re(e)?Object.values(e).some(t=>t==="denied"):!1}function jo(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}function qa(e,t,r){return t.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):jo(e)?e:p("REQUEST_FAILED",r)}const TE=new Set(_r);function OE(e){return{[qf]:async t=>{if(t!==void 0)throw p("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[Qf]:async(t,r)=>e.authorization.login(vE(t),r.trustedUserGesture)}}function vE(e){if(e===void 0)return["identity"];if(!re(e)||Object.keys(e).some(t=>t!=="scopes"))throw Ya();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!TE.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Ya();return[...e.scopes]}function Ya(){return p("INVALID_PARAMS","auth.login 参数不合法")}const PE={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.delete.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/current/delete",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return Te(e,"排行榜记录删除接口响应异常")}},RE={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/current",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return Te(e,"当前排行榜记录接口响应异常")}},CE={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.info.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/info",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return Te(e,"排行榜信息接口响应异常")}},kE={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.list.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/list",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{},limit:e.limit,...e.cursor?{cursor:e.cursor}:{}}},parse(e,t){return Te(e,"排行榜列表接口响应异常")}},LE={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.submit.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/submit",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{},score:e.score,...e.extra===void 0?{}:{extra:JSON.stringify(e.extra)}}},parse(e,t){return Te(e,"排行榜提交接口响应异常")}},xE={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 Ei(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await fe(()=>yi(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(oi(i)||qr(i,"REQUEST_UNSUPPORTED")||qr(i,"RATE_LIMITED")||qr(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof ke)throw ee("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof Dr&&qr(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof ln){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw ee("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw ee("UNAUTHORIZED","当前用户未登录");const o=UE(i.responseData);if(we(o)&&typeof o.status=="string"&&o.status!=="ok"){const s=we(o.result)?_t(o.result.error_code):void 0;if(o.status==="login"||o.status==="relogin"||ni(o.result)||ni(o)||s&&/^[A-Z][A-Z0-9_]+$/.test(s))throw Il(o,e.subject)}throw ee("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof Dr?ii(e.subject):i instanceof fn?De(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):De(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function it(e,t,r){if(!we(e)||typeof e.status!="string")throw De(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Il(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw De(`${t} 响应缺少 result`);return e.result}function wi(e,t){try{return e.onChange(t)}catch(r){if(qr(r,Yf))return()=>{};throw r}}function Il(e,t){if(e.status==="login"||e.status==="relogin")throw ee("UNAUTHORIZED",_t(e.msg)||"当前用户未登录");if(we(e.result)){const i=_t(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw ee(i,_t(e.result.message)||_t(e.msg)||`${t}请求失败`)}const r=ni(e.result)??ni(e),n=_t(r?.user_message)||_t(e.msg)||_t(r?.developer_message)||`${t}请求失败`;throw r?ee(jE(r),n,{status:e.status,sbe:r}):ee("HEYBOX_API_ERROR",n,{status:e.status})}function UE(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function ni(e){return we(e)&&we(e.sbe)?e.sbe:void 0}function jE(e){const t=_t(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 xE[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 we(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _t(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function qr(e,t){return we(e)&&e.code===t}function ee(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function De(e){return ee("INVALID_RESPONSE",e)}function ii(e){return ee("REQUEST_FAILED",`${e}请求失败`)}function oi(e){return e instanceof Error&&e.name==="AbortError"}const zE="default",jt="排行榜",BE=/^[A-Za-z0-9_-]{1,64}$/,HE=300*1e3,FE=250,$E=3;class VE{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=wi(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(LE,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=it(i,Er,jt);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),Hi(o,Er)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Br("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(kE,{miniProgramId:r,...t}),s=it(o,Tt,jt);if(!we(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw De(`${Tt} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw De(`${Tt} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>Hi(a,Tt)),...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=Br("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(RE,{miniProgramId:n,...t}),c=it(a,Wr,jt);if(!we(c))throw De(`${Wr} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Hi(c.entry,Wr)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(PE,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=it(i,Wn,jt);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!we(o)||typeof o.deleted!="boolean")throw De(`${Wn} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Br("info"),async()=>{const i=await this.request(CE,{miniProgramId:r,...t}),o=it(i,Ht,jt);if(!we(o)||typeof o.key!="string"||!BE.test(o.key))throw De(`${Ht} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw De(`${Ht} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw De(`${Ht} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw De(`${Ht} 返回的 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=Br(t,n),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,l=o?.generation,f=i().then(h=>(this.assertAccountGeneration(u),o&&s&&o.generation===l&&(r==="list"?s.size>=FE&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+HE,value:h})),h)).finally(()=>{this.inflight.get(c)?.promise===f&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:f}),f}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=$E)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)Wa(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){Wa(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await fe(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw oi(n)?n:ii(jt)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ee("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ee("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Br(t,r??zE)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ee("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return Ei({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:jt,assertUsable:()=>this.assertUsable()},t,r)}dispose(){this.disposed||(this.disposed=!0,this.accountGeneration+=1,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.buckets.clear(),this.inflight.clear())}assertUsable(){if(pe(this.options.operationContext.signal),this.disposed)throw ee("INVALID_STATE","Cloud capability 已释放")}}function GE(e){return new VE(e)}function Hi(e,t){if(!we(e))throw De(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw De(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw De(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw De(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw De(`${t} 返回的 score 必须是有限数字`);if(!we(e.extra))throw De(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw De(`${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 Wa(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Br(...e){return JSON.stringify(e)}const QE={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.delete.post",method:"POST",path:"/user_miniprogram/cloud/storage/delete",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken,key:e.key}},parse(e,t){return Te(e,"云端存储删除接口响应异常")}},Za={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.get.post",method:"POST",path:"/user_miniprogram/cloud/storage/get",body(e){return{key:e.key,runtime_auth_context_token:e.runtimeAuthContextToken}},parse(e,t){return Te(e,"云端存储读取接口响应异常")}},Ka={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.keys.post",method:"POST",path:"/user_miniprogram/cloud/storage/keys",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken}},parse(e,t){return Te(e,"云端存储 key 列表接口响应异常")}},qE={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.set.post",method:"POST",path:"/user_miniprogram/cloud/storage/set",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken,key:e.key,value:e.value,expected_version:String(e.expectedVersion),expected_revision:e.expectedRevision}},parse(e,t){return Te(e,"云端存储写入接口响应异常")}},zt="云端存储",YE=3e4,WE=128,ZE=500;class KE{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=wi(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=it(await this.request(Ka,{}),Zn,zt);if(this.assertAccountGeneration(t),!we(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw De("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"?ZE: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=it(await this.request(QE,{key:t}),Po,zt);if(this.assertAccountGeneration(r.generation),!we(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw De("删除结果不合法");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 De("云存储版本超出安全整数范围");const o=it(await this.request(qE,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),ys,zt);if(this.assertAccountGeneration(r.generation),!we(o)||o.success!==!0)throw De("云存储写入结果不合法");const s=Ja({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw De("写入版本凭证不匹配");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(Za,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=Ja(it(c,Ro,zt));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>=WE&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+YE,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([Za.id,Ka.id])}finish(t,r){if(this.unfinished.delete(t)){t.generation===this.accountGeneration&&this.invalidateRead(t.key);for(const n of t.waiters)r===void 0?n.resolve():n.reject(r)}}dispose(){this.disposed||(this.disposed=!0,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.purge(ee("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(ee("UNAUTHORIZED","登录状态已变化,请重试")),this.options.requestGate?.invalidateCoalescing()}purge(t){this.accountGeneration+=1;for(const r of this.timers.values())clearTimeout(r);this.timers.clear();for(const r of[...this.unfinished])this.finish(r,t);this.queues.clear(),this.blockedKeys.clear(),this.cache.clear(),this.inflight.clear(),this.keyGenerations.clear(),this.boundScope=void 0,this.boundUserId=void 0}async requireCurrentUser(t){this.assertAccountGeneration(t);const r=this.readMiniProgramId();let n;try{n=await fe(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw oi(o)?o:ii(zt)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),ee("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),ee("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw ee("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ee("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ee("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw ee("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await fe(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw oi(s)?s:ii(zt)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw ee("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return Ei({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:zt,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(pe(this.options.operationContext.signal),this.disposed)throw ee("INVALID_STATE","Cloud capability 已释放")}}function JE(e){return new KE(e)}function Ja(e){if(!we(e))throw De("云存储读取结果必须是对象");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 De("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw De("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const XE=/^[A-Za-z0-9_-]{1,64}$/,Xa=20,ew=100,ec=2048,tw=/^[A-Za-z0-9_-]{1,128}$/,tc=16*1024;function rw(e){const t=GE(e),r=JE(e);return{handlers:{[Er]:async i=>t.submit(nw(i)),[Tt]:async i=>t.getList(iw(i)),[Wr]:async i=>t.getCurrentUserEntry(Fi(i,Wr)),[Wn]:async i=>t.deleteCurrentUserEntry(Fi(i,Wn)),[Ht]:async i=>t.getInfo(Fi(i,Ht)),[Ro]:async i=>r.getItem(rc(i,Ro)),[ys]:async i=>{const{key:o,value:s}=ow(i);return r.setItem(o,s)},[Po]:async i=>r.removeItem(rc(i,Po)),[Zn]:async i=>(aw(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function nw(e){const t=kr(e,Er,!1);if(Lr(t,["key","score","extra"],Er),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw Qe("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Rs(t.key,Er),score:t.score,...t.extra===void 0?{}:{extra:cw(t.extra)}}}function iw(e){if(e===void 0)return{limit:Xa};const t=kr(e,Tt,!0);Lr(t,["key","limit","cursor"],Tt);const r=t.limit===void 0?Xa:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>ew)throw Qe("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw Qe("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Rs(t.key,Tt),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Fi(e,t){if(e===void 0)return{};const r=kr(e,t,!0);return Lr(r,["key"],t),Rs(r.key,t)}function rc(e,t){const r=kr(e,t,!1);return Lr(r,["key"],t),_l(r.key,t)}function ow(e){const t=ys,r=kr(e,t,!1);Lr(r,["key","value"],t);const n=_l(r.key,t);if(typeof r.value!="string")throw Qe("INVALID_PARAMS",`${t} value 必须是字符串`);if(sw(r.value))throw Qe("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>tc)throw Qe("INVALID_PARAMS",`${t} value 不能超过 ${tc} 字节`);return{key:n,value:r.value}}function sw(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=55296&&r<=56319){const n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return!0;t++}else if(r>=56320&&r<=57343)return!0}return!1}function aw(e){const t=kr(e,Zn,!0);Lr(t,[],Zn)}function _l(e,t){if(typeof e!="string"||!tw.test(e))throw Qe("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function kr(e,t,r){if(e===void 0&&r)return{};if(!Al(e))throw Qe("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Lr(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Qe("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Rs(e,t){if(e===void 0)return{};if(typeof e!="string"||!XE.test(e))throw Qe("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function cw(e){if(!Al(e))throw Qe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw Qe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw Qe("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>ec)throw Qe("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${ec} 字节`);return e}function Al(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qe(e,t){return{code:e,message:t}}const dw={auth:"optional",channel:"api",id:"heybox.user_miniprogram.runtime.game_saves.post",method:"POST",path:"/user_miniprogram/runtime/game_saves",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return Te(e,"游戏存档接口响应异常")}},uw=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function zo(e,t=0){return t>64?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e)&&(!Number.isInteger(e)||Number.isSafeInteger(e)):Array.isArray(e)?e.every(r=>zo(r,t+1)):we(e)&&Object.values(e).every(r=>zo(r,t+1))}function lw(e,t){const r=uw.get(t);if(!r||we(e)&&e.status==="unsupported")return{status:"unsupported"};if(we(e)&&e.game===r){if(e.status==="empty")return{status:"empty"};if(e.status==="failed"&&["UNAUTHORIZED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED"].includes(String(e.error_code)))throw ee(String(e.error_code),"账号或授权已变化");if(e.status==="ready"&&we(e.data)&&zo(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function Dl(e){const t=new Map,r=new Map,n=c=>c.resource?`hb_runtime_game_save_resource_sync_v1_${[c.miniProgramId,c.userId,c.resource].map(encodeURIComponent).join(":")}`:`hb_runtime_game_save_sync_v1_${[c.miniProgramId,c.userId,c.gameId].map(encodeURIComponent).join(":")}`;async function i(c,d,u){const l=n(c),f=r.get(l)??Promise.resolve();let h;const m=new Promise(N=>{h=N}),E=f.then(()=>m);r.set(l,E);try{return await fe(()=>f,d.signal),pe(d.signal),e?.withLock?await e.withLock(l,u):await u()}finally{h(),r.get(l)===E&&E.then(()=>{r.get(l)===E&&r.delete(l)})}}async function o(c,d,u=!1){const l=n(c);if(!u&&t.has(l)||!e)return t.get(l);try{const f=await fe(()=>e.getRaw(l,d),d.signal);if(!f)return;const h=JSON.parse(f);if(!h||typeof h!="object")return;const m=h;return m.version!==1||m.miniProgramId!==c.miniProgramId||m.userId!==c.userId||m.gameId!==c.gameId||(c.resource?m.resource!==c.resource:typeof m.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(m.accountId))||typeof m.taskId!="string"||(c.resource?m.taskId.length<1||m.taskId.length>128:!/^[1-9][0-9]{0,19}$/.test(m.taskId))?void 0:(u||t.set(l,m),m)}catch(f){if(pe(d.signal),u)throw f;return t.get(l)}}async function s(c,d,u){pe(u.signal);const l=n(c),f=d?{...c,version:1,taskId:d}:void 0;if(t.set(l,f),!!e)try{await fe(()=>e.setRaw(l,f?JSON.stringify(f):"",u),u.signal)}catch{pe(u.signal)}}async function a(c,d,u){await i(c,u,async()=>{const l=n(c),f=t.get(l),h=f?.taskId===d&&f.accountId===c.accountId;let m;try{m=await o(c,u,!0)}catch{pe(u.signal),h&&t.set(l,void 0);return}m?.taskId===d&&m.accountId===c.accountId?(await s(c,void 0,u),f&&!h&&t.set(l,f)):h&&t.set(l,m)})}return{run:i,async get(c,d){const u=await o(c,d);if(u&&u.accountId!==c.accountId){t.delete(n(c));return}return u?.taskId},set:s,remove:a,clear(c){for(const d of t.values())d&&a(d,d.taskId,c).catch(()=>{})}}}const fw=2e3,mw=5*6e4;function hw(e){const t=Dl(e.storage);let r=0,n=!1,i;const o=e.fileDownloads??(e.files&&e.transfer?Os({files:e.files,transfer:e.transfer,registry:e.fileRegistry,signal:e.operationContext.signal}):void 0),s=new Set,a=new Map,c={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},d=w=>o?.release(w)??Promise.resolve(),u=new Set;let l=new AbortController,f;const h=()=>{l.abort(),l=new AbortController,f=void 0},m=(w=!0)=>{w&&t.clear(c),r++,h();for(const S of u)S.abort();for(const S of s)d(S).catch(()=>{});s.clear(),a.clear()},E=wi(e.account,w=>{i&&w!==i&&(m(),i=void 0)}),N=e.authorization.onEvent(()=>m());function A(w,S,b,U){if(R(b),U.signal.aborted||!w.account_id||!e.presentation?.showSteamLoginRequired)return;const D=`${w.account_id}:${w.game_id}:${w.task_id??"sync"}`;if(f!==D){f=D;try{e.presentation.showSteamLoginRequired({userId:S,accountId:w.account_id},be(e.operationContext,l.signal))}catch{}}}function R(w){if(n||e.operationContext.signal.aborted)throw ee("RUNTIME_DESTROYED","小程序已关闭");if(w!==r)throw ee("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function y(w,S,b){if(R(S),await e.account.getCurrentUserId(b)!==w)throw m(),ee("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");R(S)}async function T(w,S,b,U){if(await y(S,b,U),!e.authorizationContext)throw ee("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const D=await e.authorizationContext.get(U);if(!D.token||D.expiresAt<=Date.now())throw ee("UNAUTHORIZED","小程序运行上下文已过期");const M=await Ei({network:e.network,operationContext:U,subject:"游戏存档",assertUsable:()=>R(b),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},dw,{...w,runtime_auth_context_token:D.token});if(await y(S,b,U),M.status==="failed"&&we(M.result)&&M.result.error_code==="RECENT_SAVE_AVAILABLE")throw ee("RECENT_SAVE_AVAILABLE",typeof M.msg=="string"&&M.msg?M.msg:"已有近期存档,请直接查询使用");const O=it(M,w.action,"游戏存档");if(!we(O))throw ee("INVALID_RESPONSE","存档响应不合法");return O}async function j(w,S,b){const U=gw(w,S),D=r;if(R(D),w==="file"&&(!e.transfer||!e.files))throw ee("METHOD_FORBIDDEN","宿主不支持存档文件读取");const M=new AbortController;u.add(M);let O=!1;const z=w==="sync"?setTimeout(()=>{O=!0,M.abort()},mw):void 0,x=be(be(e.operationContext,b.signal),M.signal);try{const L=await e.account.getCurrentUserId(x);if(!L)throw ee("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==L)throw m(),ee("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=L,w==="sync"||w==="parsed"){if(w==="sync"&&h(),!U.account_id){const Z=await T({action:"check",game_id:U.game_id},L,D,x);U.account_id=nn(Z.account_id)}if(w==="sync")return await I(U,L,D,x)}const k=await T({action:w,...U},L,D,x);if(w==="list")return pw(k);if(w==="parsed")return lw(k.parsed_data,U.game_id);if(Nl(k.file).fileId!==U.file_id)throw ee("INVALID_RESPONSE","文件标识不匹配");if(!o)throw ee("REQUEST_UNSUPPORTED","宿主不支持存档下载");const F=await o.download(k,async Z=>{try{R(D),await T({action:"check",game_id:U.game_id,account_id:U.account_id},L,D,Z)}catch(g){const C=we(g)?String(g.code):"";throw["RUNTIME_DESTROYED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED","UNAUTHORIZED"].includes(C)?(m(),ee("FILE_ACCESS_REVOKED","游戏存档授权已失效")):g}},x);let G=!1;try{if(await y(L,D,x),R(D),x.signal.aborted)throw ee("DOWNLOAD_CANCELLED","存档下载已取消");const Z=e.fileRegistry.registerFile(F,"game-save","read");return s.add(F),a.set(Ns(),{file:F,sizeBytes:o.sizeOf(F)}),G=!0,Z}finally{G||await o.release(F)}}catch(L){throw O?ee("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):L}finally{z!==void 0&&clearTimeout(z),u.delete(M)}}async function I(w,S,b,U){const D=e.identity.get()?.miniProgramId;if(!D)throw ee("INVALID_STATE","小程序身份尚未确认");const M={miniProgramId:D,userId:S,gameId:w.game_id,accountId:w.account_id},O=x=>T({action:"status",...w,task_id:x},S,b,U);let z;try{const x=await t.run(M,U,async()=>{await y(S,b,U);const k=await t.get(M,U);if(k){z=k;try{return{taskId:k,status:await O(k)}}catch(F){if(!we(F)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(F.code)))throw F;await t.set(M,void 0,U),z=void 0}}const H=await T({action:"sync",...w},S,b,U);return z=nn(H.task_id),await t.set(M,z,U),await y(S,b,U),{taskId:z,status:void 0}});z=x.taskId;let L=x.status;for(;;){if(R(b),U.signal.aborted)throw ee("REQUEST_CANCELLED","已停止等待存档同步");if(L??=await O(z),L.state==="succeeded"||L.state==="failed"){if(await t.remove(M,z,U),await y(S,b,U),L.state==="succeeded")return{state:"succeeded"};throw ee(L.error_code?si(L.error_code):"SYNC_FAILED",L.message?si(L.message):"存档同步失败")}if(L.state!=="syncing"&&L.state!=="uploading")throw ee("INVALID_RESPONSE","同步状态不合法");L=void 0,await yw(fw,U.signal)}}catch(x){if(we(x)){const L=String(x.code);L==="STEAM_LOGIN_REQUIRED"&&A({...w,task_id:z},S,b,U),z&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(L)&&await t.remove(M,z,c)}throw x}}return{handlers:{"gameSaves.list":(w,S)=>j("list",w,S),"gameSaves.sync":(w,S)=>j("sync",w,S),"gameSaves.readParsedData":(w,S)=>j("parsed",w,S),"gameSaves.getFile":(w,S)=>j("file",w,S)},diagnostics:{async getSnapshot(){const w=r;return i&&await y(i,w,e.operationContext),R(w),Array.from(a,([S,b])=>({id:S,name:b.file.name,sizeBytes:b.sizeBytes}))},async readFile(w,S){const b=r;R(b);const U=a.get(w);if(!U)throw ee("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const D=be(e.operationContext,S);D.signal.throwIfAborted();const M=await U.file.read(D);try{return D.signal.throwIfAborted(),R(b),{name:U.file.name,bytes:M}}catch(O){throw M.fill(0),O}}},allowsRead(w,S){return["file.readBytes","file.readText","file.stat","file.exists"].includes(w)&&we(S)&&e.fileRegistry.isGameSaveRef(S.target)},dispose(){n||(n=!0,m(!1),E(),N())}}}function gw(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!we(t)||Object.keys(t).some(i=>!r.includes(i)))throw ee("INVALID_PARAMS","存档参数不合法");const n=Yr(t.gameId);if(Number(n)>2147483647)throw ee("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:Yr(t.accountId)}:{},...e==="file"?{save_id:Yr(t.saveId),file_id:Yr(t.fileId)}:{}}}function Yr(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw ee("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function nn(e){try{return Yr(e)}catch{throw ee("INVALID_RESPONSE","服务端存档标识无效")}}function si(e){if(typeof e!="string")throw ee("INVALID_RESPONSE","服务端存档字段无效");return e}function Bo(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw ee("INVALID_RESPONSE","服务端存档数值无效");return e}function Nl(e){if(!we(e))throw ee("INVALID_RESPONSE","存档文件信息无效");return{fileId:nn(e.file_id),name:si(e.name),originalPath:si(e.original_path),sizeBytes:Bo(e.size_bytes),modifiedAt:Bo(e.modified_at)}}function pw(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw ee("INVALID_RESPONSE","存档列表无效");return{accountId:nn(e.account_id),saves:e.saves.map(t=>{if(!we(t)||!Array.isArray(t.files)||t.files.length>200)throw ee("INVALID_RESPONSE","存档文件列表无效");return{saveId:nn(t.save_id),createdAt:Bo(t.created_at),files:t.files.map(Nl)}})}}function yw(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(o),t.removeEventListener("abort",i),n(ee("REQUEST_CANCELLED","已停止等待存档同步"))},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}const Ew=new Set(["stdio","attachments","notifications"]),Ml=new Set(["windows-x64","macos-arm64"]),ww=new Set(["unsigned","valid","invalid","unknown"]),Iw=/^[a-f0-9]{64}$/,_w=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Aw=new Set(vu),Dw=new Set([...vu,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),bl=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 Nw(e){const t=async(n,i,o,s)=>{const a=Mw(n);try{gt(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return gt(i.signal),c}catch(c){throw Fo(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw p("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>bw(d,i)).catch(d=>{throw Fo(d)});gt(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(gt(o.signal),c.status!=="granted")throw p("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[Jd]:(n,i)=>t(n,i,async(o,s)=>Ho(await e.companion.getInfo(o,s),o)),[Kd]:(n,i)=>t(n,i,async(o,s)=>nc(await e.companion.getPreparationStatus(o,s))),[Zd]:(n,i)=>t(n,i,async(o,s)=>{const a=nc(await e.companion.getPreparationStatus(o,s));return gt(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),gt(i.signal),Ho(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(Tl(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[Wd]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Yd]:(n,i)=>t(n,i,async(o,s)=>ic(await e.companion.getActiveSession(o,s),o)),[qd]:(n,i)=>t(n,i,async(o,s)=>{const a=ic(await e.companion.getActiveSession(o,s),o);return gt(i.signal),a||(await r("launch",o,i),gt(i.signal),Ol(await e.companion.launch(o,s),o))}),[Qd]:(n,i)=>ar(n,i,e,"write"),[Gd]:(n,i)=>ar(n,i,e,"closeStdin"),[Vd]:(n,i)=>ar(n,i,e,"terminate"),[$d]:(n,i)=>ar(n,i,e,"ackOutput"),[Fd]:async(n,i)=>{const o=await ar(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Hd]:(n,i)=>ar(n,i,e,"showNotification")}}function Mw(e){if(!re(e)||typeof e.alias!="string"||!Vh.test(e.alias))throw p("INVALID_PARAMS","Companion alias 不合法");return e.alias}function gt(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function ar(e,t,r,n){if(!re(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw p("INVALID_PARAMS","Companion Session controller 不合法");try{gt(t.signal);const i=await r.companion[n](Sw(e,n),{...r.operationContext,signal:t.signal});return gt(t.signal),i}catch(i){throw Fo(i)}}function at(){throw p("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Sl(e){return!Array.isArray(e)||e.some(t=>!Ew.has(t))?at():Object.freeze([...new Set(e)])}function Ho(e,t){return!re(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Ml.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!ww.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?at():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Sl(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function bw(e,t){const r=Ho(e,t);return!re(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!Iw.test(e.sha256)?at():Object.freeze({...r,sha256:e.sha256})}function Tl(e){return re(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):at():at()}function nc(e){return re(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Tl(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&re(e.error)&&typeof e.error.code=="string"&&Aw.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:bl[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):at():at()}function Ol(e,t){return!re(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Ml.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?at():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Sl(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function ic(e,t){return e===void 0?void 0:Ol(e,t)}function Sw(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Mu(r.data))throw p("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 p("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw p("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw p("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function Tw(e){return!re(e)||!_w.has(String(e.reason))?at():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):at():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?at():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Ow(e){if(!re(e)||!re(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,r=t.sessionId;if(e.type==="companion.session.output")return!Number.isSafeInteger(t.controllerGeneration)||Number(t.controllerGeneration)<0||t.stream!=="stdout"&&t.stream!=="stderr"||!Number.isSafeInteger(t.sequence)||Number(t.sequence)<0||!Mu(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:Tw(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 Fo(e,t){return re(e)&&typeof e.code=="string"&&Dw.has(e.code)?p(e.code,bl[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&re(e)&&e.name==="AbortError"?p(t,"Companion 准备已取消"):p("COMPANION_HOST_FAILED","Companion Host 操作失败")}const oc=5e3,sc=1e4;function $e(e){throw{code:"INVALID_PARAMS",message:e}}function Cs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vl(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&$e(`${r} 不支持字段: ${n.join(", ")}`)}function vw(e){if(e===void 0)return{intensity:"light",delay:0};if(!Cs(e))return $e("device.vibrate 参数必须是对象");vl(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return $e("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>oc?$e(`device.vibrate delay 必须是 0-${oc} 的整数毫秒`):{intensity:r,delay:n}}function Pw(e){return Cs(e)?(vl(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?$e("device.setClipboard text 必须是非空字符串"):e.text.length>sc?$e(`device.setClipboard text 不能超过 ${sc} 字符`):{text:e.text}):$e("device.setClipboard 参数必须是对象")}function Rw(e){return typeof e=="string"?e.trim()?e:$e("device.executeProtocol 协议字符串不能为空"):Cs(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?$e("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):($o(e,new Set),e):$e("device.executeProtocol 参数必须是协议字符串或协议对象")}function $o(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||$e("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":$e("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":$e(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&$e("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)$o(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&$e("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))$o(i,t);t.delete(r)}function Cw(e){return{[Kf]:async(t,r)=>{const n=be(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.vibrate(vw(t),n),n.signal)},[Zf]:async(t,r)=>{const n=be(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.setClipboard(Pw(t),n),n.signal)},[Wf]:async(t,r)=>{const n=be(e.operationContext,r.signal,r.requestId);pe(n.signal);const i=Rw(t);await fe(()=>e.protocol.invoke(i,n),n.signal)}}}const ac=1e3,kw=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function Lw(e){const t=r=>be(e.operationContext,r.signal);return{files:{[sm]:async(r,n)=>{$i(n);const i=Vi(e.picker),o=xw(r),s=await Ye(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[om]:async(r,n)=>{$i(n);const i=Vi(e.picker),o=Uw(r),s=await Ye(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[im]:async(r,n)=>{$i(n);const i=Vi(e.picker),o=jw(r).suggestedName,s=t(n);if(!i.saveFile)throw ot("files.saveFile");const a=await Ye(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[ru]:async(r,n)=>{const i=Je(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);cr(o.mode),await Ye(()=>o.create(cc(i),t(n)))},[Ks]:async(r,n)=>{const i=Je(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),cr(o.handle.mode),!o.handle.remove)throw ot(Ks);await Ye(()=>o.handle.remove(t(n)))},[nm]:async(r,n)=>{const i=Je(r);return dc(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!re(o)||o.kind!=="file")throw lc()})},[tu]:async(r,n)=>{const i=Je(r),o=uc(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 p("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[rm]:async(r,n)=>{const i=Je(r,["content"]);typeof i.content!="string"&&tt("content 必须是字符串");const o=e.registry.resolveFile(i.target);cr(o.mode),await Ye(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[eu]:async(r,n)=>{const i=Je(r),o=await Ye(()=>e.registry.resolveFile(i.target).read(t(n)));return uc(o)},[tm]:async(r,n)=>{const i=Je(r,["content"]),o=e.registry.resolveFile(i.target);cr(o.mode),await Ye(()=>o.write(Bw(i.content),t(n)))},[Xd]:async(r,n)=>{const i=Je(r),o=await Ye(()=>e.registry.resolveFile(i.target).stat(t(n)));return Hw(o)}},directory:{[em]:async(r,n)=>{const i=Je(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);cr(o.mode),await Ye(()=>o.create(cc(i),t(n)))},[Zs]:async(r,n)=>{const i=Je(r,["recursive"]);if(re(i.target)&&i.target.relativePath===".")throw p("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),cr(o.handle.mode),!o.handle.remove)throw ot(Zs);await Ye(()=>o.handle.remove({recursive:i.recursive===void 0?!1:ai(i.recursive,"recursive")},t(n)))},[Xf]:async(r,n)=>{const i=Je(r);return dc(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!re(o)||o.kind!=="directory")throw lc()})},[Jf]:async(r,n)=>{const i=Je(r,["limit"]),o=zw(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 xw(e){if(e===void 0)return{mode:"read",multiple:!1};re(e)||tt("pickFiles 参数必须是对象"),Ii(e,["mode","accept","multiple"]);const t=Pl(e.mode,"read"),r=e.multiple===void 0?!1:ai(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)))&&tt("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function Uw(e){return e===void 0?{mode:"read"}:(re(e)||tt("pickDirectory 参数必须是对象"),Ii(e,["mode"]),{mode:Pl(e.mode,"read")})}function jw(e){return re(e)||tt("saveFile 参数必须是对象"),Ii(e,["suggestedName"]),{suggestedName:dn(e.suggestedName,"suggestedName")}}function Je(e,t=[]){return(!re(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&tt("文件操作参数必须包含 target"),Ii(e,["target",...t]),e}function cc(e){return{recursive:e.recursive===void 0?!1:ai(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:ai(e.exclusive,"exclusive")}}function Pl(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&tt("mode 必须是 read 或 readwrite"),e)}function ai(e,t){return typeof e!="boolean"&&tt(`${t} 必须是布尔值`),e}function zw(e){if(e===void 0)return ac;if((!Number.isSafeInteger(e)||e<=0)&&tt("limit 必须是正整数"),e>ac)throw p("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Ii(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&tt(`不支持字段: ${r.join(", ")}`)}function cr(e){if(e!=="readwrite")throw p("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function $i(e){if(!e.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Vi(e){if(!e)throw ot("files.external");return e}async function dc(e){try{return await e(),!0}catch(t){if(kw.has(Ms(t)??""))return!1;throw Ar(t)}}async function Ye(e){try{return await e()}catch(t){throw Ar(t)}}function Bw(e){return e instanceof Uint8Array||tt("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&tt("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function uc(e){if(!(e instanceof Uint8Array))throw p("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function lc(){return p("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Hw(e){if(!re(e)||e.kind!=="file"||!Fw(e.size))throw p("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!$w(e[t]))throw p("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 Fw(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function $w(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function tt(e){throw p("INVALID_PARAMS",e)}const fc=16*1024,mc=200;function Vw(e){const t=Wu(e.runtimePermissions);function r(n,i){e.capabilities&&nu(i,e.capabilities);const o=t({kind:"all",permissions:["filesystem"]},i);if(!o.allowed)throw p(o.code,o.message);const s=be(e.operationContext,n);return Vo(s),s}return{async list(n,i={}){const o=r(i.signal,"directory.list"),s=e.registry.resolveDirectoryEntry({kind:"directory",root:{kind:"sandbox"},relativePath:n}),a=await hc(()=>s.handle.list({limit:mc},o),o);return e.registry.describeListedEntries(s,a,mc).map(({name:c,kind:d})=>({name:c,kind:d}))},async read(n,i={}){const o=i.maxBytes??fc;if(!Number.isSafeInteger(o)||o<1||o>fc)throw p("INVALID_PARAMS","诊断读取最多允许 16384 bytes");const s=r(i.signal,"file.readBytes"),a=e.registry.resolveFile({kind:"file",root:{kind:"sandbox"},relativePath:n});if(!a.readPrefix)throw p("DIAGNOSTICS_UNSUPPORTED","当前 Host 不支持有界文件诊断读取");const c=await hc(()=>a.readPrefix({maxBytes:o},s),s);if(!c||!(c.bytes instanceof Uint8Array)||c.bytes.byteLength>o||typeof c.truncated!="boolean")throw p("FILE_IO_FAILED","Host 返回了无效的有界读取结果");return{bytes:new Uint8Array(c.bytes),truncated:c.truncated}}}}function Vo(e){if(e.signal.aborted)throw p("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")}async function hc(e,t){let r;try{const n=await Promise.race([e(),new Promise((i,o)=>{r=()=>o(p("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")),t.signal.addEventListener("abort",r,{once:!0}),t.signal.aborted&&r()})]);return Vo(t),n}catch(n){throw t.signal.aborted&&Vo(t),Ar(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const Gw=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),Gi={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function Qw(e){if(e instanceof ke)return p("REQUEST_UNSUPPORTED",Gi.REQUEST_UNSUPPORTED);const t=Rl(e);return t!==void 0&&Gw.has(t)?p(t,Gi[t]??"媒体操作失败"):p("MEDIA_PREPARE_FAILED",Gi.MEDIA_PREPARE_FAILED)}function Rl(e){try{if(!re(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const qw=["source","mediaType","maxCount"],zn=Object.freeze({source:"album",mediaType:"all",maxCount:1});function Yw(e){if(e===void 0)return zn;if(!bh(e))throw p("INVALID_PARAMS",Zw(e));return Ww(e)}function Ww(e){return Object.freeze({source:e.source??zn.source,mediaType:e.mediaType??zn.mediaType,maxCount:e.maxCount??zn.maxCount})}function Zw(e){if(!re(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!qw.includes(r));if(t.length>0)return`media.pick 不支持字段: ${t.join(", ")}`;if(e.source!==void 0&&e.source!=="album"&&e.source!=="camera")return"source 必须是 album 或 camera";if(e.mediaType!==void 0&&e.mediaType!=="image"&&e.mediaType!=="video"&&e.mediaType!=="all")return"mediaType 必须是 image、video 或 all";if(e.maxCount!==void 0){if(typeof e.maxCount!="number"||!Number.isSafeInteger(e.maxCount))return"maxCount 必须是安全整数";if(e.source==="camera"&&e.maxCount!==1)return"相机只支持 maxCount 为 1 或省略,不能静默收窄"}return"media.pick 参数不合法"}const Kw=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),Jw={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class Xw{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=eI(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>rI(s,i[a]));if(!Sh(o))throw pt("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(nI).filter(s=>s!==void 0)),o}}releaseBatch(t,r){this.releaseItems(t,r)}dispose(){if(this.disposed)return;this.disposed=!0;const t=[...this.committed];this.committed.clear(),this.releaseItems(t,{...this.operationContext,lifecycle:"cleanup"})}registerBatch(t,r){try{return this.registry.registerFiles(t.map(n=>n.file),"external","read",r)}catch(n){const i=Rl(n);throw i!==void 0&&Kw.has(i)?n:pt("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function gc(e,t){if(e.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw p("REQUEST_CANCELLED","media.pick 已取消")}function eI(e,t){if(!Array.isArray(e))throw pt("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw pt("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw pt("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw pt("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw pt("Host 返回了稀疏媒体结果");tI(e[n],n)}return e}function tI(e,t){if(!re(e))throw pt(`第 ${t+1} 项不是对象`);if(!Nu({...e,file:Jw}))throw pt(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!re(e.file))throw pt(`第 ${t+1} 项缺少文件句柄`)}function rI(e,t){const r={mimeType:e.mimeType,size:e.size,width:e.width,height:e.height,previewUrl:e.previewUrl,file:t};return e.type==="video"?{...r,type:"video",durationMs:e.durationMs}:{...r,type:"image"}}function nI(e){return"handleId"in e.ref?e.ref.handleId:void 0}function pt(e){return p("MEDIA_PREPARE_FAILED",e)}function iI(e){const t=e.media?new Xw(e.registry,e.media,e.operationContext):void 0;return{handlers:{[Js]:async(n,i)=>{const o=Yw(n);sI(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw ot(Js);const c=be(e.operationContext,i.signal);gc(e.operationContext,i.signal);const d=await oI(s,o,c,e.operationContext,i.signal);gc(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function oI(e,t,r,n,i){try{return await fe(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?p("REQUEST_CANCELLED","media.pick 已取消"):Qw(o)}}function sI(e){if(!e.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Mn=4294967296;function aI(e){const t=new cI;return t.write(e),t.finish()}class cI{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<Mn?(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=dI(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<Mn)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/Mn),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Mn)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function dI(e){const t=new Uint8Array(uI(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 uI(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 Cl(e){Go(e);const t=aI(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 Go(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)Go(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");Go(s,t+1,r)}r.delete(e)}const lI=["pc","console","mobile"],fI=["game","wiki"];function ci(e){throw{code:"INVALID_PARAMS",message:e}}function mI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ct(e,t){return typeof e!="string"||!e.trim()?ci(t):e.trim()}function pc(e,t,r){return typeof e!="string"||!t.includes(e)?ci(r):e}function hI(e){const t={target:"game_detail",appId:Ct(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:pc(e.gameType,lI,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=pc(e.page,fI,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Ct(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Ct(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function gI(e){return{target:"user_detail",userId:Ct(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function pI(e){const t={target:"post_detail",linkId:Ct(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Ct(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Ct(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function yI(e){const t={target:"mini_program",miniProgramId:Ct(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function EI(e){return mI(e)?e.target==="game_detail"?hI(e):e.target==="user_detail"?gI(e):e.target==="post_detail"?pI(e):e.target==="mini_program"?yI(e):ci("navigation.openAppPage target 不支持"):ci("navigation.openAppPage options 必须是对象")}function wI(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 II(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function _I(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 AI(e){const t=e;return t.target==="game_detail"?wI(t):t.target==="user_detail"?II(t):_I(t)}const DI="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",NI="data-hb-sdk-fullscreen-exit",MI=3e3,bI=2e3,yc="var(--white-70a,rgba(255,255,255,.7))",Ec="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function SI(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(NI,""),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 ${yc}`,`box-shadow:${Ec}`,"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=DI,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let o=!0,s=!1,a=!1,c,d;function u(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function l(){o||(t.style.width=u())}function f(){d?.cancel(),d=void 0}function h(N=bI){clearTimeout(c),c=setTimeout(()=>{f(),o=!1,t.style.width=u(),t.style.opacity="0.5",t.style.borderColor="var(--white-40a,rgba(255,255,255,.4))",t.style.boxShadow="none",n.style.visibility="hidden",i.style.display="none",t.setAttribute("aria-label","展开退出全屏按钮"),t.setAttribute("aria-expanded","false")},N)}function m(){f(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=yc,t.style.boxShadow=Ec,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),h()}async function E(){if(!(s||a)){if(!o){m();return}a=!0,clearTimeout(c),f();try{await e()}catch{}finally{a=!1,s||m()}}}return t.addEventListener("click",E),window.addEventListener("resize",l),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(MI),{dispose(){s=!0,clearTimeout(c),f(),t.removeEventListener("click",E),window.removeEventListener("resize",l),t.remove()}}}const kl=1e4;function Ll(e,t){const r=new AbortController;let n;const i=()=>{n??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},r.abort()};e.addEventListener("abort",i,{once:!0}),t?.addEventListener("abort",i,{once:!0}),(e.aborted||t?.aborted)&&i();const o=setTimeout(()=>{n??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},r.abort()},kl);return{signal:r.signal,async run(s){try{return await fe(s,r.signal)}catch(a){throw n??a}},dispose(){clearTimeout(o),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function wc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 参数必须是对象"};const{orientation:t,fullscreen:r}=e;if(t!==void 0&&t!=="portrait"&&t!=="landscape")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay orientation 必须是 portrait 或 landscape"};if(r!==void 0&&typeof r!="boolean")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay fullscreen 必须是布尔值"};if(t===void 0&&r===void 0)throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 至少设置 orientation 或 fullscreen"};return{orientation:t,fullscreen:r}}function Qi(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Hr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function TI(e){let t=0,r=0,n,i,o={mode:"portrait",hideCapsule:!1},s={mode:"portrait",hideCapsule:!1},a;function c(){a?.dispose(),a=void 0}function d(m){if(!m.hideCapsule){c();return}a??=SI(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",c,{once:!0});function u(m,E){if(n===m){if(n=void 0,clearTimeout(m.timer),e.operationContext.signal.removeEventListener("abort",l),"error"in E)m.controller.abort();else if(i={options:m.options,result:E.result},o=m.options,d(m.options),e.onApplied?.(m.options),E.result.supported&&!Qi(s,m.options)){s={...m.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:m.source})}catch{}}for(const N of m.subscribers)N.dispose(),"error"in E?N.reject(E.error):N.resolve(E.result);m.subscribers.clear()}}function l(){n&&u(n,{error:Hr()})}function f(m,E){return new Promise((N,A)=>{const R=()=>{m.subscribers.delete(y),y.dispose(),A(Hr()),m.subscribers.size===0&&u(m,{error:Hr()})},y={resolve:N,reject:A,dispose:()=>E?.removeEventListener("abort",R)};m.subscribers.add(y),E?.addEventListener("abort",R,{once:!0}),E?.aborted&&R()})}const h={async runDisplayRequest(m,E,N){const A=++t,R=Ll(E,e.operationContext.signal);try{return await R.run(async()=>{if(await N(R.signal),R.signal.aborted)throw Hr();if(wc(m),A<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=A,h.apply(m,R.signal)})}finally{R.dispose()}},async apply(m,E,N="api"){if(pe(e.operationContext.signal),E?.aborted)throw Hr();const A=wc(m),R=n?.options??o,y={mode:A.orientation??R.mode,hideCapsule:A.fullscreen??R.hideCapsule};y.mode==="landscape"&&(y.hideCapsule=!0);const T=e.presentation.applyOrientation;if(!T)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&Qi(n.options,y))return f(n,E);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&Qi(i.options,y))return i.result;i=void 0;const j={options:y,source:N,controller:new AbortController,subscribers:new Set};n=j;const I=f(j,E);return e.operationContext.signal.addEventListener("abort",l,{once:!0}),E||(j.timer=setTimeout(()=>{u(j,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},kl)),fe(()=>T.call(e.presentation,y,{...e.operationContext,signal:j.controller.signal}),j.controller.signal).then(_=>u(j,{result:_??{supported:!0}}),_=>u(j,{error:_})),I},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return h}function xl(e){throw{code:"INVALID_PARAMS",message:e}}function Ic(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&xl(`${t} 不支持参数`)}function OI(e){return{[dm]:async(t,r)=>{const n=be(e.operationContext,r.signal,r.requestId);pe(n.signal),Ic(t,"navigation.close"),await fe(()=>e.presentation.close(n),n.signal)},[cm]:async(t,r)=>{const n=be(e.operationContext,r.signal,r.requestId);pe(n.signal),Ic(t,"navigation.reload"),await fe(()=>e.presentation.reload(n),n.signal)},[am]:async(t,r)=>{const n=be(e.operationContext,r.signal,r.requestId);pe(n.signal);const i=EI(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Cl(i.extra)}catch{xl("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=Ll(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}pe(n.signal),await fe(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await fe(()=>e.presentation.openAppPage(AI(i),n),n.signal)}}}const _c={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function vI(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw ot("network.upload");const o=be(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw p("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(f){throw s(),Ar(f)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw p("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw p("FILE_TOO_LARGE","文件超过大小限制");let d=0,u=!1;const l=f=>{u||o.signal.aborted||!Number.isSafeInteger(f)||f<d||f>c.size||(d=f,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:f,...h}=e,m=await n.upload(a,{...h,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:l});if(u=!0,!Number.isSafeInteger(m.uploadedBytes)||m.uploadedBytes<d||m.uploadedBytes>c.size)throw p("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(m.status>=200&&m.status<300&&m.uploadedBytes!==c.size)throw p("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:m.uploadedBytes,total:c.size,lengthComputable:!0}),m}catch(f){u=!0;const h=Ms(f);throw h&&_c[h]?p(h,_c[h]):o.signal.aborted?p("UPLOAD_CANCELLED","上传已取消"):h?.startsWith("FILE_")||h?.startsWith("DIRECTORY_")?Ar(f):p("UPLOAD_NETWORK_FAILED","上传网络失败")}}const ks="withCredentials",PI=new Set(["url","method","params","data","headers","timeout",ks]),RI=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",ks]),CI=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Ac=3e4,Qo=2*1024*1024,kI=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Ul=/[\u0000-\u0008\u000A-\u001F\u007F]/,LI=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,xI="network.request 不支持 multipart/form-data,请使用专用上传能力";function UI(e){const t=jI(e.runtimePermissions);t.networkPolicy=Fu(e.networkPolicy);const r=JI(e.allowedHttpOrigins);return{[fm]:async(n,i)=>{const o=BI(n,{permission:t,allowedHttpOrigins:r}),s=await vI(o,i,e),{uploadedBytes:a,...c}=s;return Nc(c)},[lm]:async(n,i)=>{const o=HI(n,{permission:t,allowedHttpOrigins:r});return rl(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[um]:async(n,i)=>{const o=be(e.operationContext,i?.signal);pe(o.signal);const s=zI(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await fe(()=>e.network.request(s,o),o.signal)}catch(c){throw e_(c)?c:t_(c,"REQUEST_UNSUPPORTED")?me("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):me("REQUEST_FAILED","网络请求失败")}return Nc(a)}}}function jI(e){const t=Ve(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function zI(e,t){const r=Nr(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!PI.has(c));if(n.length>0)throw me("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);jl(r,"network.request");const i=Ls(r,t,"network.request"),o=$I(r.method),s=r.data;s!==void 0&&QI(s),YI(i.headers,s);const a=WI(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 BI(e,t){const r=Nr(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(u=>!n.has(u)))throw me("INVALID_PARAMS","network.upload 包含不支持的字段");const i=Ls(r,t,"network.upload");if(i.official)throw me("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw me("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!Yt(r.from))throw me("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw me("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw me("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw me("INVALID_PARAMS","上传 HTTP 方法不支持");const s={from:r.from,format:r.format,request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"upload",method:o,...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}};if(r.format==="raw"){if(["fieldName","fields","fileName","contentType"].some(u=>r[u]!==void 0))throw me("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(u=>u.toLowerCase()==="content-type"))throw me("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=Dc(r.fieldName),c=r.fields===void 0?void 0:Nr(r.fields,"fields 必须是字符串字典");for(const[u,l]of Object.entries(c??{}))if(Dc(u),typeof l!="string"||u===a)throw me("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw me("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||Ul.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw me("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:a,fields:c,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>Qo)throw me("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:Ss(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function Dc(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw me("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function HI(e,t){const r=Nr(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!RI.has(c));if(n.length>0)throw me("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);jl(r,"network.download");const i=Ls(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw me("INVALID_PARAMS","network.download timeout 必须是有限正数");Sy(i.headers);const o=Yt(r.to),s=Au(r.to);if(!o&&!s)throw me("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw me("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw me("INVALID_PARAMS","suggestedName 必须是字符串");a=Ss(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw me("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw me("INVALID_PARAMS","maxBytes 必须是正的 safe integer");return{request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"download",method:"GET",...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},url:i.url,to:r.to,targetKind:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function Ls(e,t,r){const n=FI(e.url,t.allowedHttpOrigins,r),i=t.permission.networkPolicy,o=i?.enforcement==="approved_domains"&&n.protocol==="http:"&&t.allowedHttpOrigins.has(n.origin);if(i&&!o&&(n.protocol!=="https:"||n.port!==""||!i.entries.some(a=>a.domain===n.hostname.toLowerCase())))throw me("PERMISSION_DENIED",`${r} 目标不在平台批准的域名清单中`);const s=gp(n);if(s&&!t.permission.useOfficialDomain)throw me("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(hp(n.pathname,s))throw me("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:s,params:e.params===void 0?void 0:{...Nr(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:VI(e.headers,r),timeout:GI(e.timeout,r)}}function FI(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw me("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw me("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw me("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw me("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw me("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function $I(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw me("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!CI.has(t))throw me("INVALID_PARAMS","network.request method 不合法");return t}function VI(e,t="network.request"){const r=Nr(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!kI.test(s)||typeof o!="string"||Ul.test(o))throw me("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(pp(s))throw me("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function jl(e,t){const r=e[ks];if(r!==void 0&&typeof r!="boolean")throw me("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function GI(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw me("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Ac)throw me("INVALID_PARAMS",`${t} timeout 不能超过 ${Ac}ms`);return e}}function QI(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw me("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(qI(e)>Qo)throw me("INVALID_PARAMS",`network.request data 不能超过 ${Qo} 字节`)}function qI(e){if(typeof e=="string")return qi(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return qi(e.toString());try{const t=JSON.stringify(e);return t?qi(t):0}catch{throw me("INVALID_PARAMS","network.request data 必须可序列化")}}function YI(e,t){const r=zl(e),n=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(r?.includes("multipart/form-data")||n)throw me("INVALID_PARAMS",xI)}function WI(e,t,r){if(t===void 0)return;const n=zl(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)||KI(t))?"form":ZI(t)?"json":void 0}function zl(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function ZI(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function KI(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function JI(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&&XI(n.hostname)&&t.add(n.origin)}catch{}return t}function XI(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 Nc(e){return Object.keys(e.headers).some(Mc)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Mc(t)))}:e}function Mc(e){const t=e.trim().toLowerCase();return LI.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function e_(e){return e instanceof Error&&e.name==="AbortError"}function t_(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Nr(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw me("INVALID_PARAMS",t);return e}function qi(e){return new TextEncoder().encode(e).length}function me(e,t){return{code:e,message:t}}function r_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function n_(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 i_(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=n_(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function o_(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 Bl(e,t){if(e==null)return{};if(!r_(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=i_(e.topicIds),n=o_(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 s_(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function a_(e){try{if(s_(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function xe(e){throw{code:"INVALID_PARAMS",message:e}}function mn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qo(e,t){return typeof e!="string"||!e.trim()?xe(t):e}function c_(e,t){const r=qo(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?xe(t):r}catch{return xe(t)}}function d_(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Hl(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return xe(`${t} 缺少有效的小程序分享地址`);try{const o=new URL(e.environment.getCurrentHref()),s=new URL("/tools/common_share",o);s.searchParams.set("user_miniprogram_id",i);const a=n?.version?.trim();a&&s.searchParams.set("miniprogram_version",a);const c=o.searchParams.get("h_src");return c?.trim()&&s.searchParams.set("h_src",c),r!==void 0&&s.searchParams.set("extra",r),s.href}catch{return xe(`${t} 缺少有效的小程序分享地址`)}}function u_(e,t){if(!mn(e))return xe("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return xe("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!d_(r))return xe("share.showShareMenu channel 不合法");const n=Fl(e.extra,"share.showShareMenu");return{title:qo(e.title,"share.showShareMenu title 必须是非空字符串"),description:qo(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Hl(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:c_(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Fl(e,t){if(e!==void 0)try{return Cl(e)}catch{return xe(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function $l(e,t){return e.invalidMessage&&await fe(()=>a_(t.environment),t.operationContext.signal)?xe(e.invalidMessage):e.post}function bc(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function l_(e){const t=e.getViewportMetrics();return{left:0,top:0,width:bc(t.windowWidth,0),height:bc(t.windowHeight,0)}}function Yo(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?xe(t):r}function Sc(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?xe(t):r}function f_(e){return mn(e)?{left:Yo(e.left,"share.screenshot rect.left 必须是非负数字"),top:Yo(e.top,"share.screenshot rect.top 必须是非负数字"),width:Sc(e.width,"share.screenshot rect.width 必须是正数"),height:Sc(e.height,"share.screenshot rect.height 必须是正数")}:xe("share.screenshot rect 必须是对象")}function Tc(e,t){if(e!=null&&!mn(e))return xe("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?xe("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?xe("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?l_(t):f_(r.rect),...r.delay===void 0?{}:{delay:Yo(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function m_(e,t){pe(t.operationContext.signal);const r=u_(e,t);let n=Bl(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await $l(n,t);return fe(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function h_(e,t){if(pe(t.operationContext.signal),e!==void 0&&!mn(e))return xe("share.copyLink 参数必须是对象");const r=Fl(e?.extra,"share.copyLink"),n=Hl(t,"share.copyLink",r);return await fe(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Oc(e,t,r,n=!1){pe(t.operationContext.signal);const i=Bl(mn(e)?e.post:void 0,{method:"share.screenshot"}),o=await $l(i,t),s=t.identity.get()?.miniProgramId.trim()||void 0,a=g_(),{watermarkTheme:c,...d}=r;let u=!1,l,f,h;try{if(n&&(!t.presentation.supportsLongScreenshot||!t.prepareLongScreenshot))throw{code:"REQUEST_UNSUPPORTED",message:"当前宿主不支持 DOM 长图,请更新宿主"};if(u=!0,await fe(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),n){const N=await t.prepareLongScreenshot(r.rect,t.operationContext.signal);l=N.restore,d.rect=N.rect}f=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,c),h={status:"fulfilled",value:await fe(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:o,...s?{sourceMiniProgramId:s}:{}},t.operationContext),t.operationContext.signal)}}catch(E){h={status:"rejected",error:E}}finally{try{f?.()}finally{l?.()}}const m=u?await p_(t.presentation,a,t.operationContext.signal):void 0;if(h.status==="rejected")throw h.error;if(m)throw m;return h.value}function g_(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function p_(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await fe(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function y_(e){let t=Promise.resolve();const r=async(n,i)=>{const o=be(e.operationContext,i.signal,i.requestId),s=Tc(n,e.presentation);(s.rect.top+s.rect.height>1e4||s.rect.left+s.rect.width>2048||s.rect.width*s.rect.height>4e6)&&xe("长图尺寸超出限制");const a=t.then(()=>Oc(n,{...e,operationContext:o},s,!0));return t=a.then(()=>{},()=>{}),a};return{[pm]:r,[gm]:(n,i)=>h_(n,{...e,operationContext:be(e.operationContext,i.signal,i.requestId)}),[hm]:(n,i)=>m_(n,{...e,operationContext:be(e.operationContext,i.signal,i.requestId)}),[mm]:async(n,i)=>{const o=be(e.operationContext,i.signal,i.requestId);pe(o.signal);const s=Tc(n,e.presentation),a=t.then(()=>Oc(n,{...e,operationContext:o},s));return t=a.then(()=>{},()=>{}),fe(()=>a,o.signal)}}}const E_=128,w_=/^[A-Za-z0-9_-]+$/;function I_(e){const t=e.scopedStorage??Vu({storage:e.storage,resolveScope:()=>$u({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[ea]:async n=>{pe(e.operationContext.signal);const i=vc(n,ea,e.storageLimits?.maxKeyLength),o=await fe(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:Pc(o)}},[Xs]:async n=>{pe(e.operationContext.signal);const i=Vl(n,"storage.setStorage 参数必须是对象"),o=vc(i,Xs,e.storageLimits?.maxKeyLength),s=__(i.data,e.storageLimits?.maxValueBytes);await fe(()=>t.set(o,s,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(pe(e.operationContext.signal),(await fe(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?Wt("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:Pc(o),serializedValue:o,bytes:Gl(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function vc(e,t,r=E_){const i=Vl(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Wt("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!w_.test(i))throw Wt("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function __(e,t){let r;try{r=JSON.stringify(e)}catch{throw Wt("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw Wt("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Gl(r)>t)throw Wt("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Pc(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Vl(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Wt("INVALID_PARAMS",t);return e}function Gl(e){return new TextEncoder().encode(e).length}function Wt(e,t){return{code:e,message:t}}const Rc=120;function vt(e){throw{code:"INVALID_PARAMS",message:e}}function xs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ql(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&vt(`${r} 不支持字段: ${n.join(", ")}`)}function A_(e){if(!xs(e))return vt("ui.showToast 参数必须是对象");if(Ql(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return vt("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Rc)return vt(`ui.showToast message 不能超过 ${Rc} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return vt("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function D_(e){return e===void 0?{dismissible:!1}:xs(e)?(Ql(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?vt("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):vt("ui.showLoading 参数必须是对象")}function N_(e){e!==void 0&&(!xs(e)||Object.keys(e).length)&&vt("ui.hideLoading 不支持参数")}function M_(e){return{[wm]:async(t,r)=>{const n=be(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.showToast(A_(t),n),n.signal)},[Em]:async(t,r)=>{const n=be(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.showLoading(D_(t),n),n.signal)},[ym]:async(t,r)=>{const n=be(e.operationContext,r.signal,r.requestId);pe(n.signal),N_(t),await fe(()=>e.presentation.hideLoading(n),n.signal)}}}const b_={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return Te(e,"当前用户首页资料接口响应异常")}},S_=3e4;function T_(e,t,r={}){const n=r.ttlMs??S_,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function d(){let l;try{l=await yi(e,b_,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(f){throw t.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):f instanceof ke?p("REQUEST_UNSUPPORTED",f.message):f instanceof fn?p("INVALID_RESPONSE","user home_v2 响应不合法"):f instanceof Dr?p("REQUEST_FAILED","user home_v2 请求失败"):f instanceof ln?i&&(f.status===403||f.status===429)?p("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:f.status,...f.retryAfterMs===void 0?{}:{retryAfterMs:f.retryAfterMs}}):p("REQUEST_FAILED",f.message):v_(f)?f:p("REQUEST_FAILED","user home_v2 请求失败")}return O_(l,"user home_v2")}function u(l){const f=Date.now();if(a?.userId===l&&a.expiresAt>f)return Promise.resolve(a.value);if(c?.userId===l&&c.generation===s)return c.promise;const h=s,m=d().then(E=>(s===h&&(a={userId:l,value:E,expiresAt:Date.now()+n}),E)).finally(()=>{c?.promise===m&&(c=void 0)});return c={userId:l,generation:h,promise:m},m}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function O_(e,t){if(!re(e))throw p("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 p(n,r)}if(!re(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function v_(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}const P_={auth:"optional",channel:"api",id:"heybox.bbs.app.profile.follow.user.post",method:"POST",path:"/bbs/app/profile/follow/user",bodyEncoding:"form",failurePresentation:"none",query(e){return e.query?{...e.query}:void 0},body(e){return{...e.body??{}}},parse(e,t){return Te(e,"关注用户接口响应异常")}},R_={auth:"none",channel:"api",id:"heybox.user_miniprogram.runtime.author.follow_status.post",method:"POST",path:"/user_miniprogram/runtime/author/follow_status",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return Te(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowStatus 接口响应异常")}},C_={auth:"none",channel:"api",id:"heybox.user_miniprogram.runtime.author.follow_guidance.begin.post",method:"POST",path:"/user_miniprogram/runtime/author/follow_guidance/begin",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return Te(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowGuidanceBegin 接口响应异常")}},k_={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.game.steam.get_game_list.get",method:"GET",path:"/game/steam/get_game_list",query(e){return{userid:e.userId,...e.steamId?{steam_id:e.steamId}:{},limit:e.limit,offset:e.offset,sort:e.sort,need_hidden:e.includeHidden,...e.personalInformationOpen===void 0?{}:{personal_infomation_open:e.personalInformationOpen},...e.q?{q:e.q}:{}}},parse(e,t){return Te(e,"Steam 游戏库接口响应异常")}};function L_(e,t=xo){const r=Cy({version:"2",validate:U_}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):xo,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 Cc(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 x_(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 U_(e){if(!re(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(kc(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw pr();for(const t of e.gameList){if(!re(t)||!Wo(t.appid)||!Wo(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw pr();for(const r of["image","portraitImage","icon"])j_(t,r);for(const r of["playtimeForever","playtime2Weeks"])kc(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw pr()}return e}function Wo(e){return typeof e=="number"&&Number.isFinite(e)}function kc(e,t){if(e[t]!==void 0&&!Wo(e[t]))throw pr()}function j_(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw pr()}function pr(){return p("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const ql=20,z_=100,B_=128,Yl=0,Wl="weeks",H_=100,F_=new Set(["weeks","all","achieved"]);function $_(){return{nickname:"",avatar:""}}function V_(e){const t=T_(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??ol(),i=L_(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(O,z){const x=JSON.stringify([O,z]);return(!o||o.key!==x)&&(o={key:x,scope:n.createScope(z,n.createScope(O))}),o.scope}function d(){const O=o;o=void 0,O&&n.invalidateScope(O.scope).catch(()=>{}),s.clear()}const u=pl({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??hl))}),l=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let f,h,m=0,E=!1;const N=e.account.onChange(()=>{m+=1,t.clear(),u.invalidate(),d()}),A=e.authorization.onEvent((O,z)=>{O==="user_info_authorization_change"&&Object.values(z).some(x=>x==="denied")&&(m+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(E)return;const x=await e.account.getCurrentUserId(e.operationContext);typeof x=="string"&&x.trim()&&await n.invalidateScope(c(y(),x.trim()))}).catch(()=>{}))});function R(){if(E||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function y(){const O=e.identity.get()?.miniProgramId?.trim();if(!O)throw p("INVALID_STATE","用户能力缺少 canonical 小程序身份");return O}async function T(){R(),await a,R();let O;try{O=await e.account.getCurrentUserId(e.operationContext)}catch(z){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Fr(z)?z:p("REQUEST_FAILED","读取小黑盒账号失败")}return typeof O=="string"&&O.trim()?O.trim():void 0}async function j(O,z){const x=await T();if(m!==z||x!==O)throw p("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function I(O,z,x=e.operationContext.signal){try{return await yi(e.network,O,z,{...e.operationContext,signal:x,credentials:"heybox-session",...l?{gate:l}:{}})}catch(L){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):L instanceof ke?p("REQUEST_UNSUPPORTED",L.message):L instanceof fn?p("INVALID_RESPONSE","用户接口响应不合法"):L instanceof Dr?p("REQUEST_FAILED","用户请求失败"):L instanceof ln?r&&(L.status===403||L.status===429)?p("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:L.status,...L.retryAfterMs===void 0?{}:{retryAfterMs:L.retryAfterMs}}):p("REQUEST_FAILED",L.message):Fr(L)?L:p("REQUEST_FAILED","用户请求失败")}}async function _(O,z){if(!e.authorizationContext)return{mini_program_id:O};let x;try{x=await fe(()=>e.authorizationContext.get({...e.operationContext,signal:z}),z)}catch(L){if(Fr(L))throw L;const k=p("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(k,"cause",{configurable:!0,value:L}),k}if(!x.token?.trim())throw p("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:O,runtime_auth_context_token:x.token}}async function w(){R();const O=y(),z=m,x=await T();if(!x){if(m!==z)throw p("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const L=await _(O,e.operationContext.signal);await j(x,z);const k=await I(R_,L);if(await j(x,z),y()!==O)throw p("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Uc(xc(k))}function S(O,z){if(!O)return Promise.reject(p("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(z?.aborted)return Promise.reject(p("REQUEST_CANCELLED","关注操作已取消"));if(f)return Promise.reject(p("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(p("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const x=b(z).finally(()=>{f===x&&(f=void 0)});return f=x,x}async function b(O){R();const z=y(),x=new AbortController;h=x;const L=()=>x.abort();e.operationContext.signal.addEventListener("abort",L,{once:!0}),O?.addEventListener("abort",L,{once:!0});let k=()=>{},H=!1;try{try{await fe(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:x.signal}),x.signal)}catch(ue){throw Fr(ue)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(ue.code)?p("FOLLOW_CANCELLED","已取消小黑盒登录"):ue}R();const F=m;k=e.account.onChange(()=>{H=!0,L()});const G=await fe(T,x.signal);if(!G)throw p("FOLLOW_CANCELLED","未完成小黑盒登录");const Z=async()=>{if(await fe(()=>j(G,F),x.signal),R(),y()!==z)throw p("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await Z();const g=await _(z,x.signal);await Z();const C=X_(),B=await fe(()=>I(C_,{...g,request_id:C},x.signal),x.signal);await Z();const Q=xc(B);if(Q.status!=="notFollowing")return Uc(Q);if(Q.rateLimited)throw p("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const X=await fe(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:z,signal:x.signal}),x.signal);if(await Z(),X!=="confirmed")throw p("FOLLOW_CANCELLED","已取消关注作者");const ne=Q.authorId,ie=await fe(()=>I(P_,{body:{following_id:ne}},x.signal),x.signal);if(await Z(),ie.status!=="ok"){const ue=["login","relogin","lack_token"].includes(ie.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw p(ue,typeof ie.msg=="string"&&ie.msg.trim()?ie.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(F){throw R(),H?p("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):O?.aborted?p("REQUEST_CANCELLED","关注操作已取消"):Fr(F)?F:p("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{k(),e.operationContext.signal.removeEventListener("abort",L),O?.removeEventListener("abort",L),h===x&&(h=void 0)}}async function U(){y();const O=m,z=await T();if(!z)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[x,L]=await Promise.all([e.authorization.getOrCreateLocalIdentity(z),D(z).catch(()=>$_())]);return await j(z,O),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:x.appUserId,profile:L,...x.steamId?{steam_id:x.steamId}:{}}}}function D(O){return u.read(O,()=>I(gl,void 0).then(z=>{const x=Zo(z,"账号基础信息");if(x.display_username!==void 0&&typeof x.display_username!="string")throw p("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(x.display_avatar!==void 0&&typeof x.display_avatar!="string")throw p("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:x.display_username??"",avatar:x.display_avatar??""}}))}async function M(O){const z=G_(O),x=y(),L=m,k=await T();if(!k)return d(),{isLogin:!1,isBound:!1,data:null};const H=await t.get(k);await j(k,L);const F=Zl(H.steam_id_info);if(Object.keys(F).length===0)return await n.invalidateScope(c(x,k)).catch(()=>{}),await j(k,L),s.delete(JSON.stringify([x,k])),{isLogin:!0,isBound:!1,data:null};const G=JSON.stringify([x,k]),Z=c(x,k),g=Cc({...z,steamId:void 0},F),C=Kl(F.personal_infomation_open??F.personal_information_open),B=JSON.stringify([g??null,C??null]),Q=s.get(G);Q&&Q.identity!==B&&(await n.invalidateScope(Z).catch(()=>{}),await j(k,L));const X={identity:B,scope:n.createScope(B,Z)};s.set(G,X);const ne=Cc(z,F),ie=ne?i.persistent:i.unresolved,ue=n.createScope(ne??"unresolved",X.scope),Ee=async()=>{if(await j(k,L),y()!==x||s.get(G)?.identity!==B)throw p("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},he=await ie.read({scope:ue,key:x_({miniProgramId:x,userId:k,effectiveSteamId:ne,personalInformationOpen:C,query:z}),signal:e.operationContext.signal,load:async ge=>{const ye=await I(k_,{userId:k,...z,personalInformationOpen:C},ge);return await Ee(),Z_(Zo(ye,"Steam 游戏库"),z)}}).catch(async ge=>{throw await Ee(),ge});return await Ee(),{isLogin:!0,isBound:!0,data:he}}return{getFollowStatus:w,requestFollowAuthor:S,getInfo:U,getSteamGameList:M,async invalidateSteamGameListCache(){const O=y(),z=m,x=await T();if(!x)return;const L=c(O,x);await Promise.all([i.persistent.invalidateScope(L),i.unresolved.invalidateScope(L)]),t.clear(),s.delete(JSON.stringify([O,x])),await j(x,z)},dispose(){E||(E=!0,h?.abort(),m+=1,N(),A(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function G_(e){if(e==null)return{limit:ql,offset:Yl,sort:Wl,includeHidden:!1};if(!re(e))throw Pt("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Pt(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Q_(e.limit),offset:q_(e.offset),sort:Y_(e.sort),includeHidden:W_(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>B_)throw Pt("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Pt("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,H_))}return r}function Q_(e){if(e===void 0)return ql;if(!Number.isInteger(e)||Number(e)<1)throw Pt("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),z_)}function q_(e){if(e===void 0)return Yl;if(!Number.isInteger(e)||Number(e)<0)throw Pt("user.getSteamGameList offset 必须是非负整数");return Number(e)}function Y_(e){if(e===void 0)return Wl;if(typeof e!="string"||!F_.has(e))throw Pt("user.getSteamGameList sort 不支持");return e}function W_(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Pt("user.getSteamGameList includeHidden 必须是 boolean");return e}function Z_(e,t){if(!Array.isArray(e.game_list))throw p("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(K_).filter(a=>a!==void 0),n=di(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=Kl(e.is_me);return s!==void 0&&(o.isMe=s),o}function K_(e){const t=Zl(e),r=di(t.appid),n=di(t.steam_appid)??r,i=Us(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};Yi(o,"image",t.image),typeof t.vertical_head_image=="string"&&Yi(o,"portraitImage",t.vertical_head_image),Yi(o,"icon",t.appicon??t.icon),Lc(o,"playtimeForever",t.playtime_forever),Lc(o,"playtime2Weeks",t.playtime_2weeks);const s=J_(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function Zo(e,t){if(!re(e))throw p("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 p(n,r)}if(!re(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Zl(e){return re(e)?e:{}}function Us(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function J_(e){return Array.isArray(e)?e.map(Us).filter(Boolean):[]}function di(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function Kl(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function Yi(e,t,r){const n=Us(r);n&&Object.assign(e,{[t]:n})}function Lc(e,t,r){const n=di(r);n!==void 0&&Object.assign(e,{[t]:n})}function Pt(e){return p("INVALID_PARAMS",e)}function Fr(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}function xc(e){const t=Zo(e,"关注状态");if(![0,1,2].includes(t.follow_status)||typeof t.author_id!="string"||!/^[1-9]\d*$/.test(t.author_id)||typeof t.rate_limited!="boolean")throw p("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Uc(e){return e.status}function X_(){const e=globalThis.crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function eA(e){return{[Nm]:async t=>(bn(t,"user.getFollowStatus"),e.user.getFollowStatus()),[Dm]:async(t,r)=>(bn(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[Am]:async t=>(bn(t,"user.getInfo"),e.user.getInfo()),[_m]:async(t,r)=>{bn(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Im]:async t=>e.user.getSteamGameList(t)}}function bn(e,t){if(e!==void 0)throw p("INVALID_PARAMS",`${t} 不接收入参`)}function tA(){return p("USER_DATA_PERMISSION_STATE_INVALID","本地用户数据许可状态异常,已停止访问")}function jc(e){return p("USER_DATA_PERMISSION_SAVE_FAILED","本次运行已停止访问,设置未保存,请重试",e===void 0?void 0:{reason:e instanceof Error?e.message:String(e)})}function rA(e){const t=e.managedResources??hr,r=typeof e.storage.withLock=="function"||typeof navigator<"u"&&!!navigator.locks,n=e.hash??iu,i=new Map,o=new Set;let s=!1;function a(){if(s)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function c(y,T){if(e.storage.withLock)return e.storage.withLock(u(y),T);if(typeof navigator<"u"&&navigator.locks)return Gu(u(y),T);throw p("REQUEST_UNSUPPORTED","当前宿主不支持跨实例保存资料许可")}function d(y){return Sm({miniProgramId:e.resolveMiniProgramId(),userId:y,environment:e.resolveEnvironment()})}function u(y){return yh(bm(d(y)))}function l(y,T){return e.purposeOf?n(Su(y,e.revisionOf(y),T,e.purposeOf(y))):n(`${y}\0${e.revisionOf(y)}\0${T}`)}function f(y,T){return`${y}\0${T}`}async function h(y,T){let j;try{j=await e.storage.getRaw(u(y),T)}catch(_){throw a(),T.signal.aborted?p("REQUEST_CANCELLED","许可操作已取消"):p("USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","无法读取本地用户数据许可",{reason:_ instanceof Error?_.message:String(_)})}if(a(),T.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");const I=j===void 0||j===""?void 0:Mm(j);if(j!==void 0&&j!==""&&I===void 0)throw tA();return I??{schema_version:1,records:{}}}async function m(y,T,j){if(a(),j.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");await e.storage.setRaw(u(y),JSON.stringify(T),j)}function E(y){return y?.revision??0}function N(y,T,j){const I=new Set(j.declared??[]),_=new Set(t);for(const b of Object.keys(T.records))bt(b)&&_.add(b);for(const b of i.keys())b.startsWith(`${y}\0`)&&_.add(b.slice(y.length+1));const S=[..._].sort((b,U)=>{const D=hr.indexOf(b),M=hr.indexOf(U);return(D<0?Number.MAX_SAFE_INTEGER:D)-(M<0?Number.MAX_SAFE_INTEGER:M)}).map(b=>{const U=T.records[b],D=E(U),M=j.egressTier===void 0?void 0:l(b,j.egressTier),O=i.get(f(y,b)),z=O!==void 0&&O.revision===D&&(M===void 0||O.consentFingerprint===M);return{resource:b,name:hi(b)?.name??b,purposeText:e.purposeOf?.(b)??"",scopeFingerprint:M??"",declared:I.has(b),available:I.has(b),decision:U?.decision??"ask",revision:D,...U?.decision==="allow"&&U.consentFingerprint?{consentFingerprint:U.consentFingerprint}:{},sessionAllowed:z,allowed:!o.has(f(y,b))&&I.has(b)&&U?.decision!=="deny"&&(z||r&&U?.decision==="allow"&&M!==void 0&&U.consentFingerprint===M)}});return Object.freeze({schema_version:1,canPersist:r,resources:Object.freeze(S),...j.egressTier===void 0?{}:{egressTier:j.egressTier}})}function A(y,T,j,I){const _=T.records[j],w=f(y,j);if(o.has(w))return{status:"denied",reason:"tightening"};if(_?.decision==="deny")return{status:"denied",reason:"deny"};const S=l(j,I);if(r&&_?.decision==="allow"&&_.consentFingerprint===S)return{status:"allowed",source:"persistent"};const b=i.get(w);return b&&b.revision===E(_)&&b.consentFingerprint===S?{status:"allowed",source:"session"}:{status:"ask"}}function R(y){if(typeof y!="string"||!hr.includes(y))throw p("INVALID_PARAMS","用户数据资源标识不合法")}return{canPersist:r,async read(y,T,j={}){a();const I=await h(y,T);return N(y,I,j)},async evaluate(y,T,j){a(),R(T.resource);const I=await h(y,j);return A(y,I,T.resource,T.egressTier)},async decide(y,T){a(),R(y.resource);const j=async()=>{a();const I=await h(y.userId,T);if(a(),T.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");const _=I.records[y.resource],w=E(_);if(y.expectedRevision!==void 0&&w!==y.expectedRevision)throw p("AUTHORIZATION_CONTEXT_CHANGED","资料许可已变化,请重新确认");const S=f(y.userId,y.resource),b=l(y.resource,y.egressTier);if(y.expectedFingerprint!==void 0&&y.expectedFingerprint!==b)throw p("AUTHORIZATION_CONTEXT_CHANGED","资料披露范围已变化,请重新确认");if(y.scope==="session"){if(y.decision!=="allow")throw p("INVALID_PARAMS","本次许可只支持允许");return i.set(S,Object.freeze({revision:w,consentFingerprint:b})),N(y.userId,I,{egressTier:y.egressTier})}const U=w+1,D=y.decision==="allow"?{decision:"allow",revision:U,consentFingerprint:b}:{decision:y.decision,revision:U},M={schema_version:1,records:{...I.records,[y.resource]:D}};y.decision!=="allow"&&(o.add(S),i.delete(S));try{await m(y.userId,M,T)}catch(O){throw jc(O)}return o.delete(S),i.delete(S),N(y.userId,M,{egressTier:y.egressTier})};return y.scope==="session"?j():c(y.userId,j)},async revokeSession(y,T){a(),y.resource!==void 0&&R(y.resource);for(const I of[...i.keys()])I.startsWith(`${y.userId}\0`)&&(y.resource===void 0||I===f(y.userId,y.resource))&&i.delete(I);const j=await h(y.userId,T);return N(y.userId,j,{})},async reset(y,T){return a(),c(y.userId,async()=>{a();const j=await h(y.userId,T);if(a(),T.signal.aborted)throw p("REQUEST_CANCELLED","许可操作已取消");const I=new Set(t);for(const S of Object.keys(j.records))I.add(S);for(const S of i.keys())S.startsWith(`${y.userId}\0`)&&I.add(S.slice(y.userId.length+1));for(const S of I)o.add(f(y.userId,S));for(const S of[...i.keys()])S.startsWith(`${y.userId}\0`)&&i.delete(S);const _={...j.records};for(const S of I)_[S]={decision:"ask",revision:(_[S]?.revision??0)+1};const w={schema_version:1,records:_};try{await m(y.userId,w,T)}catch(S){throw jc(S)}for(const S of I)o.delete(f(y.userId,S));return N(y.userId,w,{})})},dispose(){s||(s=!0,i.clear(),o.clear())}}}const _i={auth:"none",channel:"api",method:"POST",bodyEncoding:"form",failurePresentation:"none",parse(e){return Te(e,"游戏资料接口响应异常")}};function Ai(e){return{runtime_auth_context_token:e.runtime_auth_context_token,resource:e.resource,disclosure_revision:e.disclosure_revision}}const nA={..._i,id:"heybox.user_miniprogram.runtime.user_game_data.query.post",path:"/user_miniprogram/runtime/user_game_data/query",body(e){return{...Ai(e),operation:e.operation,schema_version:e.schema_version,...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit}}}},iA={..._i,id:"heybox.user_miniprogram.runtime.user_game_data.sync.post",path:"/user_miniprogram/runtime/user_game_data/sync",body:Ai},zc={..._i,id:"heybox.user_miniprogram.runtime.user_game_data.sync_status.post",path:"/user_miniprogram/runtime/user_game_data/sync_status",body(e){return{...Ai(e),task_id:e.task_id}}},oA={..._i,id:"heybox.user_miniprogram.runtime.user_game_data.file.post",path:"/user_miniprogram/runtime/user_game_data/file",body(e){return{...Ai(e),save_id:e.save_id,file_id:e.file_id}}};function sA(e){const t=Dl(e.storage),r=e.fileDownloads??(e.files&&e.transfer?Os({files:e.files,transfer:e.transfer,registry:e.registry,signal:e.signal}):void 0),n=new Set,i=d=>{if(e.signal.aborted||d.signal.aborted)throw ee("REQUEST_CANCELLED","资料请求已取消")};async function o(d,u){if(i(u),!e.authorizationContext)throw ee("REQUEST_UNSUPPORTED","宿主缺少受信运行上下文");const l=await e.authorizationContext.get(u);if(!l.token||!Number.isFinite(l.expiresAt)||l.expiresAt<=Date.now())throw ee("UNAUTHORIZED","受信运行上下文已过期");return{runtime_auth_context_token:l.token,resource:d.key,disclosure_revision:d.disclosureRevision}}async function s(d,u,l){i(l);const f=await Ei({network:e.network,operationContext:l,subject:"游戏资料",assertUsable:()=>i(l),requestPolicyEnabled:e.requestPolicyEnabled,...e.requestGate?{gate:{capability:"userGameData",gate:e.requestGate}}:{}},d,u),h=it(f,"user.data","游戏资料");if(!we(h))throw ee("INVALID_RESPONSE","游戏资料响应无效");return i(l),h}const a=d=>{const u=hi(d);if(!u)throw ee("REQUEST_UNSUPPORTED","未开放资料资源");return u};async function c(d){n.delete(d),await r?.release(d)}return{releaseFile:c,invalidate(){for(const d of n)r?.release(d);n.clear()},async query(d,u){const l=a(d.resource),f=l.queries[d.operation];if(!f)throw ee("REQUEST_UNSUPPORTED","未开放资料操作");const h=await s(nA,{...await o(l,u),operation:d.operation,schema_version:f.version,...d.cursor===void 0?{}:{cursor:d.cursor},...d.limit===void 0?{}:{limit:d.limit}},u);if(h.resource!==d.resource||h.operation!==d.operation||h.schema_version!==f.version||h.disclosure_revision!==l.disclosureRevision)throw ee("INVALID_RESPONSE","游戏资料合同不匹配");if(h.status==="ready"){if(!Qg(f.schema,h.data))throw ee("INVALID_RESPONSE","游戏资料正文不匹配公开 schema");return{status:"ready",data:h.data,meta:{},schemaVersion:f.version}}if(h.status==="empty"&&(h.reason==="no_data"||h.reason==="not_ready")&&typeof h.message=="string")return{status:"empty",reason:h.reason,message:h.message,meta:{},schemaVersion:f.version};throw ee("INVALID_RESPONSE","游戏资料状态无效")},async sync(d,u,l){const f=a(d.resource);if(!f.operations.includes("sync"))throw ee("REQUEST_UNSUPPORTED","资源不支持同步");const h=await o(f,u),m=new AbortController,E=()=>m.abort();u.signal.addEventListener("abort",E,{once:!0}),u.signal.aborted&&E();let N=!1;const A=setTimeout(()=>{N=!0,E()},5*6e4),R={...u,signal:m.signal},y={...l,gameId:f.game,resource:d.resource};let T;try{const j=await t.run(y,R,async()=>{const _=await t.get(y,R);if(_)return T=_,{id:_,status:await s(zc,{...await o(f,R),task_id:_},R)};const w=await s(iA,h,R);if(typeof w.task_id!="string"||!w.task_id||w.task_id.length>128)throw ee("INVALID_RESPONSE","同步任务缺失");return await t.set(y,w.task_id,R),{id:w.task_id,status:w}});let I=j.status;for(T=j.id;;){if(i(R),I.state==="succeeded")return await t.remove(y,T,R),{status:"succeeded"};if(I.state==="failed")throw await t.remove(y,T,R),ee(typeof I.error_code=="string"?I.error_code:"SYNC_FAILED","存档同步失败");if(I.state!=="syncing"&&I.state!=="uploading")throw ee("INVALID_RESPONSE","同步状态无效");if(await aA(R.signal),I=await s(zc,{...await o(f,R),task_id:T},R),I.task_id!==T)throw ee("INVALID_RESPONSE","同步任务不匹配")}}catch(j){throw T&&we(j)&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED"].includes(String(j.code))&&await t.remove(y,T,R),N?ee("REQUEST_TIMEOUT","等待同步超时,后台任务可能仍在执行"):j}finally{clearTimeout(A),u.signal.removeEventListener("abort",E)}},async file(d,u,l){const f=a(d.resource);if(!f.operations.includes("file")||!r)throw ee("REQUEST_UNSUPPORTED","宿主不支持资料文件下载");const h=async E=>{await l(E);const N=await s(oA,{...await o(f,E),save_id:d.saveId,file_id:d.fileId},E);if(!we(N.file)||N.file.file_id!==d.fileId)throw ee("INVALID_RESPONSE","文件标识不匹配");return await l(E),N},m=await r.download(await h(u),async E=>{await h(E)},u);try{return i(u),await l(u),i(u),n.add(m),m}catch(E){throw await c(m),E}}}}function aA(e){return new Promise((t,r)=>{const n=()=>{clearTimeout(i),e.removeEventListener("abort",n),r(ee("REQUEST_CANCELLED","已停止等待同步"))},i=setTimeout(()=>{e.removeEventListener("abort",n),t()},2e3);e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})}const $r=["event_id","miniProgramId","environment","host_platform","host_version","sdk_version","runtime_version","egress_tier","resource","call_id","flow_id"],cA=Object.freeze({user_game_data_permission_show:new Set([...$r,"entry","reason"]),user_game_data_permission_result:new Set([...$r,"choice","apply_result"]),user_game_data_permission_manage:new Set([...$r,"operation","apply_result","succeeded_count","failed_count"]),user_game_data_action:new Set([...$r,"stage","action_type","outcome","duration_ms"]),user_game_data_access_result:new Set([...$r,"api","trigger","status","error_code","failure_stage","duration_ms","cache_hit","sample_rate","overview_status_counts"])}),Bc=10*6e4,dA=256;function uA(e){const t=e.now??Date.now,r=e.random??Math.random,n=e.createId??hA,i=fA(e.sampleRate),o=new Map,s=new Map,a=new Map;let c=!1,d=0,u=0,l=0,f=0;const h={get emitted(){return d},get failed(){return u},get skipped(){return l},get deduplicated(){return f}};function m(I){return`${I}${n()}`}function E(){const I=t();for(const[_,w]of o)I-w.createdAt<=Bc||(o.delete(_),s.get(w.key)===_&&s.delete(w.key));for(const[_,w]of a){if(I-w<=Bc&&a.size<=dA)break;a.delete(_)}}function N(I){const _=o.get(I);_!==void 0&&(o.delete(I),s.get(_.key)===I&&s.delete(_.key))}function A(I){N(I),a.delete(I),a.set(I,t())}function R(I,_){const w=cA[I],S={};for(const[b,U]of Object.entries(_))U===void 0||!w.has(b)||(S[b]=U);return Object.freeze(S)}function y(I){const _={event_id:m("evt_"),miniProgramId:dr(()=>e.resolveMiniProgramId())??"unknown",environment:lA(dr(()=>e.resolveEnvironment())),host_platform:dr(e.resolveHostPlatform)??"unknown",host_version:dr(e.resolveHostVersion)??"unknown",sdk_version:dr(e.resolveSdkVersion)??"unknown",runtime_version:dr(e.resolveRuntimeVersion)??"unknown",egress_tier:mA(e)};return I.resource!==void 0&&(_.resource=I.resource),I.callId!==void 0&&(_.call_id=I.callId),I.flowId!==void 0&&(_.flow_id=I.flowId),_}function T(I,_){if(c){l+=1;return}try{if(e.sink===void 0){l+=1;return}e.sink.postEvent(I,R(I,_)),d+=1}catch{u+=1}}function j(I,_){if(I===void 0)return!1;const w=o.get(I);return w===void 0?!1:_==="start"&&w.started||_==="shown"&&w.shown||_==="decided"&&w.decided?!0:(_==="start"&&(w.started=!0),_==="shown"&&(w.shown=!0),_==="decided"&&(w.decided=!0),!1)}return{diagnostics:h,createCallId(){return m("call_")},beginFlow(I){E();const _=`${I.resource??""}\0${I.actionType}`,w=s.get(_);if(w!==void 0&&o.has(w))return w;const S=m("flow_");return o.set(S,{key:_,createdAt:t(),started:!1,shown:!1,decided:!1}),s.set(_,S),S},permissionShow(I){if(j(I.flowId,"shown")){f+=1;return}T("user_game_data_permission_show",{...y(I),entry:I.entry,reason:I.reason})},permissionResult(I){if(j(I.flowId,"decided")){f+=1;return}T("user_game_data_permission_result",{...y(I),choice:I.choice,apply_result:I.applyResult})},permissionManage(I){T("user_game_data_permission_manage",{...y(I),operation:I.operation,apply_result:I.applyResult,...I.succeededCount===void 0?{}:{succeeded_count:I.succeededCount},...I.failedCount===void 0?{}:{failed_count:I.failedCount}})},action(I){if(I.stage==="start"&&j(I.flowId,"start")){f+=1;return}if(I.stage==="finish"){if(I.flowId!==void 0&&a.has(I.flowId)){f+=1;return}I.flowId!==void 0&&A(I.flowId)}T("user_game_data_action",{...y(I),stage:I.stage,action_type:I.actionType,...I.outcome===void 0?{}:{outcome:I.outcome},...I.durationMs===void 0?{}:{duration_ms:Math.max(0,Math.round(I.durationMs))}})},access(I){if(i<=0){l+=1;return}if(i<1&&r()>=i){l+=1;return}T("user_game_data_access_result",{...y(I),api:I.api,trigger:I.trigger,status:I.status,duration_ms:Math.max(0,Math.round(I.durationMs)),sample_rate:i,...I.errorCode===void 0?{}:{error_code:I.errorCode},...I.failureStage===void 0?{}:{failure_stage:I.failureStage},...I.cacheHit===void 0?{}:{cache_hit:I.cacheHit},...I.overviewStatusCounts===void 0?{}:{overview_status_counts:I.overviewStatusCounts}})},dispose(){c||(c=!0,o.clear(),s.clear(),a.clear())}}}function lA(e){switch(e){case"public":case"production":return"production";case"preview":return"preview";case"development":case"dev":case"local":return"development";case"mock":return"mock";default:return"unknown"}}function fA(e){return e===void 0||!Number.isFinite(e)?1:e<=0?0:e>=1?1:e}function dr(e){if(e!==void 0)try{const t=e();if(typeof t!="string")return;const r=t.trim();return r===""?void 0:r}catch{return}}function mA(e){try{return e.resolveEgressTier()==="upload"?"upload":"no_network"}catch{return"no_network"}}function hA(){const e=globalThis.crypto;if(typeof e?.randomUUID=="function")return e.randomUUID();const t=new Uint8Array(16);if(typeof globalThis.crypto?.getRandomValues=="function")globalThis.crypto.getRandomValues(t);else for(let r=0;r<t.length;r+=1)t[r]=Math.floor(Math.random()*256);return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function ft(e){const t=Ve(e);return t.valid?t.permissions.network?.status==="enabled"||t.permissions.companion?.status==="enabled"?"upload":"no_network":"upload"}function gA(e){let t=!1,r=0,n,i=!1;const o=new Map,s=new Map,a=new Set,c=new Map,d=e.now??Date.now,u=g=>A()[g]?.purpose??"",l=g=>{const C=hi(g);if(!C)throw p("REQUEST_UNSUPPORTED","未开放的资料资源");return C},f=g=>Su(g,l(g).disclosureRevision,ft(e.runtimePermissions),u(g)),h=()=>rA({storage:e.storage,resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,revisionOf:g=>l(g).disclosureRevision,purposeOf:u,...e.hash?{hash:e.hash}:{}});let m=h();const E=uA({resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,resolveEgressTier:()=>ft(e.runtimePermissions),...e.telemetry??{}}),N=sA({network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,storage:e.storage,registry:e.fileRegistry,fileDownloads:e.fileDownloads,requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled,signal:e.operationContext.signal});function A(){const g=Ve(e.runtimePermissions),C=g.valid?g.permissions.user_game_data:void 0;return C?.status==="enabled"?tn(C.config.resources):{}}function R(g){if(t||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序已关闭");if(g?.signal.aborted)throw p("REQUEST_CANCELLED","资料请求已取消")}function y(g){for(const[C,B]of o)B!==void 0&&(g===void 0||B===g)&&C.abort()}function T(g){for(const[C,B]of s)(g===void 0||C===g)&&(B.abort(),s.delete(C))}function j(){r++,T();for(const g of o.keys())g.abort();for(const g of a)e.fileRegistry.revokeFiles([g]);a.clear(),c.clear(),N.invalidate()}const I=wi(e.account,g=>{if(i&&n===g)return;const C=n;i=!0,n=g,C!==void 0&&(j(),m.dispose(),m=h())}),_=()=>j();e.operationContext.signal.addEventListener("abort",_,{once:!0});async function w(g,C){R(g);const B=new AbortController,Q=()=>B.abort();o.set(B,void 0),g.signal.addEventListener("abort",Q,{once:!0}),g.signal.aborted&&Q();const X={...e.operationContext,...g,signal:B.signal};try{const ne=await C(X);return R(X),ne}catch(ne){throw re(ne)&&ne.name==="AbortError"?p("REQUEST_CANCELLED","资料操作已取消"):ne}finally{g.signal.removeEventListener("abort",Q),o.delete(B)}}function S(g){const C=l(g);if(!u(C.key))throw p("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明这项游戏资料",{resource:C.key});return C}async function b(g){R(g);const C=await e.account.getCurrentUserId(g);if(R(g),!i)i=!0,n=C;else if(n!==C){const B=n;n=C,B!==void 0&&(j(),m.dispose(),m=h(),R(g))}return C}function U(g,C){const B={login_required:"请先登录小黑盒",permission_required:"尚未允许读取这项资料",permission_denied:"已拒绝读取这项资料",source_not_linked:"请先在小黑盒关联对应游戏账号",source_login_required:"请先在小黑盒更新游戏来源登录"},Q=C==="login_required"?{type:"user_login",label:"登录并授权"}:C==="permission_required"?{type:"permission",label:"允许读取"}:C==="permission_denied"&&e.presentation?.openDataPermissions?{type:"manage",label:"管理数据权限"}:void 0;return{status:"blocked",resource:g,reason:C,message:B[C],...Q?{interaction:Q}:{}}}async function D(g,C){S(g);const B=await b(C);if(!B)return U(g,"login_required");const Q=await m.evaluate(B,{resource:g,egressTier:ft(e.runtimePermissions)},C);return R(C),Q.status==="allowed"?{userId:B}:U(g,Q.status==="denied"?"permission_denied":"permission_required")}async function M(g,C,B,Q,X){if(R(X),r!==B||await b(X)!==C||f(g)!==Q)throw p("AUTHORIZATION_CONTEXT_CHANGED","账号或资料范围已变化");return D(g,X)}function O(g,C){if(!re(g)||typeof g.resource!="string")throw p("INVALID_PARAMS","资料请求无效");if(!bt(g.resource))throw p("REQUEST_UNSUPPORTED","当前宿主尚未开放该资料资源");const B=C==="query"?["resource","operation","schemaVersion","cursor","limit"]:["resource","saveId","fileId"];if(Object.keys(g).some(X=>!B.includes(X)))throw p("INVALID_PARAMS","资料请求包含未知参数");const Q=S(g.resource);if(C==="query"){if(g.operation!=="get"&&g.operation!=="list")throw p("INVALID_PARAMS","资料查询操作无效");const X=Q.queries[g.operation];if(!X)throw p("REQUEST_UNSUPPORTED","资源不支持该查询");if(g.schemaVersion!==X.version)throw p("REQUEST_UNSUPPORTED","SDK 与宿主正文合同版本不匹配");if(g.operation!=="list"&&(g.cursor!==void 0||g.limit!==void 0))throw p("INVALID_PARAMS","单份查询不能分页");if(g.cursor!==void 0&&(typeof g.cursor!="string"||!g.cursor||g.cursor.length>32768))throw p("INVALID_PARAMS","分页游标无效");if(!X.page&&(g.cursor!==void 0||g.limit!==void 0))throw p("INVALID_PARAMS","该列表不支持分页");if(g.limit!==void 0&&(typeof g.limit!="number"||!Number.isInteger(g.limit)||g.limit<1||g.limit>(X.page?.maxSize??100)))throw p("INVALID_PARAMS","分页数量无效")}else if(!Q.operations.includes(C))throw p("REQUEST_UNSUPPORTED","资源不支持该操作");if(C==="file"&&(typeof g.saveId!="string"||!g.saveId||typeof g.fileId!="string"||!g.fileId))throw p("INVALID_PARAMS","资料文件标识无效");return C==="query"?{resource:g.resource,operation:g.operation,schemaVersion:g.schemaVersion,...g.cursor===void 0?{}:{cursor:g.cursor},...g.limit===void 0?{}:{limit:g.limit}}:{resource:g.resource,saveId:g.saveId,fileId:g.fileId}}async function z(g,C,B,Q){const X=d(),ne=r,ie=f(C.resource);for(const ue of o.keys())ue.signal===B.signal&&o.set(ue,C.resource);try{const ue=await D(C.resource,B);if("status"in ue)return E.access({resource:C.resource,api:g,trigger:"initial",status:"blocked",durationMs:d()-X}),ue;let Ee;try{Ee=await Q()}catch(ge){const ye=re(ge)?ge.code:void 0;if(ye==="USER_DATA_SOURCE_NOT_LINKED"||ye==="USER_DATA_SOURCE_LOGIN_REQUIRED")return E.access({resource:C.resource,api:g,trigger:"initial",status:"blocked",durationMs:d()-X}),U(C.resource,ye==="USER_DATA_SOURCE_NOT_LINKED"?"source_not_linked":"source_login_required");throw ge}const he=await M(C.resource,ue.userId,ne,ie,B);return"status"in he?(E.access({resource:C.resource,api:g,trigger:"initial",status:"blocked",durationMs:d()-X}),he):(E.access({resource:C.resource,api:g,trigger:"initial",status:re(Ee)&&Ee.status==="empty"?"empty":g===Ri?"succeeded":"ready",durationMs:d()-X}),Ee)}catch(ue){throw E.access({resource:C.resource,api:g,trigger:"initial",status:"error",durationMs:d()-X,errorCode:re(ue)?String(ue.code):"REQUEST_FAILED"}),ue}}async function x(g){const C=await b(g);if(!C)throw p("UNAUTHORIZED","请先登录小黑盒");return m.read(C,g,{declared:Object.keys(A()),egressTier:ft(e.runtimePermissions)})}async function L(g,C){const B=S(g);let Q=await b(C);if(Q||(await e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:C.signal}),Q=await b(C)),!Q)return{status:"cancelled"};let X=await m.evaluate(Q,{resource:g,egressTier:ft(e.runtimePermissions)},C);if(X.status==="allowed")return{status:"allowed"};if(X.status==="denied"){if(e.presentation?.openDataPermissions){const Me=r,Pe=f(g),je=await e.presentation.openDataPermissions({resource:g,miniProgramName:e.miniProgramPresentation?.name,signal:C.signal});if(!("status"in await M(g,Q,Me,Pe,C)))return{status:"allowed"};if(!je)return{status:"cancelled"}}return X=await m.evaluate(Q,{resource:g,egressTier:ft(e.runtimePermissions)},C),{status:X.status==="allowed"?"allowed":"denied"}}if(!e.presentation?.confirmDataPermission)throw p("REQUEST_UNSUPPORTED","当前宿主不支持资料许可弹窗");T(g);const ne=new AbortController;s.set(g,ne);const ie=()=>ne.abort();C.signal.addEventListener("abort",ie,{once:!0}),C.signal.aborted&&ie();const ue={...C,signal:ne.signal},Ee=r,he=f(g),ge=m,ye=E.beginFlow({resource:g,actionType:"permission"});let Oe="error";try{const Pe=(await ge.read(Q,ue,{egressTier:ft(e.runtimePermissions)})).resources.find(Ut=>Ut.resource===g);E.action({resource:g,flowId:ye,stage:"start",actionType:"permission"}),E.permissionShow({resource:g,flowId:ye,entry:"other",reason:Pe?.decision==="allow"?"scope_changed":"first"});const je=await fe(()=>e.presentation.confirmDataPermission({miniProgramName:e.miniProgramPresentation?.name,resource:g,scopeText:`此黑盒账号关联的${B.name}${B.operations.includes("sync")?`。${xm}`:""}`,purposeText:u(g),egress:ft(e.runtimePermissions),canPersist:ge.canPersist,signal:ne.signal}),ne.signal);if(R(ue),r!==Ee||await b(ue)!==Q||f(g)!==he)throw p("AUTHORIZATION_CONTEXT_CHANGED","资料许可范围已变化");return je.decision==="cancelled"?(Oe="cancelled",E.permissionResult({resource:g,flowId:ye,choice:"cancel",applyResult:"cancelled"}),{status:"cancelled"}):(await ge.decide({userId:Q,resource:g,decision:je.decision==="deny"?"deny":"allow",scope:je.decision==="session"?"session":"persistent",egressTier:ft(e.runtimePermissions),expectedRevision:Pe?.revision??0,expectedFingerprint:Pe?.scopeFingerprint},ue),je.decision==="deny"&&y(g),Oe=je.decision==="deny"?"unresolved":"resolved",E.permissionResult({resource:g,flowId:ye,choice:je.decision,applyResult:"applied"}),{status:je.decision==="deny"?"denied":"allowed"})}catch(Me){throw Oe=ue.signal.aborted?"cancelled":"error",E.permissionResult({resource:g,flowId:ye,choice:"cancel",applyResult:ue.signal.aborted?"cancelled":"error"}),Me}finally{E.action({resource:g,flowId:ye,stage:"finish",actionType:"permission",outcome:Oe}),C.signal.removeEventListener("abort",ie),s.get(g)===ne&&s.delete(g)}}async function k(g,C,B,Q,X,ne){C==="allow"?S(g):l(g);const ie=await b(Q);if(!ie)throw p("UNAUTHORIZED","请先登录小黑盒");try{await m.decide({userId:ie,resource:g,decision:C,scope:B,expectedRevision:X,expectedFingerprint:ne,egressTier:ft(e.runtimePermissions)},Q)}catch(ue){throw re(ue)&&ue.code==="USER_DATA_PERMISSION_SAVE_FAILED"&&y(g),ue}return T(g),C!=="allow"&&y(g),x(Q)}async function H(g,C,B){try{const Q=await B();return E.permissionManage({operation:g,resource:C,applyResult:"applied"}),Q}catch(Q){throw E.permissionManage({operation:g,resource:C,applyResult:re(Q)&&Q.code==="USER_DATA_PERMISSION_SAVE_FAILED"?"save_failed":"error"}),Q}}async function F(g,C){T(g),y(g);const B=await b(C);if(!B)throw p("UNAUTHORIZED","请先登录小黑盒");return H("revoke",g,async()=>(await m.revokeSession({userId:B,resource:g},C),x(C)))}function G(){let g;const C=B=>w(e.operationContext,async Q=>{const X=await b(Q);if(!X)throw p("UNAUTHORIZED","请先登录小黑盒");if(g&&(g.userId!==X||g.generation!==r))throw p("AUTHORIZATION_CONTEXT_CHANGED","管理页面所属账号已变化,请重新打开");return g??={userId:X,generation:r},B(Q)});return{getSnapshot:()=>C(x),setDecision:B=>C(Q=>H("modify",B.resource,()=>k(B.resource,B.decision,B.scope,Q,B.expectedRevision,B.expectedFingerprint))),revokeSession:B=>C(Q=>F(B?.resource,Q)),resetAll:()=>C(async B=>{T(),y();const Q=await b(B);return H("reset",void 0,async()=>(await m.reset({userId:Q},B),x(B)))})}}return{handlers:{[Cm]:async(g,C)=>w(C,async B=>{if(g!==void 0&&(!re(g)||Object.keys(g).some(ne=>ne!=="game")||g.game!==void 0&&typeof g.game!="string"))throw p("INVALID_PARAMS","概览参数无效");if(re(g)&&typeof g.game=="string"&&!na(g.game))throw p("REQUEST_UNSUPPORTED","当前宿主尚未开放该游戏");const Q=Object.keys(A()),X=re(g)?g.game:void 0;return km.filter(ne=>X===void 0||ne===X).map(ne=>({game:ne,name:Lm[ne],resources:Cn.filter(ie=>ie.game===ne&&Q.includes(ie.key)).map(ie=>({resource:ie.key,name:ie.name,status:"not_checked",statusText:"尚未检查"}))})).filter(ne=>ne.resources.length>0)}),[ra]:async(g,C)=>w(C,B=>{const Q=O(g,"query");return z(ra,Q,B,()=>N.query(Q,B))}),[Ri]:async(g,C)=>w(C,async B=>{if(!re(g)||Object.keys(g).length!==1||typeof g.game!="string"||!na(g.game))throw p("INVALID_PARAMS","同步需要指定已开放的游戏");const Q={game:g.game};if(!Cn.some(Ee=>Ee.game===Q.game&&Ee.sync))throw p("REQUEST_UNSUPPORTED","该游戏不支持存档同步");const X=Cn.filter(Ee=>Ee.game===Q.game&&Ee.sync&&u(Ee.key));if(X.length===0)throw p("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明可同步的资料");let ne,ie;for(const Ee of X){const he=await D(Ee.key,B);if(!("status"in he)){ne=Ee.key;break}(!ie||ie.reason==="permission_denied")&&(ie=he)}if(!ne)return ie;const ue={resource:ne};return z(Ri,ue,B,async()=>{const Ee=await b(B),he=`${Ee}\0${ue.resource}`;let ge=c.get(he);if(!ge){const ye=new AbortController;o.set(ye,ue.resource);const Oe={controller:ye,waiters:0,settled:!1,promise:Promise.resolve(void 0)};Oe.promise=N.sync(ue,{...e.operationContext,signal:ye.signal},{userId:Ee,miniProgramId:e.identity.get()?.miniProgramId??""}).finally(()=>{Oe.settled=!0,o.delete(ye),c.get(he)===Oe&&c.delete(he)}),Oe.promise.catch(()=>{}),c.set(he,Oe),ge=Oe}ge.waiters++;try{return await fe(()=>ge.promise,B.signal)}finally{ge.waiters--,ge.waiters===0&&!ge.settled&&ge.controller.abort()}})}),[ta]:async(g,C)=>w(C,async B=>{const Q=O(g,"file"),X=await b(B),ne=r,ie=f(Q.resource),ue=async he=>{try{const ge=await M(Q.resource,X,ne,ie,he);if("status"in ge)throw p("FILE_ACCESS_REVOKED","文件授权已撤销",{reason:ge.reason})}catch(ge){throw re(ge)&&["AUTHORIZATION_CONTEXT_CHANGED","USER_DATA_RESOURCE_NOT_DECLARED"].includes(String(ge.code))?p("FILE_ACCESS_REVOKED","文件授权已失效",{causeCode:ge.code}):ge}};let Ee;try{const he=await z(ta,Q,B,async()=>(Ee=await N.file(Q,B,ue),{handle:Ee}));if(re(he)&&he.status==="blocked"){const Me=String(he.reason);throw p(Me==="source_not_linked"?"USER_DATA_SOURCE_NOT_LINKED":Me==="source_login_required"?"USER_DATA_SOURCE_LOGIN_REQUIRED":Me==="login_required"?"UNAUTHORIZED":"PERMISSION_DENIED",String(he.message),{reason:Me})}const ge=he.handle,ye={...ge,read:async Me=>{await ue(Me);const Pe=await ge.read(Me);try{return await ue(Me),Pe}catch(je){throw Pe.fill(0),je}},stat:async Me=>{await ue(Me);const Pe=await ge.stat(Me);return await ue(Me),Pe}},Oe=e.fileRegistry.registerFile(ye,"download","read");return"handleId"in Oe.ref&&a.add(Oe.ref.handleId),Oe}catch(he){throw Ee&&await N.releaseFile(Ee),he}}),[Rm]:async(g,C)=>{if(!C.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","许可操作需要点击");return w(C,B=>{if(!re(g)||Object.keys(g).length!==1||typeof g.resource!="string"||!bt(g.resource))throw p("INVALID_PARAMS","许可资源无效");return L(g.resource,B)})},[Pm]:async(g,C)=>w(C,x),[vm]:async(g,C)=>{if(!C.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","修改许可需要点击");if(!re(g)||typeof g.resource!="string"||!bt(g.resource)||g.decision!=="deny"||g.scope!=="persistent"||Object.keys(g).some(B=>!["resource","decision","scope"].includes(B)))throw p("INVALID_PARAMS","允许许可只能由可信弹窗确认");return w(C,B=>k(g.resource,g.decision,"persistent",B))},[Om]:async(g,C)=>{if(!C.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","管理资料许可需要点击");if(!e.presentation?.openDataPermissions)throw p("REQUEST_UNSUPPORTED","宿主未提供资料管理界面");if(g!==void 0&&(!re(g)||Object.keys(g).some(B=>B!=="resource")||g.resource!==void 0&&(typeof g.resource!="string"||!bt(g.resource))))throw p("INVALID_PARAMS","管理资源无效");return w(C,async B=>(await e.presentation.openDataPermissions({resource:re(g)?g.resource:void 0,miniProgramName:e.miniProgramPresentation?.name,signal:B.signal}),x(B)))},[Tm]:async(g,C)=>{if(!C.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","撤销许可需要点击");if(g!==void 0&&(!re(g)||Object.keys(g).some(B=>B!=="resource")||g.resource!==void 0&&(typeof g.resource!="string"||!bt(g.resource))))throw p("INVALID_PARAMS","撤销资源无效");return w(C,B=>F(re(g)?g.resource:void 0,B))}},get permissionBridge(){return G()},diagnostics:{telemetry:E.diagnostics},dispose(){t||(t=!0,j(),I(),e.operationContext.signal.removeEventListener("abort",_),m.dispose(),E.dispose())}}}function Hc(e){throw{code:"INVALID_PARAMS",message:e}}function Vr(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Jl(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Sn(e,t,r){return Math.min(Jl(e,t),r)}async function pA(e){try{return Jl(await e.getNavigationBarHeight(),0)}catch{return 0}}function yA(e,t,r,n){const i=Sn(e.safeArea?.left,0,t),o=Math.max(i,Sn(e.safeArea?.right,t,t)),s=Sn(e.safeArea?.top,n,r),a=Math.max(s,Sn(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Fc(e){const t=e.getViewportMetrics(),r=Vr(t.windowWidth,0),n=Vr(t.windowHeight,0),i=await pA(e);return{pixelRatio:Vr(t.pixelRatio,1),screenWidth:Vr(t.screenWidth,r),screenHeight:Vr(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:yA(t,r,n,i),screenTop:i}}function EA(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 l=++i;Fc(r.presentation).then(f=>{if(n||r.operationContext.signal.aborted||l!==i)return;const h=JSON.stringify(f);h!==o&&(o=h,r.onViewportChange?.(f))}).catch(()=>{})},c=TI({...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:{[Kn]:async(l,f)=>c.apply(l,f?.signal),[jm]:async()=>(pe(r.operationContext.signal),Fc(r.presentation)),[Um]:async l=>{if(pe(r.operationContext.signal),typeof l!="object"||l===null||Array.isArray(l))return Hc("viewport.setNavigationBarStyle 参数必须是对象");const f=l.foregroundStyle;if(f!=="light"&&f!=="dark")return Hc("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await fe(()=>r.presentation.setNavigationBarStyle(f,e.operationContext),r.operationContext.signal)}},runDisplayRequest:c.runDisplayRequest,applyOrientation:(l,f)=>c.apply({orientation:l.mode,fullscreen:l.hideCapsule},f),notifyChange:()=>{o=void 0,a()},dispose:d}}function wA(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw Ie("INVALID_PARAMS","工作区卡片刷新参数必须是对象");const t=e;if(Object.keys(t).some(i=>i!=="gameAppId"&&i!=="cardIds"))throw Ie("INVALID_PARAMS","工作区卡片刷新包含未知参数");const{gameAppId:r,cardIds:n}=t;if(r!==void 0&&(typeof r!="string"||!/^[1-9][0-9]{0,9}$/.test(r)||Number(r)>2147483647))throw Ie("INVALID_PARAMS","工作区卡片游戏编号无效");if(n!==void 0&&(!Array.isArray(n)||n.length>3||n.some(i=>typeof i!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(i))||new Set(n).size!==n.length))throw Ie("INVALID_PARAMS","工作区卡片编号无效");return{...r===void 0?{}:{gameAppId:r},...n===void 0?{}:{cardIds:[...n]}}}function IA(e,t){return{[zm]:async(r,n)=>{const i=be(t,n.signal,n.requestId);if(pe(i.signal),!e)throw Ie("CAPABILITY_UNAVAILABLE","当前 Host 不支持工作区卡片");const o=wA(r),s=await fe(()=>e.requestRefresh(o,i),i.signal);if(!s||typeof s!="object"||Array.isArray(s)||Object.keys(s).some(a=>a!=="scheduled")||!Number.isSafeInteger(s.scheduled)||s.scheduled<0)throw Ie("HOST_INVALID_RESPONSE","工作区卡片刷新回执无效");return{scheduled:s.scheduled}}}}const _A=new Map(Rt.map(e=>[e.method,e]));function Wi(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function AA(e){const t=Wu(e);return r=>t(r.requirement,r.method)}function DA(e,t,r,n){let i;try{i=Promise.resolve(e(t,r))}catch(o){return n.aborted?Promise.resolve({status:"dropped"}):Promise.reject(o)}return n.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((o,s)=>{let a=!1;const c=u=>{a||(a=!0,n.removeEventListener("abort",d),u())},d=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",d,{once:!0}),i.then(u=>c(()=>o({status:"handled",value:u})),u=>c(()=>s(u)))})}function NA(e){const t=AA(e.runtimePermissions),r=Ve(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??MA,c=e.onTrace?a():0,d=e.onTrace?Date.now():0,u=e.onTrace?s.requestId??`runtime_${++n}`:"";e.onTrace&&Zi(e.onTrace,{callId:u,method:i,startedAt:d,outcome:"started"},()=>c,c);try{if(e.terminalSignal.aborted)throw Wi("RUNTIME_DESTROYED","小程序 Runtime 已终止");nu(i,e.effectiveCapabilities);const l=_A.get(i);if(!l)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const f=t(l),h=!f.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,o)===!0,m=!f.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,o)===!0,E=!f.allowed&&r.valid&&r.permissions.user_game_data?.status==="enabled"&&e.allowsUserGameDataFileAccess?.(i,o)===!0;if(!f.allowed&&!h&&!m&&!E)throw Wi(f.code,f.message,f.data);const N=e.handlers[i];if(!N)throw new Error(`Capability method ${i} 缺少 handler`);const A=async T=>{for(const j of e.policies??[]){const I=await j.evaluate({method:i,payload:o,capability:l});if(e.terminalSignal.aborted||T.aborted)throw Vc();if(!I.allowed)throw Wi(I.code,I.message,I.data)}if(e.terminalSignal.aborted||T.aborted)throw Vc()},y=await DA(async()=>{if(i===Kn){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,A)}return await A(e.terminalSignal),N(o,s)},void 0,s,e.terminalSignal);return e.onTrace&&Zi(e.onTrace,$c(u,i,o,d,y),a,c),y}catch(l){throw e.onTrace&&Zi(e.onTrace,$c(u,i,o,d,{status:"error",error:l}),a,c),l}}}}function MA(){return typeof performance>"u"?Date.now():performance.now()}function Zi(e,t,r,n){if(!e)return;const i=r()-n,o=Date.now();try{e({...t,phase:"host",timestamp:o,durationMs:Math.max(0,Number.isFinite(i)?i:0)})}catch{}}function $c(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:bA(i.error)}:{},...SA(t,r,i)}}function bA(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function SA(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"&&Ko(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 Ko(e){return typeof e=="object"&&e!==null}function Vc(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function TA(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=Wy(e.requestPolicy);let n;if(e.files)try{n=zy(e.files,t)}catch{}const i=ol({store:n}),o=e.onRequestPolicyReport??(r.debugReport?OA:void 0),s=r.enabled?Gy({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new bs(e.files,e.miniProgramDetail),c=Lw({registry:a,picker:e.picker,operationContext:t}),d=_E({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode,authorizationContext:e.authorizationContext,identityTtlMs:r.identityTtlMs,requestGate:s,requestPolicyEnabled:r.enabled});let u,l,f,h,m,E,N=()=>{},A=()=>{};try{u=EA({operationContext:t,presentation:e.hostPresentation,onDisplayChange:M=>e.eventSink.postEvent("display_change",M),onViewportChange:M=>e.eventSink.postEvent("viewport_change",M)}),f=V_({authPresentation:e.authPresentation,authorizationContext:e.authorizationContext,account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:d,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:s,requestPolicyEnabled:r.enabled}),N=d.onEvent((M,O)=>e.eventSink.postEvent(M,O)),A=e.hostCompanion?.onSessionEvent?.(M=>{const O=Ow(M);!e.terminalSignal.aborted&&O&&e.eventSink.postEvent(O.type,O.payload)})??(()=>{}),h=rw({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const R=e.files&&e.transfer?Os({files:e.files,transfer:e.transfer,registry:a,signal:t.signal}):void 0,y=gA({identity:e.identity,account:e.account,storage:e.storage,network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,fileDownloads:R,requestGate:s,requestPolicyEnabled:r.enabled,fileRegistry:a,...e.userDataPresentation===void 0?{}:{presentation:e.userDataPresentation},...e.miniProgramPresentation===void 0?{}:{miniProgramPresentation:e.miniProgramPresentation},runtimePermissions:e.runtimePermissions,environment:e.miniProgramDetail?.releaseChannel,operationContext:t,...e.onUserDataTelemetry===void 0?{}:{telemetry:{sink:{postEvent(M,O){e.onUserDataTelemetry?.({name:M,payload:O})}}}}});E=y,m=hw({identity:e.identity,storage:e.storage,account:e.account,presentation:e.hostPresentation,network:e.network,authorization:d,authorizationContext:e.authorizationContext,operationContext:t,files:e.files,transfer:e.transfer,fileRegistry:a,fileDownloads:R,requestGate:s,requestPolicyEnabled:r.enabled});const T=I_({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});l=iI({registry:a,media:e.media,operationContext:t});const j=[{name:"gameSaves",handlers:Object.fromEntries(Object.entries(m.handlers).map(([M,O])=>[M,async(z,x)=>{const L=e.verifiedSdkVersion,k=L?vs(L,"0.10.0-0"):void 0;if(k===void 0||k>=0)throw p("REQUEST_UNSUPPORTED","当前 SDK 不支持旧游戏存档入口,请使用 user.games.get(...).saves");return O(z,x)}]))},{name:"auth",handlers:OE({authorization:d})},{name:"user",handlers:{...eA({user:f,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...Ry({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:y_({prepareScreenshot:e.prepareScreenshot,prepareLongScreenshot:e.prepareLongScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:u.handlers},{name:"storage",handlers:T.handlers},{name:"network",handlers:UI({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins,networkPolicy:e.networkPolicy})},{name:"workspaceCards",handlers:IA(e.workspaceCards,t)},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"media",handlers:l.handlers},{name:"ui",handlers:M_({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Cw({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:OI({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:M=>u.applyOrientation({mode:"portrait",hideCapsule:!1},M)}:{}})},{name:"cloud",handlers:h.handlers},{name:"userGameData",handlers:E.handlers},{name:"companion",handlers:Nw({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],I=vA(j);let _=!1;const w=()=>{_||(_=!0,e.terminalSignal.removeEventListener("abort",w),u?.dispose(),l?.dispose(),h?.dispose(),m?.dispose(),E?.dispose(),N(),A(),f?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?w():e.terminalSignal.addEventListener("abort",w,{once:!0});const S=new Set(["file.readText","file.readBytes","file.stat"]),b=(M,O)=>S.has(M)&&Ko(O)&&a.isCompanionAttachmentRef(O.target),U=new Set(["file.readText","file.readBytes","file.stat","file.exists"]),D=(M,O)=>U.has(M)&&Ko(O)&&a.isUserDataDownloadRef(O.target);return{get permissionBridge(){return y.permissionBridge},modules:j,handlers:I,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:b,allowsGameSaveAccess:m.allowsRead,allowsUserGameDataFileAccess:D,gameSaveDiagnostics:m.diagnostics,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...T.diagnostics?{storageDiagnostics:T.diagnostics}:{},...e.files?{sandboxDiagnostics:Vw({registry:a,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},dispose:w}}catch(R){throw u?.dispose(),l?.dispose(),h?.dispose(),m?.dispose(),E?.dispose(),N(),A(),f?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),R}}function OA(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function vA(e){const t=new Map(Rt.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=Rt.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Rt.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const PA="heybox-mini-dev:";function Gc(e){try{return RA(new URL(e))}catch{return!1}}function RA(e){return e.protocol===PA}function CA(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||kA(e)}function kA(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 LA=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function xA(e,t){const r=[],n=UA(e.environmentInfo,r),i=Bn(n?.appVersion,"host.appVersion",r),o=zA(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:jA(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:Bn(t.miniProgramId),version:Bn(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function UA(e,t){if(e!=null){if(Xl(e))return e;t.push("environmentInfo")}}function jA(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function zA(e,t){if(e==null)return{name:"unknown",version:null};if(!Xl(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=LA.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:Bn(e.version,"operatingSystem.version",t)}}function Bn(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Xl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const BA="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",HA="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",FA="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",$A="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function VA(e,t,r,n,i="dark"){pe(n);const o=e.defaultView;if(!o||!e.body)throw new Error("截图水印缺少可用的展示窗口");const s=e.createElement("div"),a=i==="light",c=a?"black":"white";s.dataset.miniProgramScreenshotWatermark="",s.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);s.style.cssText=`position:absolute;left:${r.left+o.scrollX}px;top:${r.top+o.scrollY+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const u=e.createElement("div");u.style.cssText=`display:flex;flex-direction:column;align-items:center;width:${r.width/d}px;height:57px;transform:scale(${d});transform-origin:top left;font-family:"PingFang SC",sans-serif;`;const l=e.createElement("div");l.style.cssText="display:flex;align-items:center;max-width:calc(100% - 24px);height:22px;flex-shrink:0;";const f=e.createElement("img");f.src=a?FA:BA,f.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const h=e.createElement("div");h.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${c};border-radius:11px;padding:0 7px 0 6px;`;const m=e.createElement("img");m.src=a?$A:HA,m.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 N=e.createElement("div");N.textContent="小黑盒工坊小程序",N.style.cssText=`margin-top:6px;color:${a?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,h.append(m,E),l.append(f,h),u.append(l,N),s.append(u),e.body.append(s);const A=()=>{s.remove(),n.removeEventListener("abort",A)};n.addEventListener("abort",A,{once:!0});try{return await fe(()=>Promise.all([f.decode(),m.decode()]),n),await fe(()=>new Promise(R=>{let y=o.requestAnimationFrame(()=>{y=o.requestAnimationFrame(()=>{n.removeEventListener("abort",T),R()})});const T=()=>o.cancelAnimationFrame(y);n.addEventListener("abort",T,{once:!0})}),n),A}catch(R){throw A(),R}}const GA=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"]),QA=new Set(["url","inline","eval","unknown"]),qA=/^\/(?:\:segment(?:\/\:segment)*)?$/,YA=/^[a-f0-9]{64}$/,WA=255,ZA=160,KA=256;function JA(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!GA.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>KA||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!QA.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=XA(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>ZA||!qA.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!YA.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 XA(e){if(e!==void 0&&!(typeof e!="string"||e.length>WA))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Di=["android","ios","ohos","windows","macos","linux"],e0="0.9.0",t0=Object.freeze(["android","ios","ohos","windows","macos"]),ef="该小程序暂不支持当前平台",r0="PLATFORM_UNSUPPORTED";function n0(e){return typeof e=="string"&&Di.includes(e)}function i0(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 o0(e){const t=e.manifest;if(!u0(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=qc(e.sdkVersion)??qc(t.sdkVersion);return c0(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:a0()}const r=tf(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function s0(e){const t=i0(e.operatingSystemName);if(!t)return fr("host_operating_system_unknown");const r=e.platformAccess;if(!r)return fr("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Di,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=o0({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?fr("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):Qc(t,s)}if(r.effectivePlatforms===void 0)return fr("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=tf(r.effectivePlatforms);if("reason"in n)return fr("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=d0(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return Qc(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function Qc(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:fr("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function fr(e,t={}){return{status:"denied",reason:e,message:ef,...t}}function a0(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:t0,platformsDeclared:!1,policy:"legacy_mobile_default"}}function tf(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(!n0(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Di.filter(r=>t.has(r)))}}function c0(e){if(typeof e!="string"||!e.trim())return!1;const t=vs(e.trim(),e0);return t!==void 0&&t>=0}function qc(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function d0(e){return e==="explicit"||e==="legacy_mobile_default"}function u0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function l0(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:f0(i.pathname),sanitizedPathnameHash:iu(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function f0(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}const m0=1e4,h0=1e4,Ki=2e3,g0=2,p0="open-with-native-credential-policy",rf="安全提示",nf="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class y0{nonce=Ta();runtimeId=Ta();terminalController=new AbortController;options;handshakeTimeout;ports;primitiveAvailability;effectiveCapabilities;identity;identityRef;iframe;iframeErrorListener;iframeLoadListener;bridgeServer=null;miniProgramSrc="";launchUrl="";startPromise=null;readyContext=null;resolveReady;rejectReady;terminalError;status="idle";stateValue="idle";handshakeTimeoutTimer;lifecycleDisposer;workspaceCardsDisposer;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;failureTransitionInProgress=!1;destroyRequestedDuringFailure=!1;sdkVersionDecision;platformGateDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;unexpectedDocumentLoadTimer;devDocumentDisposer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;networkPolicy;networkPolicyDisposer;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=Hu(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities,hasUserDataPresentation:t.userDataPresentation!==void 0,hasUserDataSettings:t.userDataPresentation?.openDataPermissions!==void 0});this.ports=r.ports,this.primitiveAvailability=r.primitiveAvailability,this.effectiveCapabilities=r.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const n=this.identity.miniProgramId?.trim();if(n)return{miniProgramId:n,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??m0,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}getDataPermissionBridge(){return this.capabilityGraph?.permissionBridge}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics,r=this.capabilityGraph?.sandboxDiagnostics,n=this.capabilityGraph?.gameSaveDiagnostics;return{...t?{storage:t}:{},...r?{sandbox:r}:{},...n?{gameSaves:n}:{}}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??Ie("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??Ie("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(O0(),this.startPromise=this.createReadyPromise(),this.setState("starting"),this.setStatus("starting"),this.launch().catch(t=>{this.failRuntime(t)}),this.startPromise)}destroy(){if(this.failureTransitionInProgress){this.destroyRequestedDuringFailure=!0;return}if(this.stateValue==="destroyed")return;const t=this.terminalError??Ie("RUNTIME_DESTROYED","小程序运行时已销毁");this.terminalError=t,this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.teardownIframe(),this.rejectReady?.(t)}show(){const t=this.hostVisible;this.hostVisible=!0,this.emitLifecycleEvent("show"),this.capabilityGraph?.notifyViewportChange(),!t&&this.stateValue==="ready"&&this.sdkVersionDecision?.heartbeatEnabled&&(this.documentRevalidationPending?this.preparedHistoryTraversalGeneration!==void 0?this.armDocumentRevalidationTimer(this.documentRevalidationGeneration,{waitingForDocument:!0}):this.resendDocumentRevalidationProbe():this.sendLocationProbe())}hide(){this.hostVisible=!1,this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.emitLifecycleEvent("hide")}prepareForHistoryTraversal(){if(this.stateValue!=="ready"||this.bridgeServer?.protocolVersion!==2||!this.sdkVersionDecision?.heartbeatEnabled)return()=>{};const t=this.beginDocumentRevalidation({deferProbe:!0});return this.isInactive()||t!==this.documentRevalidationGeneration?()=>{}:(this.preparedHistoryTraversalGeneration=t,()=>{this.preparedHistoryTraversalGeneration===t&&this.cancelPreparedHistoryTraversal()})}createReadyPromise(){return new Promise((t,r)=>{this.resolveReady=t,this.rejectReady=r})}async launch(){const t=await this.resolveRuntimeLaunchConfiguration();if(this.isInactive())return;if(this.runtimePermissions=Fp(t.runtimePermissions),this.networkPolicy=Fu(t.networkPolicy),this.networkPolicy?.enforcement==="restricted"){const s=t.canonicalIdentity?.miniProgramId?.trim();if(!s||!this.options.networkPolicyEnforcement)throw{code:"NETWORK_POLICY_UNSUPPORTED",message:"当前 Host 尚未具备严格网络策略执行能力,请更新 Host 后重新打开"};const a=await Np(this.options.networkPolicyEnforcement,{policy:this.networkPolicy,miniProgramId:s,launchUrl:t.launchUrl,onInvalidated:()=>this.failRuntime({code:"NETWORK_POLICY_CHANGED",message:"网络权限已变更,请重新打开小程序"})},{signal:this.terminalController.signal});if(this.isInactive()){a();return}this.networkPolicyDisposer=a}this.runtimeFeatures=t.runtimeFeatures?Object.freeze({...t.runtimeFeatures}):void 0,this.miniProgramPresentation=t.miniProgramPresentation,this.locationBasePath=t.locationBasePath,this.anonymousStorageScope=t.anonymousStorageScope??this.options.anonymousStorageScope;const r=t.allowedHttpOrigins??this.options.allowedHttpOrigins;this.allowedHttpOrigins=r?Object.freeze([...r]):void 0,this.bindCanonicalIdentity(t.canonicalIdentity),this.sdkVersionDecision=vy(t.sdkVersionPolicy);const n=xA(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=s0({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw R0(this.platformGateDecision);if(this.miniProgramDetail=C0(t),this.effectiveCapabilities=Bu(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),N0(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(b0(i)),this.launchUrl=i,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const s=Qu(new URL(i),this.locationBasePath);this.devDocumentDisposer=Hp({iframe:this.iframe,launchUrl:i,nonce:this.nonce,locationBasePath:s,onLeaving:()=>{this.prepareForHistoryTraversal()},onResume:()=>{!this.isInactive()&&this.documentRevalidationPending&&this.beginDocumentRevalidation()},onReload:a=>{this.isInactive()||nt(c=>this.options.onDevDocumentReload?.(c,s),a)}})}if(this.miniProgramSrc=Cp(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=ps(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:Kn,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,nt(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[Kn])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=TA({verifiedSdkVersion:this.sdkVersionDecision?.sdkVersion,diagnosticCapabilities:this.effectiveCapabilities,account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,media:this.ports.media,transfer:this.ports.transfer,storage:this.ports.storage,scopedStorage:this.ports.scopedStorage,storageDiagnostics:this.ports.storageDiagnostics,hostPresentation:this.ports.presentation,hostCompanion:this.ports.companion,hostProtocol:this.ports.protocol,...this.options.userDataPresentation===void 0?{}:{userDataPresentation:this.options.userDataPresentation},...this.options.onUserDataTelemetry===void 0?{}:{onUserDataTelemetry:this.options.onUserDataTelemetry},workspaceCards:this.ports.workspaceCards,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,networkPolicy:this.networkPolicy,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,prepareLongScreenshot:(n,i)=>Dp(this.iframe,n,i),prepareScreenshot:(n,i,o)=>{const s=this.sdkVersionDecision?.sdkVersion;return!s||(vs(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):VA(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=NA({handlers:this.capabilityGraph.handlers,runDisplayRequest:this.capabilityGraph.runDisplayRequest,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,allowsGameSaveAccess:this.capabilityGraph.allowsGameSaveAccess,allowsUserGameDataFileAccess:this.capabilityGraph.allowsUserGameDataFileAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:u})=>{const l={type:"capability",phase:"host",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...u?{network:u}:{}};nt(this.options.onCapabilityTrace,l)}}:{}});this.bridgeServer=new qp({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,...this.options.onDevUploadSession?{onDevUploadSession:n=>{this.isInactive()||nt(this.options.onDevUploadSession,n)}}:{},...this.ports.workspaceCards?{getWorkspaceCardLaunchContext:()=>this.ports.workspaceCards.getLaunchContext()}:{},onHandshake:n=>this.handleBridgeHandshake(n),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:n=>{this.handleInternalBridgeEvent(n)},onResponsePosted:({method:n,outcome:i,errorCode:o})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:n,outcome:i,...o?{errorCode:o}:{}})}}),this.bridgeServer.start(),this.workspaceCardsDisposer=this.ports.workspaceCards?.onLaunchContextChange(()=>this.publishWorkspaceCardLaunchContext()),this.setStatus("bridge_started"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge_started"})}onIframeError(t=new Error("小程序 iframe 加载失败")){if(this.isInactive())return;const r=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(Ie("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 D0(t)?t:of(Ie("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 Rp(t,r,{allowPrivateNetwork:Gc(r)||Yc(r)||await this.isDevRuntime()})}catch(r){throw Ie("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??T0)({message:nf,title:rf,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(va(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!Gc(r)&&!Yc(r)}async closeAfterDevLaunchCancellation(){const t=Ie("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{Wc(),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(()=>Wc())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Tp),this.iframe.setAttribute("referrerpolicy",Op),this.iframe.setAttribute("sandbox",qu)}removeIframeListeners(){this.iframe.removeEventListener("error",this.iframeErrorListener),this.iframe.removeEventListener("load",this.iframeLoadListener)}installSubscriptions(){if(this.options.lifecycle&&!this.lifecycleDisposer){const t=this.options.lifecycle.subscribe({show:this.show.bind(this),hide:this.hide.bind(this)});this.lifecycleDisposer=typeof t=="function"?t:null}}clearLifecycleDisposer(){const t=[this.lifecycleDisposer,this.workspaceCardsDisposer];this.lifecycleDisposer=null,this.workspaceCardsDisposer=null;for(const r of t)try{r?.()}catch{}}publishWorkspaceCardLaunchContext(){this.stateValue!=="ready"||!this.ports.workspaceCards||this.bridgeServer?.postEvent("workspace_cards_launch_context_change",this.ports.workspaceCards.getLaunchContext())}handleBridgeReady(){if(this.isInactive())return;if(this.readyContext){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"});return}this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge",method:"ready"}),this.setState("ready"),this.sdkVersionDecision?.heartbeatEnabled&&this.hostVisible&&this.sendLocationProbe(),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),nt(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(),nt(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Py(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(Ie("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>=g0)){this.failRuntime(Ie("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(En,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},Ki),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:En})}clearHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0),this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0}beginDocumentRevalidation(t={}){this.clearUnexpectedDocumentLoadFailure(),this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.preparedHistoryTraversalGeneration=void 0,this.documentRevalidationPending=!0;const r=++this.documentRevalidationGeneration;return this.iframeHiddenForRevalidation||(this.iframeVisibilityBeforeRevalidation=this.iframe.style.visibility,this.iframe.style.visibility="hidden",this.iframeHiddenForRevalidation=!0),t.deferProbe?this.armDocumentRevalidationTimer(r,{waitingForDocument:!0}):this.sendDocumentRevalidationProbe(),this.traceDocumentValidation(),r}sendDocumentRevalidationProbe(){if(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)return;const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.armDocumentRevalidationTimer(this.documentRevalidationGeneration),this.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled||this.preparedHistoryTraversalGeneration!==void 0)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(En,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:En})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&this.failRuntime(Ie("DOCUMENT_REVALIDATION_TIMEOUT",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时"))},r.waitingForDocument?h0:Ki))}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()},Ki)),this.traceDocumentValidation()}traceDocumentValidation(){this.isInactive()||this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"document_validation",documentVerifying:this.documentRevalidationPending,message:this.documentRevalidationPending?"当前文档正在验证":"当前文档验证等待已结束"})}clearDocumentRevalidation(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1}cancelPreparedHistoryTraversal(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.iframeHiddenForRevalidation&&this.iframe.style.visibility==="hidden"&&(this.iframe.style.visibility=this.iframeVisibilityBeforeRevalidation??""),this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1,this.hostVisible&&this.sdkVersionDecision?.heartbeatEnabled&&this.sendLocationProbe(),this.traceDocumentValidation()}handleDuplicateBridgeHandshake(){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"}),this.documentRevalidationPending&&this.resendDocumentRevalidationProbe()}handleInternalBridgeEvent(t){if(t.method===Ih){this.handleCspViolation(t.payload);return}if(t.method!==wh)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(Ie("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Yu(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(Ie("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=JA(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){nt(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=l0(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(Ie("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:Sp,launchUrlType:va(t),networkPolicy:p0})}failRuntime(t){const r=E0(t);if(this.isInactive())return r;this.terminalError=r,this.stateValue="failed",this.failureTransitionInProgress=!0;try{this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),nt(this.options.onError,w0(r)),nt(this.options.onStateChange,"failed"),this.terminalController.abort(r),this.postBridgeError(r);try{this.disposeRuntimeResources()}finally{this.teardownIframe(r)}}finally{this.rejectReady?.(r),this.failureTransitionInProgress=!1,this.destroyRequestedDuringFailure&&(this.destroyRequestedDuringFailure=!1,this.destroy())}return r}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(this.devDocumentDisposer?.(),this.devDocumentDisposer=void 0,!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0;try{this.networkPolicyDisposer?.()}catch{}this.networkPolicyDisposer=void 0,this.clearHandshakeTimeout(),this.clearHeartbeat(),this.clearUnexpectedDocumentLoadFailure(),this.clearDocumentRevalidation(),this.destroyBridgeServer(),this.capabilityGraph?.dispose(),this.capabilityGraph=void 0,this.clearLifecycleDisposer(),this.removeIframeListeners();try{this.options.dispose?.()}catch{}}}teardownIframe(t){if(!this.iframeTornDown){this.iframeTornDown=!0;try{this.options.teardownIframe?this.options.teardownIframe(this.iframe,t):this.iframe.remove()}catch{}}}setStatus(t){this.status!==t&&(this.status=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:t}))}setState(t){this.stateValue!==t&&(this.stateValue=t,nt(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){nt(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 E0(e){const t=ps(e);return ui(e)&&"cause"in e&&of(t,e.cause),t}function of(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function w0(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{},...e.cause!==void 0?{cause:A0(e.cause)}:{}}}const Ji=(()=>{const e=Object.getOwnPropertyDescriptor(new Error,"stack")?.get,t=Object.getOwnPropertyDescriptor(new Error,"stack")?.get;return typeof e=="function"&&e===t?e:void 0})(),I0=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function _0(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return;if("value"in r)return r.value;if(t!=="stack"||!Ji||r.get!==Ji)return;const n=Object.getPrototypeOf(e);if(I0.has(n)){for(const i of["name","message"]){const o=Object.getOwnPropertyDescriptor(e,i),s=Object.getOwnPropertyDescriptor(n,i)??Object.getOwnPropertyDescriptor(Error.prototype,i);if(o&&!("value"in o)||s&&!("value"in s))return}return Ji.call(e)}}function A0(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=_0(e,r);typeof n=="string"&&(t[r]=n.slice(0,r==="stack"?8192:2048).replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@").replace(/([?&][^=\s]+)=([^&#\s]*)/g,"$1=[redacted]").replace(/(authorization|cookie|password|secret|token|pkey|api[_-]?key)([\"'\s:=]+)([^\s,}]+)/gi,"$1$2[redacted]"))}return Object.keys(t).length?t:void 0}catch{return}}function D0(e){return ui(e)&&typeof e.code=="string"&&typeof e.message=="string"}function ui(e){return!!e&&typeof e=="object"}function nt(e,t){try{e?.(t)}catch{}}function N0(e,t,r){try{e?.(t,r)}catch{}}function Yc(e){try{const t=new URL(e);return t.protocol==="http:"&&CA(t.hostname)}catch{return!1}}function M0(e){try{return new URL(e).origin}catch{return}}function b0(e){return vp()?"*":M0(e)}function S0(e){return`${rf}
6
-
7
- ${nf}
8
-
9
- URL: ${e}`}function T0(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(S0(e.url))}function Wc(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function O0(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,r=typeof window>"u"?void 0:window,n=Object.freeze({protocolVersion:yu,knownMethodCount:Rt.length,supportsFileCreate:Rt.some(i=>i.method===ru),system:v0(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:ur(e?.hardwareConcurrency),maxTouchPoints:ur(e?.maxTouchPoints),screen:{width:ur(t?.width),height:ur(t?.height)},viewport:{width:ur(r?.innerWidth),height:ur(r?.innerHeight),devicePixelRatio:P0(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function v0(e="",t=""){const r=`${t} ${e}`.toLowerCase();return/iphone|ipad|ipod/.test(r)?"ios":r.includes("android")?"android":/win32|win64|windows/.test(r)?"windows":/darwin|macintosh|macintel|mac os/.test(r)?"macos":/linux|x11/.test(r)?"linux":"unknown"}function ur(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function P0(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function R0(e){return Ie(r0,ef,{reason:e.reason,...e.platform===void 0?{}:{platform:e.platform},...e.invalidReason===void 0?{}:{invalidReason:e.invalidReason},...e.effectivePlatforms===void 0?{}:{effectivePlatforms:e.effectivePlatforms}})}function C0(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(!t)return;const r=e.canonicalIdentity?.miniProgramVersion?.trim(),n=e.miniProgramPresentation?.name?.trim(),i=e.miniProgramPresentation?.avatarUrl?.trim(),o=e.miniProgramPresentation?.author?.trim();return Object.freeze({miniProgramId:t,...r?{version:r}:{},...n?{name:n}:{},...i?{iconUrl:i}:{},...o?{author:o}:{},...e.sdkVersionPolicy.releaseChannel===void 0?{}:{releaseChannel:e.sdkVersionPolicy.releaseChannel}})}function k0(e){if(!ui(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!ui(e.environment)||typeof e.environment.getCurrentHref!="function"||typeof e.environment.isDevRuntime!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 environment");if(typeof e.resolveLaunchConfiguration!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 resolveLaunchConfiguration");return new y0(e)}function L0(e={}){return async(t,r,n)=>{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");const i=e.indexedDB??globalThis.indexedDB,o=e.crypto??globalThis.crypto;if(!i||!o?.getRandomValues)throw new Error("Host 缺少持久化账号标识能力");const s=await new Promise((a,c)=>{const d=i.open("heybox-mini-program-private-account-v1",1);let u=!1;const l=()=>n.signal.removeEventListener("abort",h),f=m=>{u||(u=!0,l(),c(m))},h=()=>f(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{u?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>f(d.error),d.onblocked=()=>f(new Error("账号存储被阻塞")),d.onsuccess=()=>{u?d.result.close():(u=!0,l(),a(d.result))},n.signal.addEventListener("abort",h,{once:!0}),n.signal.aborted&&h()});try{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");return await new Promise((a,c)=>{const d=s.transaction("accounts","readwrite"),u=d.objectStore("accounts"),l=JSON.stringify([t,r]);let f;const h=()=>{try{d.abort()}catch{}m(),c(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",h,{once:!0});const m=()=>n.signal.removeEventListener("abort",h);d.oncomplete=()=>{m(),a(f)},d.onabort=d.onerror=()=>{m(),c(d.error??new Error("账号存储事务失败"))};const E=u.get(l);E.onsuccess=()=>{try{if(typeof E.result=="string"&&/^ak_[0-9a-f]{64}$/.test(E.result))f=E.result;else{const N=o.getRandomValues(new Uint8Array(32));f=`ak_${Array.from(N,A=>A.toString(16).padStart(2,"0")).join("")}`,u.put(f,l)}}catch{d.abort()}}})}finally{s.close()}}}const x0=/^(?:authentication-info|authorization|cookie|cookie2|proxy-authenticate|proxy-authentication-info|proxy-authorization|set-cookie|set-cookie2|www-authenticate|pkey|x-pkey|x-access-token|x-auth-token)$/i,U0=new Set(["origin","referer","user-agent"]);function j0(e,t){return Zg({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=z0(r),a=await e.authenticatedRequest(s,o);return F0(a)})}).network}function z0(e){const t=B0(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function B0(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!H0(t)))}function H0(e){const t=e.trim().toLowerCase();return U0.has(t)}function F0(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:$0(e.headers)??{}}}function $0(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!V0(t)))}function V0(e){const t=e.trim().toLowerCase();return x0.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function G0(e,t,r){const n=Z0(e.presentation,t);return{account:Y0(e,t,r),network:j0(e,t),...e.storage===void 0?{}:{storage:W0(e,t)},...e.storage===void 0?{}:Q0(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function Q0(e,t){const r=e.storage;return typeof r.storage.key!="function"||typeof r.storage.length!="number"?{}:{storageDiagnostics:{listRaw:n=>t.run(n.signal,()=>{const i=[];for(let o=0;o<r.storage.length;o+=1){const s=r.storage.key(o);if(s===null)continue;const a=r.storage.getItem(s);a!==null&&i.push({area:r.area,key:s,value:a})}return i})}}}function q0(e,t){return{getCurrentHref:()=>(t.assertActive(),e.environment.getCurrentHref()),isDevRuntime:()=>t.run(void 0,()=>e.environment.isDevRuntime()),...e.environment.setDocumentTitle===void 0?{}:{setDocumentTitle:r=>{t.assertActive(),e.environment.setDocumentTitle?.(r)}}}}function Y0(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??L0();return{getAccountKey:(i,o,s)=>t.run(s.signal,a=>n(i,o,{...s,signal:a})),getCurrentUserId:i=>t.run(i.signal,o=>e.account.getCurrentUserId({signal:o})),ensureAuthenticated:i=>t.run(i.signal,o=>e.account.ensureAuthenticated({trustedUserGesture:i.trustedUserGesture,reason:i.reason,signal:o})),onChange:i=>{t.assertActive();const o=e.account.onChange(s=>{t.signal.aborted||i(s)});return r(o)}}}function W0(e,t){const r=e.storage.storage;return{getRaw:(n,i)=>t.run(i.signal,()=>{const o=r.getItem(n);return o===null?void 0:o}),setRaw:(n,i,o)=>t.run(o.signal,()=>{r.setItem(n,i)})}}function Z0(e,t){if(!e)return;const r={};return e.close&&(r.close=n=>t.run(n.signal,i=>e.close({...n,signal:i}))),e.reload&&(r.reload=n=>t.run(n.signal,i=>e.reload({...n,signal:i}))),e.openAppPage&&(r.openAppPage=(n,i)=>t.run(i.signal,o=>e.openAppPage(n,{...i,signal:o}))),e.openWindow&&(r.openWindow=(n,i)=>t.run(i.signal,o=>e.openWindow(n,{...i,signal:o}))),e.applyOrientation&&(r.applyOrientation=(n,i)=>t.run(i.signal,o=>e.applyOrientation(n,{...i,signal:o}))),e.onViewportChange&&(r.onViewportChange=n=>{t.assertActive();const i=e.onViewportChange(()=>{t.signal.aborted||n()});let o=!1;const s=()=>{o||(o=!0,t.signal.removeEventListener("abort",s),i())};return t.signal.addEventListener("abort",s,{once:!0}),s}),e.getViewportMetrics&&(r.getViewportMetrics=()=>(t.assertActive(),e.getViewportMetrics())),e.getNavigationBarHeight&&(r.getNavigationBarHeight=()=>(t.assertActive(),e.getNavigationBarHeight())),e.setNavigationBarStyle&&(r.setNavigationBarStyle=(n,i)=>t.run(i.signal,o=>e.setNavigationBarStyle(n,{...i,signal:o}))),e.showShareMenu&&(r.showShareMenu=(n,i)=>t.run(i.signal,o=>e.showShareMenu(n,{...i,signal:o}))),e.setScreenshotChromeHidden&&(r.setScreenshotChromeHidden=(n,i)=>cp(i)?e.setScreenshotChromeHidden(n,i):t.run(i.signal,o=>e.setScreenshotChromeHidden(n,{...i,signal:o}))),e.captureAndShare&&(r.captureAndShare=(n,i)=>t.run(i.signal,o=>e.captureAndShare(n,{...i,signal:o}))),e.showToast&&(r.showToast=(n,i)=>t.run(i.signal,o=>e.showToast(n,{...i,signal:o}))),e.showLoading&&(r.showLoading=(n,i)=>t.run(i.signal,o=>e.showLoading(n,{...i,signal:o}))),e.hideLoading&&(r.hideLoading=n=>t.run(n.signal,i=>e.hideLoading({...n,signal:i}))),e.vibrate&&(r.vibrate=(n,i)=>t.run(i.signal,o=>e.vibrate(n,{...i,signal:o}))),e.setClipboard&&(r.setClipboard=(n,i)=>t.run(i.signal,o=>e.setClipboard(n,{...i,signal:o}))),Object.keys(r).length===0?void 0:r}function K0(){const e=new AbortController;return{signal:e.signal,abort:t=>{e.signal.aborted||e.abort(t)},assertActive:t=>{const r=[e.signal,t].find(n=>n?.aborted);if(r)throw Tn(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(u=>u.aborted);if(i)throw Tn(i.reason);const o=new AbortController;let s;const a=new Promise((u,l)=>{s=l}),c=n.map(u=>{const l=()=>{o.signal.aborted||o.abort(u.reason),s(Tn(u.reason))};return u.addEventListener("abort",l,{once:!0}),{listener:l,source:u}});let d;try{d=Promise.resolve(r(o.signal))}catch(u){d=Promise.reject(u)}try{const u=await Promise.race([d,a]),l=n.find(f=>f.aborted);if(l)throw Tn(l.reason);return u}finally{for(const{listener:u,source:l}of c)l.removeEventListener("abort",u)}}}}function Tn(e){return new DOMException("Web Host operation aborted","AbortError")}async function J0(e){const t=K0(),r=new Set;let n=!1;const i=f=>{if(n||t.signal.aborted)return Xi(f),()=>{};let h=!0;const m=()=>{h&&(h=!1,r.delete(m),Xi(f))};return r.add(m),m},o=()=>s(e.signal.reason),s=f=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(f);for(const h of[...r])h();e.onDispose&&Xi(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=G0(e,t,i);a.storage?.getRaw&&a.storage.setRaw&&(a.scopedStorage=Vu({storage:a.storage,diagnostics:a.storageDiagnostics,coordinationKey:e.storage.storage,lock:Gu,resolveScope:async()=>$u((await l()).configuration)}));const c=Hu(a,{hostCapabilities:e.hostCapabilities,hasUserDataPresentation:e.userDataPresentation!==void 0,hasUserDataSettings:e.userDataPresentation?.openDataPermissions!==void 0}),d=q0(e,t);let u;const l=()=>u??=t.run(void 0,f=>e.resolveLaunch(f));return{platform:"web",ports:a,environment:d,resolveLaunch:l,...e.authPresentation===void 0?{}:{authPresentation:X0(e.authPresentation,t)},...e.userDataPresentation===void 0?{}:{userDataPresentation:eD(e.userDataPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function Xi(e){try{e()}catch{}}function X0(e,t){return{...e.confirmFollowAuthor?{confirmFollowAuthor:r=>t.run(r.signal,n=>e.confirmFollowAuthor({...r,signal:n}))}:{},confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}function eD(e,t){return{...e.openDataPermissions?{openDataPermissions:r=>t.run(r.signal,n=>e.openDataPermissions({...r,signal:n}))}:{},confirmDataPermission:r=>t.run(r.signal,n=>e.confirmDataPermission({...r,signal:n}))}}var lr={},eo,Zc;function tD(){return Zc||(Zc=1,eo=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),eo}var to={},Nt={},Kc;function Jt(){if(Kc)return Nt;Kc=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Nt.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},Nt.getSymbolTotalCodewords=function(n){return t[n]},Nt.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Nt.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Nt.isKanjiModeEnabled=function(){return typeof e<"u"},Nt.toSJIS=function(n){return e(n)},Nt}var ro={},Jc;function js(){return Jc||(Jc=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,i){if(e.isValid(n))return n;try{return t(n)}catch{return i}}})(ro)),ro}var no,Xc;function rD(){if(Xc)return no;Xc=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},no=e,no}var io,ed;function nD(){if(ed)return io;ed=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,i){const o=t*this.size+r;this.data[o]=n,i&&(this.reservedBit[o]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},io=e,io}var oo={},td;function iD(){return td||(td=1,(function(e){const t=Jt().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const i=Math.floor(n/7)+2,o=t(n),s=o===145?26:Math.ceil((o-13)/(2*i-2))*2,a=[o-7];for(let c=1;c<i-1;c++)a[c]=a[c-1]-s;return a.push(6),a.reverse()},e.getPositions=function(n){const i=[],o=e.getRowColCoords(n),s=o.length;for(let a=0;a<s;a++)for(let c=0;c<s;c++)a===0&&c===0||a===0&&c===s-1||a===s-1&&c===0||i.push([o[a],o[c]]);return i}})(oo)),oo}var so={},rd;function oD(){if(rd)return so;rd=1;const e=Jt().getSymbolSize,t=7;return so.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},so}var ao={},nd;function sD(){return nd||(nd=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,d=null,u=null;for(let l=0;l<o;l++){a=c=0,d=u=null;for(let f=0;f<o;f++){let h=i.get(l,f);h===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=h,a=1),h=i.get(f,l),h===u?c++:(c>=5&&(s+=t.N1+(c-5)),u=h,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const d=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(d===4||d===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let d=0;d<o;d++){a=c=0;for(let u=0;u<o;u++)a=a<<1&2047|i.get(d,u),u>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(u,d),u>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let d=0;d<s;d++){o(d),e.applyMask(d,i);const u=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(d,i),u<c&&(c=u,a=d)}return a}})(ao)),ao}var On={},id;function sf(){if(id)return On;id=1;const e=js(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return On.getBlocksCount=function(i,o){switch(o){case e.L:return t[(i-1)*4+0];case e.M:return t[(i-1)*4+1];case e.Q:return t[(i-1)*4+2];case e.H:return t[(i-1)*4+3];default:return}},On.getTotalCodewordsCount=function(i,o){switch(o){case e.L:return r[(i-1)*4+0];case e.M:return r[(i-1)*4+1];case e.Q:return r[(i-1)*4+2];case e.H:return r[(i-1)*4+3];default:return}},On}var co={},Gr={},od;function aD(){if(od)return Gr;od=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let i=0;i<255;i++)e[i]=n,t[n]=i,n<<=1,n&256&&(n^=285);for(let i=255;i<512;i++)e[i]=e[i-255]})(),Gr.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Gr.exp=function(n){return e[n]},Gr.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},Gr}var sd;function cD(){return sd||(sd=1,(function(e){const t=aD();e.mul=function(n,i){const o=new Uint8Array(n.length+i.length-1);for(let s=0;s<n.length;s++)for(let a=0;a<i.length;a++)o[s+a]^=t.mul(n[s],i[a]);return o},e.mod=function(n,i){let o=new Uint8Array(n);for(;o.length-i.length>=0;){const s=o[0];for(let c=0;c<i.length;c++)o[c]^=t.mul(i[c],s);let a=0;for(;a<o.length&&o[a]===0;)a++;o=o.slice(a)}return o},e.generateECPolynomial=function(n){let i=new Uint8Array([1]);for(let o=0;o<n;o++)i=e.mul(i,new Uint8Array([1,t.exp(o)]));return i}})(co)),co}var uo,ad;function dD(){if(ad)return uo;ad=1;const e=cD();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(n.length+this.degree);i.set(n);const o=e.mod(i,this.genPoly),s=this.degree-o.length;if(s>0){const a=new Uint8Array(this.degree);return a.set(o,s),a}return o},uo=t,uo}var lo={},fo={},mo={},cd;function af(){return cd||(cd=1,mo.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),mo}var mt={},dd;function cf(){if(dd)return mt;dd=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
10
- ]))+`;mt.KANJI=new RegExp(r,"g"),mt.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),mt.BYTE=new RegExp(n,"g"),mt.NUMERIC=new RegExp(e,"g"),mt.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return mt.testKanji=function(c){return i.test(c)},mt.testNumeric=function(c){return o.test(c)},mt.testAlphanumeric=function(c){return s.test(c)},mt}var ud;function Xt(){return ud||(ud=1,(function(e){const t=af(),r=cf();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(o,s){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!t.isValid(s))throw new Error("Invalid version: "+s);return s>=1&&s<10?o.ccBits[0]:s<27?o.ccBits[1]:o.ccBits[2]},e.getBestModeForData=function(o){return r.testNumeric(o)?e.NUMERIC:r.testAlphanumeric(o)?e.ALPHANUMERIC:r.testKanji(o)?e.KANJI:e.BYTE},e.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},e.isValid=function(o){return o&&o.bit&&o.ccBits};function n(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+i)}}e.from=function(o,s){if(e.isValid(o))return o;try{return n(o)}catch{return s}}})(fo)),fo}var ld;function uD(){return ld||(ld=1,(function(e){const t=Jt(),r=sf(),n=js(),i=Xt(),o=af(),s=7973,a=t.getBCHDigit(s);function c(f,h,m){for(let E=1;E<=40;E++)if(h<=e.getCapacity(E,m,f))return E}function d(f,h){return i.getCharCountIndicator(f,h)+4}function u(f,h){let m=0;return f.forEach(function(E){const N=d(E.mode,h);m+=N+E.getBitsLength()}),m}function l(f,h){for(let m=1;m<=40;m++)if(u(f,m)<=e.getCapacity(m,h,i.MIXED))return m}e.from=function(h,m){return o.isValid(h)?parseInt(h,10):m},e.getCapacity=function(h,m,E){if(!o.isValid(h))throw new Error("Invalid QR Code version");typeof E>"u"&&(E=i.BYTE);const N=t.getSymbolTotalCodewords(h),A=r.getTotalCodewordsCount(h,m),R=(N-A)*8;if(E===i.MIXED)return R;const y=R-d(E,h);switch(E){case i.NUMERIC:return Math.floor(y/10*3);case i.ALPHANUMERIC:return Math.floor(y/11*2);case i.KANJI:return Math.floor(y/13);case i.BYTE:default:return Math.floor(y/8)}},e.getBestVersionForData=function(h,m){let E;const N=n.from(m,n.M);if(Array.isArray(h)){if(h.length>1)return l(h,N);if(h.length===0)return 1;E=h[0]}else E=h;return c(E.mode,E.getLength(),N)},e.getEncodedBits=function(h){if(!o.isValid(h)||h<7)throw new Error("Invalid QR Code version");let m=h<<12;for(;t.getBCHDigit(m)-a>=0;)m^=s<<t.getBCHDigit(m)-a;return h<<12|m}})(lo)),lo}var ho={},fd;function lD(){if(fd)return ho;fd=1;const e=Jt(),t=1335,r=21522,n=e.getBCHDigit(t);return ho.getEncodedBits=function(o,s){const a=o.bit<<3|s;let c=a<<10;for(;e.getBCHDigit(c)-n>=0;)c^=t<<e.getBCHDigit(c)-n;return(a<<10|c)^r},ho}var go={},po,md;function fD(){if(md)return po;md=1;const e=Xt();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let i,o,s;for(i=0;i+3<=this.data.length;i+=3)o=this.data.substr(i,3),s=parseInt(o,10),n.put(s,10);const a=this.data.length-i;a>0&&(o=this.data.substr(i),s=parseInt(o,10),n.put(s,a*3+1))},po=t,po}var yo,hd;function mD(){if(hd)return yo;hd=1;const e=Xt(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(i){let o;for(o=0;o+2<=this.data.length;o+=2){let s=t.indexOf(this.data[o])*45;s+=t.indexOf(this.data[o+1]),i.put(s,11)}this.data.length%2&&i.put(t.indexOf(this.data[o]),6)},yo=r,yo}var Eo,gd;function hD(){if(gd)return Eo;gd=1;const e=Xt();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,i=this.data.length;n<i;n++)r.put(this.data[n],8)},Eo=t,Eo}var wo,pd;function gD(){if(pd)return wo;pd=1;const e=Xt(),t=Jt();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(i){return i*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let i;for(i=0;i<this.data.length;i++){let o=t.toSJIS(this.data[i]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+`
11
- Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},wo=r,wo}var Io={exports:{}},yd;function pD(){return yd||(yd=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,d,u,l,f,h,m,E,N;!a.empty();){c=a.pop(),d=c.value,l=c.cost,f=r[d]||{};for(u in f)f.hasOwnProperty(u)&&(h=f[u],m=l+h,E=s[u],N=typeof s[u]>"u",(N||E>m)&&(s[u]=m,a.push(u,m),o[u]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var A=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(A)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var i=[],o=n;o;)i.push(o),r[o],o=r[o];return i.reverse(),i},find_path:function(r,n,i){var o=t.single_source_shortest_paths(r,n,i);return t.extract_shortest_path_from_predecessor_list(o,i)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,i={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);return i.queue=[],i.sorter=r.sorter||n.default_sorter,i},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var i={value:r,cost:n};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Io)),Io.exports}var Ed;function yD(){return Ed||(Ed=1,(function(e){const t=Xt(),r=fD(),n=mD(),i=hD(),o=gD(),s=cf(),a=Jt(),c=pD();function d(A){return unescape(encodeURIComponent(A)).length}function u(A,R,y){const T=[];let j;for(;(j=A.exec(y))!==null;)T.push({data:j[0],index:j.index,mode:R,length:j[0].length});return T}function l(A){const R=u(s.NUMERIC,t.NUMERIC,A),y=u(s.ALPHANUMERIC,t.ALPHANUMERIC,A);let T,j;return a.isKanjiModeEnabled()?(T=u(s.BYTE,t.BYTE,A),j=u(s.KANJI,t.KANJI,A)):(T=u(s.BYTE_KANJI,t.BYTE,A),j=[]),R.concat(y,T,j).sort(function(_,w){return _.index-w.index}).map(function(_){return{data:_.data,mode:_.mode,length:_.length}})}function f(A,R){switch(R){case t.NUMERIC:return r.getBitsLength(A);case t.ALPHANUMERIC:return n.getBitsLength(A);case t.KANJI:return o.getBitsLength(A);case t.BYTE:return i.getBitsLength(A)}}function h(A){return A.reduce(function(R,y){const T=R.length-1>=0?R[R.length-1]:null;return T&&T.mode===y.mode?(R[R.length-1].data+=y.data,R):(R.push(y),R)},[])}function m(A){const R=[];for(let y=0;y<A.length;y++){const T=A[y];switch(T.mode){case t.NUMERIC:R.push([T,{data:T.data,mode:t.ALPHANUMERIC,length:T.length},{data:T.data,mode:t.BYTE,length:T.length}]);break;case t.ALPHANUMERIC:R.push([T,{data:T.data,mode:t.BYTE,length:T.length}]);break;case t.KANJI:R.push([T,{data:T.data,mode:t.BYTE,length:d(T.data)}]);break;case t.BYTE:R.push([{data:T.data,mode:t.BYTE,length:d(T.data)}])}}return R}function E(A,R){const y={},T={start:{}};let j=["start"];for(let I=0;I<A.length;I++){const _=A[I],w=[];for(let S=0;S<_.length;S++){const b=_[S],U=""+I+S;w.push(U),y[U]={node:b,lastCount:0},T[U]={};for(let D=0;D<j.length;D++){const M=j[D];y[M]&&y[M].node.mode===b.mode?(T[M][U]=f(y[M].lastCount+b.length,b.mode)-f(y[M].lastCount,b.mode),y[M].lastCount+=b.length):(y[M]&&(y[M].lastCount=b.length),T[M][U]=f(b.length,b.mode)+4+t.getCharCountIndicator(b.mode,R))}}j=w}for(let I=0;I<j.length;I++)T[j[I]].end=0;return{map:T,table:y}}function N(A,R){let y;const T=t.getBestModeForData(A);if(y=t.from(R,T),y!==t.BYTE&&y.bit<T.bit)throw new Error('"'+A+'" cannot be encoded with mode '+t.toString(y)+`.
12
- Suggested mode is: `+t.toString(T));switch(y===t.KANJI&&!a.isKanjiModeEnabled()&&(y=t.BYTE),y){case t.NUMERIC:return new r(A);case t.ALPHANUMERIC:return new n(A);case t.KANJI:return new o(A);case t.BYTE:return new i(A)}}e.fromArray=function(R){return R.reduce(function(y,T){return typeof T=="string"?y.push(N(T,null)):T.data&&y.push(N(T.data,T.mode)),y},[])},e.fromString=function(R,y){const T=l(R,a.isKanjiModeEnabled()),j=m(T),I=E(j,y),_=c.find_path(I.map,"start","end"),w=[];for(let S=1;S<_.length-1;S++)w.push(I.table[_[S]].node);return e.fromArray(h(w))},e.rawSplit=function(R){return e.fromArray(l(R,a.isKanjiModeEnabled()))}})(go)),go}var wd;function ED(){if(wd)return to;wd=1;const e=Jt(),t=js(),r=rD(),n=nD(),i=iD(),o=oD(),s=sD(),a=sf(),c=dD(),d=uD(),u=lD(),l=Xt(),f=yD();function h(I,_){const w=I.size,S=o.getPositions(_);for(let b=0;b<S.length;b++){const U=S[b][0],D=S[b][1];for(let M=-1;M<=7;M++)if(!(U+M<=-1||w<=U+M))for(let O=-1;O<=7;O++)D+O<=-1||w<=D+O||(M>=0&&M<=6&&(O===0||O===6)||O>=0&&O<=6&&(M===0||M===6)||M>=2&&M<=4&&O>=2&&O<=4?I.set(U+M,D+O,!0,!0):I.set(U+M,D+O,!1,!0))}}function m(I){const _=I.size;for(let w=8;w<_-8;w++){const S=w%2===0;I.set(w,6,S,!0),I.set(6,w,S,!0)}}function E(I,_){const w=i.getPositions(_);for(let S=0;S<w.length;S++){const b=w[S][0],U=w[S][1];for(let D=-2;D<=2;D++)for(let M=-2;M<=2;M++)D===-2||D===2||M===-2||M===2||D===0&&M===0?I.set(b+D,U+M,!0,!0):I.set(b+D,U+M,!1,!0)}}function N(I,_){const w=I.size,S=d.getEncodedBits(_);let b,U,D;for(let M=0;M<18;M++)b=Math.floor(M/3),U=M%3+w-8-3,D=(S>>M&1)===1,I.set(b,U,D,!0),I.set(U,b,D,!0)}function A(I,_,w){const S=I.size,b=u.getEncodedBits(_,w);let U,D;for(U=0;U<15;U++)D=(b>>U&1)===1,U<6?I.set(U,8,D,!0):U<8?I.set(U+1,8,D,!0):I.set(S-15+U,8,D,!0),U<8?I.set(8,S-U-1,D,!0):U<9?I.set(8,15-U-1+1,D,!0):I.set(8,15-U-1,D,!0);I.set(S-8,8,1,!0)}function R(I,_){const w=I.size;let S=-1,b=w-1,U=7,D=0;for(let M=w-1;M>0;M-=2)for(M===6&&M--;;){for(let O=0;O<2;O++)if(!I.isReserved(b,M-O)){let z=!1;D<_.length&&(z=(_[D]>>>U&1)===1),I.set(b,M-O,z),U--,U===-1&&(D++,U=7)}if(b+=S,b<0||w<=b){b-=S,S=-S;break}}}function y(I,_,w){const S=new r;w.forEach(function(O){S.put(O.mode.bit,4),S.put(O.getLength(),l.getCharCountIndicator(O.mode,I)),O.write(S)});const b=e.getSymbolTotalCodewords(I),U=a.getTotalCodewordsCount(I,_),D=(b-U)*8;for(S.getLengthInBits()+4<=D&&S.put(0,4);S.getLengthInBits()%8!==0;)S.putBit(0);const M=(D-S.getLengthInBits())/8;for(let O=0;O<M;O++)S.put(O%2?17:236,8);return T(S,I,_)}function T(I,_,w){const S=e.getSymbolTotalCodewords(_),b=a.getTotalCodewordsCount(_,w),U=S-b,D=a.getBlocksCount(_,w),M=S%D,O=D-M,z=Math.floor(S/D),x=Math.floor(U/D),L=x+1,k=z-x,H=new c(k);let F=0;const G=new Array(D),Z=new Array(D);let g=0;const C=new Uint8Array(I.buffer);for(let ie=0;ie<D;ie++){const ue=ie<O?x:L;G[ie]=C.slice(F,F+ue),Z[ie]=H.encode(G[ie]),F+=ue,g=Math.max(g,ue)}const B=new Uint8Array(S);let Q=0,X,ne;for(X=0;X<g;X++)for(ne=0;ne<D;ne++)X<G[ne].length&&(B[Q++]=G[ne][X]);for(X=0;X<k;X++)for(ne=0;ne<D;ne++)B[Q++]=Z[ne][X];return B}function j(I,_,w,S){let b;if(Array.isArray(I))b=f.fromArray(I);else if(typeof I=="string"){let z=_;if(!z){const x=f.rawSplit(I);z=d.getBestVersionForData(x,w)}b=f.fromString(I,z||40)}else throw new Error("Invalid data");const U=d.getBestVersionForData(b,w);if(!U)throw new Error("The amount of data is too big to be stored in a QR Code");if(!_)_=U;else if(_<U)throw new Error(`
13
- The chosen QR Code version cannot contain this amount of data.
14
- Minimum version required to store current data is: `+U+`.
15
- `);const D=y(_,w,b),M=e.getSymbolSize(_),O=new n(M);return h(O,_),m(O),E(O,_),A(O,w,0),_>=7&&N(O,_),R(O,D),isNaN(S)&&(S=s.getBestMask(O,A.bind(null,O,w))),s.applyMask(S,O),A(O,w,S),{modules:O,version:_,errorCorrectionLevel:w,maskPattern:S,segments:b}}return to.create=function(_,w){if(typeof _>"u"||_==="")throw new Error("No input text");let S=t.M,b,U;return typeof w<"u"&&(S=t.from(w.errorCorrectionLevel,t.M),b=d.from(w.version),U=s.from(w.maskPattern),w.toSJISFunc&&e.setToSJISFunction(w.toSJISFunc)),j(_,b,S,U)},to}var _o={},Ao={},Id;function df(){return Id||(Id=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),d=Math.floor((s+o.margin*2)*c),u=o.margin*c,l=[o.color.light,o.color.dark];for(let f=0;f<d;f++)for(let h=0;h<d;h++){let m=(f*d+h)*4,E=o.color.light;if(f>=u&&h>=u&&f<d-u&&h<d-u){const N=Math.floor((f-u)/c),A=Math.floor((h-u)/c);E=l[a[N*s+A]?1:0]}n[m++]=E.r,n[m++]=E.g,n[m++]=E.b,n[m]=E.a}}})(Ao)),Ao}var _d;function wD(){return _d||(_d=1,(function(e){const t=df();function r(i,o,s){i.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=s,o.width=s,o.style.height=s+"px",o.style.width=s+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(o,s,a){let c=a,d=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(d=n()),c=t.getOptions(c);const u=t.getImageWidth(o.modules.size,c),l=d.getContext("2d"),f=l.createImageData(u,u);return t.qrToImageData(f.data,o,c),r(l,d,u),l.putImageData(f,0,0),d},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const d=e.render(o,s,c),u=c.type||"image/png",l=c.rendererOpts||{};return d.toDataURL(u,l.quality)}})(_o)),_o}var Do={},Ad;function ID(){if(Ad)return Do;Ad=1;const e=df();function t(i,o){const s=i.a/255,a=o+'="'+i.hex+'"';return s<1?a+" "+o+'-opacity="'+s.toFixed(2).slice(1)+'"':a}function r(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function n(i,o,s){let a="",c=0,d=!1,u=0;for(let l=0;l<i.length;l++){const f=Math.floor(l%o),h=Math.floor(l/o);!f&&!d&&(d=!0),i[l]?(u++,l>0&&f>0&&i[l-1]||(a+=d?r("M",f+s,.5+h+s):r("m",c,0),c=0,d=!1),f+1<o&&i[l+1]||(a+=r("h",u),u=0)):c++}return a}return Do.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,u=o.modules.data,l=d+c.margin*2,f=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+l+"v"+l+'H0z"/>':"",h="<path "+t(c.color.dark,"stroke")+' d="'+n(u,d,c.margin)+'"/>',m='viewBox="0 0 '+l+" "+l+'"',N='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+m+' shape-rendering="crispEdges">'+f+h+`</svg>
16
- `;return typeof a=="function"&&a(null,N),N},Do}var Dd;function _D(){if(Dd)return lr;Dd=1;const e=tD(),t=ED(),r=wD(),n=ID();function i(o,s,a,c,d){const u=[].slice.call(arguments,1),l=u.length,f=typeof u[l-1]=="function";if(!f&&!e())throw new Error("Callback required as last argument");if(f){if(l<2)throw new Error("Too few arguments provided");l===2?(d=a,a=s,s=c=void 0):l===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(l<1)throw new Error("Too few arguments provided");return l===1?(a=s,s=c=void 0):l===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(h,m){try{const E=t.create(a,c);h(o(E,s,c))}catch(E){m(E)}})}try{const h=t.create(a,c);d(null,o(h,s,c))}catch(h){d(h)}}return lr.create=t.create,lr.toCanvas=i.bind(null,r.render),lr.toDataURL=i.bind(null,r.renderToDataURL),lr.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),lr}var AD=_D();function DD(e){const t=`hb-game-saves-${crypto.randomUUID()}`,r=c=>`hb-sdk:game-save-cache:${c}`;let n,i;const o=new Promise((c,d)=>{n=c,i=d});let s;const a=new Promise(c=>{s=c});return e.signal.addEventListener("abort",s,{once:!0}),e.signal.aborted&&s(),e.locks.request(r(t),async()=>{let c;try{c=await e.getRoot();const d=await e.locks.request("hb-sdk:game-save-cache:gc",async()=>{e.signal.throwIfAborted();for await(const[u,l]of c)l.kind!=="directory"||!/^hb-game-saves-[a-f0-9-]{36}$/.test(u)||await e.locks.request(r(u),{ifAvailable:!0},async f=>{f&&await Nd(c,u)});return e.signal.throwIfAborted(),c.getDirectoryHandle(t,{create:!0})});e.signal.throwIfAborted(),n(d),await a}catch(d){i(d)}finally{e.signal.removeEventListener("abort",s),c&&await Nd(c,t).catch(()=>{})}}).catch(i),o.catch(()=>{}),o}async function Nd(e,t){for(let r=0;;r++)try{await e.removeEntry(t,{recursive:!0});return}catch(n){if(n instanceof DOMException&&n.name==="NotFoundError")return;if(!(n instanceof DOMException)||n.name!=="NoModificationAllowedError"||r>=4)throw n;await new Promise(i=>setTimeout(i,25*(r+1)))}}const No=8*1024*1024,ND=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),MD="/__hb_sdk__/game-save-download",Fe=(e,t)=>({code:e,message:t});function bD(e){const t=e.getRoot??(navigator.storage?.getDirectory?()=>navigator.storage.getDirectory():void 0),r=e.locks??navigator.locks,n=e.supportsWritable??(typeof FileSystemFileHandle<"u"&&typeof FileSystemFileHandle.prototype.createWritable=="function");if(!t||!r||!n)return;const i=DD({getRoot:t,locks:r,signal:e.signal}),o=new WeakMap,s=new WeakSet,a=m=>{m.signal.throwIfAborted(),m.lifecycle!=="cleanup"&&e.signal.throwIfAborted()},c=()=>i;function d(m){if(!/^\.hb-game-saves\/[a-zA-Z0-9_-]+\.zip$/.test(m))throw Fe("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存");return m.slice(15)}async function u(m,E){a(E);const N=d(m);try{return await(await c()).getFileHandle(N)}catch(A){throw A instanceof DOMException&&A.name==="NotFoundError"?Fe("FILE_NOT_FOUND","存档缓存不存在"):A}}function l(m){const E={kind:"file",mode:"readwrite",name:m.split("/").at(-1),async create(N,A){a(A);const R=d(m),y=await c();if(N.exclusive)try{throw await y.getFileHandle(R),Fe("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(T){if(!(T instanceof DOMException&&T.name==="NotFoundError"))throw T}a(A),await y.getFileHandle(R,{create:!0}),a(A)},async remove(N){a(N);const A=d(m);if(i)try{await(await i).removeEntry(A)}catch(R){if(!(R instanceof DOMException&&R.name==="NotFoundError"))throw R}},async read(N){const A=await(await u(m,N)).getFile();if(A.size>No)throw Fe("FILE_TOO_LARGE","存档文件超过 8 MiB");const R=new Uint8Array(await A.arrayBuffer());try{return a(N),R}catch(y){throw R.fill(0),y}},async write(){throw Fe("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(N){const A=await(await u(m,N)).getFile();return a(N),{kind:"file",size:A.size,modifiedAt:A.lastModified}}};return o.set(E,m),E}const f=async()=>{throw Fe("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},h={kind:"directory",mode:"readwrite",name:"",file:l,directory(m){return{...h,name:m,async create(E,N){if(a(N),m!==".hb-game-saves")return f();await c(),a(N)}}},create:f,stat:f,list:f};return{files:{sandbox:h},transfer:{network:{async open(m,E){if(a(E),!gu(m))throw Fe("METHOD_FORBIDDEN","仅支持受控存档下载");const N=await(e.fetch??fetch)(MD,{method:"POST",credentials:"same-origin",redirect:"error",headers:{"content-type":"application/json","x-hb-sdk-csrf":e.csrfToken()},body:JSON.stringify(m),signal:AbortSignal.any([E.signal,e.signal,AbortSignal.timeout(6e4)])});if(!N.ok){const A=await N.json().catch(()=>({}));throw Fe(A.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return s.add(N),{status:N.status,headers:Object.fromEntries(Array.from(N.headers).filter(([A])=>ND.has(A)).map(([A,R])=>[A,[R]])),body:N}},async release(m){s.delete(m),await m.body?.cancel()}},files:{async writeResource(m,E,N,A){let R,y;try{a(A);const T=o.get(m);if(!T||!s.delete(E))throw Fe("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(N.mode!=="replace-existing")throw Fe("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(R=await(await u(T,A)).createWritable(),!E.body)throw Fe("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");y=E.body.getReader();let I=0;for(;;){a(A);const _=await y.read().catch(w=>{throw a(A),Fe(w instanceof DOMException&&w.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(a(A),_.done)break;if(I+=_.value.byteLength,I>Math.min(N.maxBytes??No,No))throw Fe("FILE_TOO_LARGE","存档文件超过 8 MiB");await R.write(new Uint8Array(_.value)),A.onProgress(I)}if(N.expectedBytes!==void 0&&I!==N.expectedBytes)throw Fe("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return a(A),await R.close(),R=void 0,{committedBytes:I}}catch(T){throw T instanceof DOMException&&T.name==="QuotaExceededError"?Fe("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):T}finally{await y?.cancel().catch(()=>{}),y||await E.body?.cancel().catch(()=>{}),await R?.abort().catch(()=>{}),s.delete(E)}}}}}}function ht(e,t){throw{code:e,message:t}}function SD(e){const t=e.now??Date.now;let r;const n=new Map,i=()=>{r=void 0};e.signal.addEventListener("abort",i,{once:!0});function o(){if(e.signal.aborted)throw new DOMException("调试会话已结束","AbortError");const a=e.readState();a.userId||(i(),ht("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:c,browser:d}=a,u=Cg(c.developmentSnapshot);(c.source!=="remote"||!c.miniProgramId||!c.localDevLaunchToken||!c.expiresAt||c.expiresAt<=t()||!u||!c.developmentSnapshotDigest||!/^[a-f0-9]{64}$/.test(c.developmentSnapshotDigest))&&(i(),ht("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态")),(d.source!=="remote"||d.miniProgramId!==c.miniProgramId||d.devSessionId!==u.session_id||d.contextRevision!==u.revision||c.devSessionId!==u.session_id||c.contextRevision!==u.revision)&&(i(),ht("AUTHORIZATION_CONTEXT_CHANGED","开发快照正在更新,请稍后重试"));const l={mini_program_id:c.miniProgramId,launch_kind:"remote-dev",version_identity:`dev:${u.session_id}:${u.revision}`,sdk_version:u.sdk_version,local_dev_launch_token:c.localDevLaunchToken,dev_snapshot_digest:c.developmentSnapshotDigest,dev_network_enabled:a.networkEnabled};return{body:l,key:JSON.stringify([a.userId,a.accountRevision,l]),expiresAt:c.expiresAt}}async function s(a,c){const d=c.signal;let u;try{u=await e.request({source:"runtime-private",credentials:"heybox-session",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:"heybox.user_miniprogram.runtime.auth.context.post",path:"/user_miniprogram/runtime/auth/context",channel:"api"},method:"POST",bodyEncoding:"form",data:a.body,timeout:1e4},c)}catch(E){d.throwIfAborted();const N=E&&typeof E=="object"&&"code"in E?String(E.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(N)&&ht("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(N)||E instanceof DOMException&&["AbortError","TimeoutError"].includes(E.name))throw E;ht("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted(),o().key!==a.key&&ht("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const l=u.data;(u.status===401||l?.status==="login"||l?.status==="relogin")&&ht("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(u.status!==200||l?.status!=="ok")&&ht("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const f=l.result,h=Number(f?.expires_at)*1e3;(typeof f?.token!="string"||!f.token.trim()||!Number.isSafeInteger(f?.expires_at)||!Number.isSafeInteger(h)||h<=t()||!["legacy","local","server"].includes(String(f.user_data_mode)))&&ht("INVALID_RESPONSE","开发运行授权响应无效");const m={token:f.token,expiresAt:Math.min(h,a.expiresAt),steamAccount:f.steam_account===!0,userDataMode:f.user_data_mode};return r={key:a.key,value:m},m}return{async get(a){const c=AbortSignal.any([a.signal,e.signal]);c.throwIfAborted(),await e.refreshAccount(c),c.throwIfAborted();const d=o();if(r?.key===d.key&&r.value.expiresAt>t()+3e4)return r.value;i();let u=n.get(d.key);if(!u||u.controller.signal.aborted){const f=new AbortController,h=s(d,{...a,signal:AbortSignal.any([f.signal,e.signal])});u={promise:h,controller:f,users:0},n.set(d.key,u);const m=u;h.finally(()=>{n.get(d.key)===m&&n.delete(d.key)}).catch(()=>{})}u.users++;let l;try{const f=await Promise.race([u.promise,new Promise((h,m)=>{l=()=>m(c.reason),c.addEventListener("abort",l,{once:!0}),c.aborted&&l()})]);return c.throwIfAborted(),o().key!==d.key&&ht("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),f}finally{c.removeEventListener("abort",l),--u.users===0&&u.controller.abort()}}}}const TD="/__hb_sdk__/dev-context";function Md(e,t){return on(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId:void 0,developmentSnapshot:typeof e.developmentSnapshot=="string"?e.developmentSnapshot:void 0,developmentSnapshotDigest:typeof e.developmentSnapshotDigest=="string"?e.developmentSnapshotDigest:void 0,localDevLaunchToken:typeof e.localDevLaunchToken=="string"?e.localDevLaunchToken:void 0,runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,publishedRuntimePermissions:e.publishedRuntimePermissions,warning:typeof e.warning=="string"?e.warning:void 0,declaredPermissions:on(e.declaredPermissions)?e.declaredPermissions:void 0,platforms:Array.isArray(e.platforms)?e.platforms.filter(r=>["android","ios","ohos","windows","macos","linux"].includes(String(r))):void 0,localDevGrant:e.localDevGrant,contextRevision:typeof e.contextRevision=="number"?e.contextRevision:void 0,devSessionId:typeof e.devSessionId=="string"?e.devSessionId:void 0,expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0,companionManifestSha256:typeof e.companionManifestSha256=="string"?e.companionManifestSha256:void 0}:{source:"anonymous",runtimePermissions:t}}function Kr(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Tu(e.localDevGrant);return!r.valid||!e.devSessionId?.trim()||!Number.isSafeInteger(e.contextRevision)||e.contextRevision!==r.grant.revision||!e.expiresAt||!Number.isFinite(e.expiresAt)||e.source!=="remote"&&e.expiresAt<=t?{...e,localDevGrant:void 0,warning:"本地临时授权无效或已过期,已降权"}:{...e,...e.expiresAt<=t?{source:"anonymous",localDevLaunchToken:void 0,expiresAt:t+3e4}:{},localDevGrant:Fh({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,revision:r.grant.revision,eligiblePermissionKeys:e.platforms?.some(n=>["windows","macos","linux"].includes(n))?["network","companion","appProtocol"]:["network","appProtocol"]})}}function OD(e){if(!on(e)||!bd(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!on(t)||!bd(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const vD={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Ni(e){const t=Ve(e.localDevGrant?_s({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}).runtimePermissions:e.runtimePermissions),r=t.permissions.network;return t.valid&&r?{networkRequest:{status:r.status,useOfficialDomain:r.config.useOfficialDomain===!0}}:RD()}function uf(e,t,r){return r?.localDevGrant?_s({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:lf(e,t,t.networkRequest.useOfficialDomain)}function PD(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=Ni({...e,localDevGrant:void 0});return lf(e.runtimePermissions,t,!1)}function RD(){return{networkRequest:{...vD.networkRequest}}}function lf(e,t,r){const n=Ve(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of Zt){const a=n.permissions[s];a&&i.push(s==="network"?{key:s,status:t.networkRequest.status,config:{useOfficialDomain:r}}:s==="user_game_data"?{key:s,status:a.status,config:{resources:a.config.resources}}:{key:s,status:a.status,config:{}})}const o=on(e)&&typeof e.revision=="number"&&Number.isInteger(e.revision)&&e.revision>=0?e.revision:void 0;return{schema_version:1,...o===void 0?{}:{revision:o},entries:i}}function on(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function bd(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function CD(e){let t,r=!1,n=!1,i;return{invalidate(a){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(a,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=o().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function o(){let a={ok:!0};for(;r&&!n;){r=!1;const c=new AbortController;t=c;let d;try{d=await e.fetch(c.signal)}catch(l){a={ok:!1},!n&&!c.signal.aborted&&s(l);continue}finally{t===c&&(t=void 0)}if(n)return{ok:!1};let u;try{u=e.apply(d)}catch(l){a={ok:!1},n||s(l);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(u))try{await e.onChanged(u)}catch(l){a={ok:!1},n||s(l)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function kD(e){return CD({apply:e.applyStatus,fetch:e.fetchStatus,hasChanged:t=>t.changed,onChanged:t=>e.reconcile(t.status),onError:e.onError,shouldSkip:t=>t!==void 0&&t<=e.getCanonicalRevision()})}function LD(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,o;return{schedule:s,reset(){n=t,a()},dispose(){i||(i=!0,a())}};function s(){i||e.isDisposed()||(a(),o=e.timers.setTimeout(async()=>{o=void 0;let c;try{c=await e.invalidate()}catch{c={ok:!1}}if(!(i||e.isDisposed())){if(c.ok){n=t,e.connectEvents();return}n=Math.min(n*2,r),s()}},n))}function a(){o!==void 0&&e.timers.clearTimeout(o),o=void 0}}const Mo=new WeakMap;function zs(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}const{root:n,signal:i}=e;Mo.set(n,document.activeElement);const o=[...n.querySelectorAll("button[data-action]")];n.dataset.hostDialog="true",n.style.zIndex="40";const s=()=>[...document.querySelectorAll("[data-host-dialog]")].at(-1);n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-label",e.title);let a;const c=()=>{i?.removeEventListener("abort",u),document.removeEventListener("keydown",f);const m=s()===n;if(n.remove(),m){const E=s();E&&(E.inert=!1,E.removeAttribute("aria-hidden"));let N=Mo.get(n)??null;for(;N instanceof HTMLElement&&!N.isConnected;){const A=N.closest("[data-host-dialog]");N=A?Mo.get(A)??null:null}N instanceof HTMLElement&&(!E||E.contains(N))?N.focus():E?.querySelector("button")?.focus()}},d=Bm({kind:"dialog",mode:e.mode??"simulated",title:e.title,method:e.method,...e.callId?{callId:e.callId}:{},actions:o.map(m=>m.textContent?.trim()??"")},m=>{c(),a!==void 0?t(a):r(i?.reason??new DOMException(`宿主弹窗已${m}`,"AbortError"))});function u(){d.finish("cancelled")}function l(m){a=m,d.finish(m===e.cancelAction?"cancelled":"confirmed")}function f(m){if(s()!==n||(m.key==="Escape"&&e.cancelAction&&(m.preventDefault(),l(e.cancelAction)),m.key!=="Tab"||o.length===0))return;const E=o[0],N=o.at(-1);m.shiftKey&&document.activeElement===E?(m.preventDefault(),N.focus()):!m.shiftKey&&document.activeElement===N&&(m.preventDefault(),E.focus())}if(!d.active)return;if(i?.aborted){u();return}for(const m of o)m.addEventListener("click",()=>l(m.dataset.action));n.addEventListener("click",m=>{m.target===n&&e.cancelAction&&l(e.cancelAction)}),n.dataset.interactionId=d.interactionId;const h=s();h&&(h.inert=!0,h.setAttribute("aria-hidden","true")),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n),i?.addEventListener("abort",u,{once:!0}),document.addEventListener("keydown",f),o[0]?.focus(),i?.aborted&&u()})}function Xe(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}const Sd="hb-sdk-action-dialog-style";async function Mi(e){await ff(e)}async function xD(e){return await ff({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function ff(e){HD();const t=document.createElement("div");return t.className="hb-sdk-action-dialog",t.innerHTML=`
17
- <div class="hb-sdk-action-dialog__panel">
18
- <h2>${Xe(e.title)}</h2>
19
- <pre class="hb-sdk-action-dialog__detail">${Xe(e.detail)}</pre>
20
- <div class="hb-sdk-action-dialog__actions">
21
- ${e.confirmation?'<button type="button" data-action="cancel">取消</button>':""}
22
- <button type="button" class="primary" data-action="confirm">${e.confirmation?"关注":"确定"}</button>
23
- </div>
24
- </div>`,await zs({root:t,title:e.title,method:e.method??"host.action",signal:e.signal,callId:e.callId,mode:e.mode,...e.confirmation?{cancelAction:"cancel"}:{}})==="confirm"}async function UD(e,t){await Mi({method:"navigation.openAppPage",title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+Mr(e.params)].join(`
25
- `),signal:t.signal,callId:t.requestId})}async function jD(e,t){await Mi({method:"navigation.openAppPage",title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+Mr(e.extra)].join(`
26
- `),signal:t.signal,callId:t.requestId})}async function zD(e,t){await Mi({method:"share.showShareMenu",title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+Mr(e.channel),"post: "+Mr(e.post)].join(`
27
- `),signal:t.signal,callId:t.requestId})}async function BD(e,t){await Mi({method:"share.screenshot",title:"截图分享",detail:["rect: "+Mr(e.rect),"post: "+Mr(e.post)].join(`
28
- `),signal:t.signal,callId:t.requestId})}function Mr(e){return JSON.stringify(e,null,2)}function HD(){if(document.getElementById(Sd))return;const e=document.createElement("style");e.id=Sd,e.textContent=`
29
- .hb-sdk-action-dialog {
30
- position: absolute;
31
- inset: 0;
32
- display: grid;
33
- place-items: center;
34
- padding: 24px;
35
- background: rgba(15, 23, 42, 0.45);
36
- }
37
-
38
- .hb-sdk-action-dialog__panel {
39
- width: min(420px, 100%);
40
- border-radius: 12px;
41
- padding: 20px;
42
- background: #fff;
43
- box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
44
- }
45
-
46
- .hb-sdk-action-dialog__panel h2 {
47
- margin: 0 0 8px;
48
- font-size: 18px;
49
- }
50
-
51
- .hb-sdk-action-dialog__detail {
52
- margin: 0 0 16px;
53
- max-height: 40vh;
54
- overflow: auto;
55
- color: #1f2933;
56
- font-family: inherit;
57
- font-size: 12px;
58
- line-height: 1.6;
59
- white-space: pre-wrap;
60
- overflow-wrap: anywhere;
61
- word-break: break-word;
62
- }
63
-
64
- .hb-sdk-action-dialog__actions {
65
- display: flex;
66
- justify-content: flex-end;
67
- gap: 8px;
68
- }
69
-
70
- .hb-sdk-action-dialog__actions button {
71
- min-height: 36px;
72
- border: 1px solid #cad5e2;
73
- border-radius: 6px;
74
- padding: 0 12px;
75
- background: #fff;
76
- cursor: pointer;
77
- }
78
-
79
- .hb-sdk-action-dialog__actions .primary {
80
- border-color: #2563eb;
81
- color: #fff;
82
- background: #2563eb;
83
- }
84
- `,document.head.appendChild(e)}const FD={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};async function $D(e){const t=document.createElement("div");return t.className="hb-sdk-auth-dialog",t.innerHTML=`
85
- <div class="hb-sdk-auth-dialog__panel">
86
- <h2>授权请求</h2>
87
- <p class="hb-sdk-auth-dialog__app">${Xe(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
88
- <ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(n=>`<li>${Xe(FD[n]||n)}</li>`).join("")}</ul>
89
- ${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${Xe(e.userProfile.nickname)}</p>`:""}
90
- <div class="hb-sdk-auth-dialog__actions">
91
- <button type="button" data-action="deny">拒绝</button>
92
- <button type="button" class="primary" data-action="allow">允许</button>
93
- </div>
94
- </div>
95
- `,await zs({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function VD(e){const t=e.miniProgramName?.trim();return{launchUrl:e.launchUrl,...e.locationBasePath!==void 0?{locationBasePath:e.locationBasePath}:{},...t?{miniProgramPresentation:{name:t}}:{},sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:ia,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:Di},sdkVersion:ia},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const Td="hb-sdk-user-data-dialog-style",GD=new Map(Cn.map(e=>[e.key,e.name]));function QD(e){return(bt(e)?GD.get(e):void 0)??"游戏资料"}function qD(e){return e==="upload"?"可上传":"无网络权限"}async function YD(e){ZD();const t=e.miniProgramName?.trim()||"当前小程序",r=QD(e.resource),n=`“${t}”想读取你的${r}`,i=qD(e.egress),o=Hm[e.egress],s=e.egress==="upload"?"↑":"⊘",a=document.createElement("div");a.className="hb-sdk-user-data-dialog",a.innerHTML=`
96
- <div class="hb-sdk-user-data-dialog__panel">
97
- <h2>${Xe(n)}</h2>
98
- <dl class="hb-sdk-user-data-dialog__meta">
99
- <dt>范围</dt><dd>${Xe(e.scopeText)}</dd>
100
- <dt>用途</dt><dd>${Xe(e.purposeText)}</dd>
101
- </dl>
102
- <p class="hb-sdk-user-data-dialog__egress" data-egress="${Xe(e.egress)}">
103
- <span class="hb-sdk-user-data-dialog__egress-label" aria-hidden="true">${Xe(s)}</span>
104
- <span class="hb-sdk-user-data-dialog__egress-tag">${Xe(i)}</span>
105
- <span>${Xe(o)}</span>
106
- </p>
107
- <p class="hb-sdk-user-data-dialog__mock-note">Browser Mock:不会写入真实设备许可,也不会触发来源登录。</p>
108
- <div class="hb-sdk-user-data-dialog__actions">
109
- <button type="button" data-action="deny">拒绝</button>
110
- <button type="button" data-action="session">本次使用允许</button>
111
- ${e.canPersist===!1?"":'<button type="button" class="primary" data-action="persistent">在此设备上始终允许</button>'}
112
- </div>
113
- </div>
114
- `;const c=await zs({root:a,title:n,method:"user.dataPermission.confirm",mode:"browser",signal:e.signal,cancelAction:"cancelled"});return{decision:WD(c)}}function WD(e){return e==="deny"||e==="session"||e==="persistent"?e:"cancelled"}function ZD(){if(document.getElementById(Td))return;const e=document.createElement("style");e.id=Td,e.textContent=`
115
- .hb-sdk-user-data-dialog {
116
- position: absolute;
117
- inset: 0;
118
- display: grid;
119
- place-items: center;
120
- padding: 24px;
121
- background: rgba(15, 23, 42, 0.45);
122
- }
123
-
124
- .hb-sdk-user-data-dialog__panel {
125
- width: min(440px, 100%);
126
- border-radius: 12px;
127
- padding: 20px;
128
- background: #fff;
129
- box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
130
- }
131
-
132
- .hb-sdk-user-data-dialog__panel h2 {
133
- margin: 0 0 12px;
134
- font-size: 17px;
135
- line-height: 1.45;
136
- color: #1f2933;
137
- overflow-wrap: anywhere;
138
- }
139
-
140
- .hb-sdk-user-data-dialog__meta {
141
- display: grid;
142
- grid-template-columns: auto 1fr;
143
- gap: 4px 10px;
144
- margin: 0 0 12px;
145
- font-size: 12px;
146
- line-height: 1.6;
147
- }
148
-
149
- .hb-sdk-user-data-dialog__meta dt {
150
- color: #7b8794;
151
- white-space: nowrap;
152
- }
153
-
154
- .hb-sdk-user-data-dialog__meta dd {
155
- white-space: pre-wrap;
156
- margin: 0;
157
- color: #1f2933;
158
- overflow-wrap: anywhere;
159
- }
160
-
161
- .hb-sdk-user-data-dialog__egress {
162
- display: flex;
163
- flex-wrap: wrap;
164
- align-items: baseline;
165
- gap: 6px;
166
- margin: 0 0 10px;
167
- padding: 10px 12px;
168
- border: 1px solid #cad5e2;
169
- border-radius: 8px;
170
- font-size: 12px;
171
- line-height: 1.6;
172
- color: #1f2933;
173
- }
174
-
175
- .hb-sdk-user-data-dialog__egress[data-egress="upload"] {
176
- border-color: #e0b34d;
177
- background: #fff8e6;
178
- }
179
-
180
- .hb-sdk-user-data-dialog__egress[data-egress="no_network"] {
181
- border-color: #9fb3c8;
182
- background: #f2f6fa;
183
- }
184
-
185
- .hb-sdk-user-data-dialog__egress-label {
186
- font-weight: 700;
187
- }
188
-
189
- .hb-sdk-user-data-dialog__egress-tag {
190
- font-weight: 700;
191
- white-space: nowrap;
192
- }
193
-
194
- .hb-sdk-user-data-dialog__mock-note {
195
- margin: 0 0 16px;
196
- font-size: 11px;
197
- line-height: 1.6;
198
- color: #7b8794;
199
- }
200
-
201
- .hb-sdk-user-data-dialog__actions {
202
- display: flex;
203
- flex-wrap: wrap;
204
- justify-content: flex-end;
205
- gap: 8px;
206
- }
207
-
208
- .hb-sdk-user-data-dialog__actions button {
209
- min-height: 36px;
210
- border: 1px solid #cad5e2;
211
- border-radius: 6px;
212
- padding: 0 12px;
213
- background: #fff;
214
- color: #1f2933;
215
- cursor: pointer;
216
- }
217
-
218
- .hb-sdk-user-data-dialog__actions .primary {
219
- border-color: #2563eb;
220
- color: #fff;
221
- background: #2563eb;
222
- }
223
- `,document.head.appendChild(e)}function KD(e){const t=Ve(e.runtimePermissions);let r={};return t.valid&&t.permissions.user_game_data?.status==="enabled"?r=tn(t.permissions.user_game_data.config.resources):e.runtimePermissions===void 0&&e.declaredPermissions?.user_game_data?.enabled&&(r=tn(e.declaredPermissions.user_game_data.resources)),{resources:zh(r),source:"manifest"}}function JD(e){return async t=>{if(t.source!=="runtime-private"||t.target.kind!=="heybox-api"||!t.target.path.startsWith("/user_miniprogram/runtime/user_game_data/"))return;const r=t.data,n=typeof r?.resource=="string"?hi(r.resource):void 0;if(!n)return{status:400,headers:{},data:{status:"failed",result:{error_code:"USER_GAME_DATA_TARGET_UNSUPPORTED"}}};const i=r?.operation==="list"?"list":"get",o=e();if(["source_invalid","source_link_required","user_login"].includes(o))return{status:400,headers:{},data:{status:"failed",result:{error_code:o==="source_invalid"?"USER_DATA_SOURCE_LOGIN_REQUIRED":"USER_DATA_SOURCE_NOT_LINKED",message:"Mock 来源条件尚未满足"}}};if(o==="failed"||o==="unavailable"||o==="unknown")return{status:503,headers:{},data:{status:"failed",result:{error_code:o==="failed"?"UPSTREAM_FAILED":"REQUEST_UNSUPPORTED",message:"Mock 数据源不可用"}}};const s=t.target.path.split("/").at(-1);if(s==="sync"||s==="sync_status")return{status:200,headers:{},data:{status:"ok",result:{task_id:"mock-task",state:s==="sync"?"syncing":"succeeded"}}};if(s==="file")return{status:400,headers:{},data:{status:"failed",result:{error_code:"FILE_NOT_FOUND",message:"Mock 列表没有可下载文件"}}};const a=n.queries[i];if(!a)return{status:400,headers:{},data:{status:"failed",result:{error_code:"REQUEST_UNSUPPORTED"}}};const c=o==="no_data"||o==="updating"?{status:"empty",reason:o==="no_data"?"no_data":"not_ready",message:"Mock 资料尚未就绪"}:{status:"ready",data:qg(a.schema)};return{status:200,headers:{},data:{status:"ok",result:{...c,resource:n.key,operation:i,schema_version:a.version,disclosure_revision:n.disclosureRevision}}}}}const mf=5,XD=50,hf=Object.freeze({user_game_data_permission_show:["entry","reason"],user_game_data_permission_result:["choice","apply_result"],user_game_data_permission_manage:["operation","apply_result","succeeded_count","failed_count"],user_game_data_action:["stage","action_type","outcome","duration_ms"],user_game_data_access_result:["api","trigger","status","error_code","failure_stage","duration_ms","cache_hit"]}),eN="host.userDataTelemetry",Od=80;function tN(e={}){const t=Math.max(1,Math.floor(e.limit??XD)),r=e.now??Date.now,n=new Set;let i=[],o=0;function s(){const c=a();for(const d of[...n])try{d(c)}catch{}}function a(){return[...i].reverse()}return{record(c){if(typeof c?.name!="string"||typeof c.payload!="object"||c.payload===null)return;const d=Object.freeze({sequence:++o,name:c.name,payload:Object.freeze({...c.payload}),timestamp:r(),summary:rN(c)});i=[...i,d],i.length>t&&(i=i.slice(i.length-t)),s()},recent(c){const d=Math.max(0,Math.floor(c??mf));return a().slice(0,d)},entries:a,subscribe(c){return n.add(c),()=>n.delete(c)},clear(){i.length!==0&&(i=[],s())}}}function rN(e){const t=hf[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}=${Bs(i)}`)}return[e.name,...r].join(" · ")}function nN(e){return{method:eN,detail:{...e.payload,eventName:e.name,message:iN(e)}}}function iN(e){const t=hf[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}: ${Bs(i)}`)}return[e.name,...r].join(" · ")}function Bs(e){let t;if(typeof e=="string")t=e;else if(typeof e=="number"||typeof e=="boolean")t=String(e);else if(Array.isArray(e))t=e.map(r=>Bs(r)).join(",");else try{t=JSON.stringify(e)??""}catch{t="[无法序列化]"}return t.length>Od?`${t.slice(0,Od)}…`:t}const oN=44;function sN(e){const t=()=>e.isCapsuleHidden?.()?0:oN,r=()=>{const n=e.getDeviceMetrics?.();return n?{windowWidth:n.screenWidth,windowHeight:n.screenHeight,screenWidth:n.screenWidth,screenHeight:n.screenHeight,pixelRatio:n.pixelRatio,safeArea:{top:n.safeAreaInsets.top+t(),right:n.screenWidth-n.safeAreaInsets.right,bottom:n.screenHeight-n.safeAreaInsets.bottom,left:n.safeAreaInsets.left}}:{windowWidth:window.innerWidth,windowHeight:window.innerHeight,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}};return{...e.applyDisplay?{applyOrientation:async(n,i)=>(await e.applyDisplay(n,i.signal),{supported:!0})}:{},...e.onViewportChange?{onViewportChange:e.onViewportChange}:{},close:async()=>{await e.close()},reload:async()=>{await e.reload()},getViewportMetrics:()=>e.getViewportMetrics?.()??r(),getNavigationBarHeight:()=>{if(e.getNavigationBarHeight)return e.getNavigationBarHeight();const n=e.getDeviceMetrics?.().statusBarHeight;return n===void 0?0:n+t()},setNavigationBarStyle:n=>{document.documentElement.dataset.navigationBarStyle=n,e.onNavigationBarStyleChange?.(n)},setClipboard:async({text:n})=>{await navigator.clipboard.writeText(n)},showToast:Qm,showLoading:Gm,hideLoading:Vm,vibrate:$m,openAppPage:UD,openWindow:jD,showShareMenu:zD,captureAndShare:BD,setScreenshotChromeHidden:Fm}}const vd=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],vn=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Pd={"launch-only":[],stdio:["stdio"],full:["stdio","attachments","notifications"],"prepare-fail":[],"prepare-cancel":[],"launch-cancel":[],"os-blocked":[],"normal-exit":["stdio"],crash:["stdio"],"output-limit":["stdio"]};class aN{port;presentation;now;schedule;clearSchedule;onDiagnostic;preparations=new Map;sessions=new Map;eventSink;sessionEventListeners=new Set;nextSessionId=0;constructor(t={}){this.now=t.now??Date.now,this.schedule=t.schedule??((r,n)=>setTimeout(r,n)),this.clearSchedule=t.clearSchedule??(r=>clearTimeout(r)),this.onDiagnostic=t.onDiagnostic??(()=>{}),this.port={getInfo:async r=>this.getInfo(r),getPreparationStatus:async r=>this.getPreparationStatus(r),prepare:(r,n)=>this.prepare(r,n),cancelPreparation:async r=>this.cancelPreparation(r),getActiveSession:async r=>this.getActiveSession(r),launch:async r=>this.launch(r),write:async r=>this.write(r),closeStdin:async r=>this.closeStdin(r),terminate:async r=>this.terminate(r),ackOutput:async r=>this.ackOutput(r),openAttachment:async r=>this.openAttachment(r),showNotification:async r=>this.showNotification(r),onSessionEvent:r=>(this.sessionEventListeners.add(r),()=>this.sessionEventListeners.delete(r))},this.presentation={confirmCompanionOperation:async({action:r,companion:n})=>{const i=n.alias===`${r}-cancel`;return this.diagnostic(`authorization.${i?"cancelled":"granted"}`,n.alias,{action:r}),i?{status:"cancelled"}:{status:"granted"}}}}bindEventSink(t){this.eventSink=t,this.diagnostic(t?"runtime.connected":"runtime.disconnected")}reset(t){const r=t?[t]:[...vd];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(ze("COMPANION_PREPARATION_CANCELLED","固定 Fake 已重置")),this.preparations.delete(n),this.sessions.delete(n)}this.diagnostic("reset",t)}getInfo(t){const r=this.readAlias(t);return{alias:r,displayName:`Browser Fake: ${r}`,target:r==="os-blocked"?"macos-arm64":"windows-x64",capabilities:Pd[r],archiveBytes:12,signatureStatus:"unsigned"}}getPreparationStatus(t){const r=this.readAlias(t);return this.preparations.get(r)?.status??{state:"not-prepared"}}prepare(t,r){const n=this.readAlias(t),i=this.preparations.get(n);if(i?.status.state==="ready")return Promise.resolve(this.getInfo(n));if(i?.operation)return i.operation.listeners.add(r.onProgress),this.diagnostic("prepare.joined",n),r.onProgress(i.status.state==="preparing"?i.status.progress:vn[0]),i.operation.promise;let o,s;const a=new Promise((d,u)=>{o=d,s=u}),c={cancelled:!1,listeners:new Set([r.onProgress]),promise:a,reject:s,resolve:o,timers:new Set};{const d={status:{state:"preparing",progress:vn[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),vn.forEach((u,l)=>{const f=this.schedule(()=>{if(c.timers.delete(f),!c.cancelled){d.status={state:"preparing",progress:u};try{c.listeners.forEach(h=>h(u))}catch(h){c.cancelled=!0;for(const m of c.timers)this.clearSchedule(m);d.operation=void 0,d.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",n,{message:h instanceof Error?h.message:String(h)}),c.reject(h);return}if(this.diagnostic("prepare.progress",n,{phase:u.phase}),l===vn.length-1){if(d.operation=void 0,n==="prepare-fail"){d.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},c.reject(ze("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",n,{code:"COMPANION_INTEGRITY_FAILED"});return}d.status={state:"ready",preparedAt:this.now()},c.resolve(this.getInfo(n)),this.diagnostic("prepare.ready",n)}}},l+1);c.timers.add(f)})}return a}cancelPreparation(t){const r=this.readAlias(t),n=this.preparations.get(r);if(n?.operation){n.operation.cancelled=!0;for(const i of n.operation.timers)this.clearSchedule(i);n.operation.reject(ze("COMPANION_PREPARATION_CANCELLED","准备已取消")),n.operation=void 0,n.status={state:"not-prepared"},this.diagnostic("prepare.cancelled",r)}}getActiveSession(t){const r=this.readAlias(t),n=this.sessions.get(r);if(!n||n.exited)return;const i=n.snapshot.controllerGeneration;return n.snapshot={...n.snapshot,controllerGeneration:i+1},this.emit(Dh,{sessionId:n.snapshot.id,controllerGeneration:i}),n.waitingOutput&&(n.queuedOutput.unshift(n.waitingOutput),n.waitingOutput=void 0,this.flushOutput(n)),this.diagnostic("session.controller-transferred",r,{controllerGeneration:n.snapshot.controllerGeneration}),{...n.snapshot,capabilities:[...n.snapshot.capabilities]}}launch(t){const r=this.readAlias(t);if(this.getPreparationStatus(r).state!=="ready")throw ze("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw ze("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw ze("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:Pd[r],state:"running",controllerGeneration:1},o={snapshot:i,stdinClosed:!1,exited:!1,queuedOutput:[]};return this.sessions.set(r,o),this.diagnostic("session.launched",r,{capabilities:[...i.capabilities],sessionId:i.id}),i.capabilities.includes("stdio")&&this.schedule(()=>{this.queueOutput(o,"stdout",1,`fake:ready
224
- `),this.queueOutput(o,"stderr",1,`fake:diagnostic
225
- `)},20),r==="normal-exit"&&this.schedule(()=>this.requestExit(o,{reason:"exited",exitCode:0}),40),r==="crash"&&this.schedule(()=>this.requestExit(o,{reason:"crashed",exitCode:1}),40),r==="output-limit"&&this.schedule(()=>this.requestExit(o,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("stdio"))throw ze("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw ze("COMPANION_PIPE_CLOSED","stdin 已关闭");const n=Math.max(1,...r.queuedOutput.map(i=>i.sequence),r.waitingOutput?.sequence??0)+1;this.queueOutput(r,"stdout",n,new Uint8Array(t.data)),this.diagnostic("stdio.write",r.snapshot.alias,{bytes:t.data.byteLength})}closeStdin(t){const r=this.readController(t);r.stdinClosed=!0,this.diagnostic("stdio.closed",r.snapshot.alias)}terminate(t){const r=this.readController(t);this.exit(r,{reason:"terminated"})}ackOutput(t){const r=this.readController(t),n=r.waitingOutput;!n||n.stream!==t.stream||n.sequence!==t.sequence||(r.waitingOutput=void 0,this.diagnostic("stdio.ack",r.snapshot.alias,{sequence:t.sequence,stream:t.stream}),this.flushOutput(r))}openAttachment(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("attachments"))throw ze("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw ze("COMPANION_ATTACHMENT_NOT_FOUND","固定 Fake Attachment 不存在");this.diagnostic("attachment.opened",r.snapshot.alias,{id:t.id});const n=new TextEncoder().encode(`Browser Fake Companion report
226
- `);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw ze("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw ze("FILE_ACCESS_DENIED","Attachment 只读")},stat:async()=>({kind:"file",size:n.byteLength})}}showNotification(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("notifications"))throw ze("COMPANION_NOTIFICATION_UNAVAILABLE","notifications 未启用");this.diagnostic("notification.shown",r.snapshot.alias,{category:t.category})}queueOutput(t,r,n,i){t.queuedOutput.push({stream:r,sequence:n,data:typeof i=="string"?new TextEncoder().encode(i):i}),this.flushOutput(t)}flushOutput(t){if(t.exited||t.waitingOutput||!this.eventSink&&this.sessionEventListeners.size===0)return;const r=t.queuedOutput.shift();if(!r){t.pendingExit&&this.exit(t,t.pendingExit);return}t.waitingOutput=r,this.emit(_h,{sessionId:t.snapshot.id,controllerGeneration:t.snapshot.controllerGeneration,...r}),this.diagnostic("stdio.chunk",t.snapshot.alias,{bytes:r.data.byteLength,sequence:r.sequence,stream:r.stream})}requestExit(t,r){t.pendingExit=r,!t.waitingOutput&&t.queuedOutput.length===0&&this.exit(t,r)}exit(t,r){t.exited||(t.exited=!0,t.pendingExit=void 0,t.waitingOutput=void 0,t.queuedOutput.length=0,this.emit(Ah,{sessionId:t.snapshot.id,exit:r}),this.diagnostic("session.exit",t.snapshot.alias,{...r}))}readController(t){const r=[...this.sessions.values()].find(n=>n.snapshot.id===t.sessionId);if(!r||r.exited)throw ze("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw ze("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!vd.includes(t))throw ze("COMPANION_NOT_DECLARED","未知固定 Companion Fake 场景");return t}emit(t,r){this.eventSink?.(t,r),this.sessionEventListeners.forEach(n=>n({type:t,payload:r}))}diagnostic(t,r,n){this.onDiagnostic({action:t,...r?{alias:r}:{},...n?{detail:n}:{}})}}const cN=Object.freeze({[Jd]:!0,[Kd]:!0,[Zd]:!0,[Wd]:!0,[Yd]:!0,[qd]:!0,[Qd]:!0,[Gd]:!0,[Vd]:!0,[$d]:!0,[Fd]:!0,[Hd]:!0,[eu]:!0,[tu]:!0,[Xd]:!0});function dN(e){return new aN(e)}function ze(e,t){return Object.assign(new Error(t),{code:e})}const uN=/^[A-Za-z0-9_-]{22}$/,lN="https://api.xiaoheihe.cn/open_inapp/";function fN(e){const t=typeof e.port=="number"?e.port:Number(e.port);if(!Number.isInteger(t)||t<=0||t>65535)throw new TypeError("Mobile launch redirect port is invalid");if(!uN.test(e.token))throw new TypeError("Mobile launch redirect token is invalid");const r=new URL(`http://${e.host}:${t}/l/${e.token}`);if(r.protocol!=="http:"||r.hostname!==e.host||r.port!==String(t)||r.username||r.password||r.search||r.hash)throw new TypeError("Mobile launch redirect host is invalid");return r.href}function mN(e){const t=new URL(e);if(t.protocol!=="http:"||t.username||t.password)throw new TypeError("Mobile launch redirect URL must be an HTTP URL without credentials");const r=`heybox://${encodeURIComponent(JSON.stringify({protocol_type:"openWindow",full_screen:!0,navigation_bar:{title:""},webview:{url:t.href,pull:!1,refresh:!1}}))}`;return`${lN}#${r}`}function hN(e){const t=Ve(e.runtimePermissions),r=_s({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=Ve(e.publishedRuntimePermissions),o=Ve(r.runtimePermissions);for(const s of Is){const a=s.key,c={network:"Network",companion:"Companion",appProtocol:"AppProtocol"}[a]??s.name;if(!e.declaredPermissions?.[a]?.enabled)continue;const d=t.valid&&t.permissions[a]?.status==="enabled",u=r.temporaryPermissionKeys.some(l=>l===a);n.push({key:a,label:c,state:s.access==="declaration"?"declared":d?"approved":u?"temporary":"unavailable",facts:{platformApproval:s.access==="declaration"?null:d,temporary:u,effective:o.permissions[a]?.status==="enabled",online:i.valid?i.permissions[a]?.status??"missing":"unknown"},...u?{releaseDifference:"本次使用临时授权,发布后仍需平台批准。"}:i.valid&&!i.permissions[a]?{releaseDifference:"线上快照尚未包含该权限,需发布包含声明的新版本。"}:{},...a==="appProtocol"?{highestRisk:!0}:{},...s.access!=="declaration"&&!d&&!u?{reason:a==="appProtocol"?"最高危险权限:可执行任意协议并绕过其他 SDK 能力权限;当前没有有效临时授权,线上未批准":"没有有效的本地临时授权,线上未批准"}:{}})}if(e.declaredPermissions?.network?.useOfficialDomain){const s=t.valid&&t.permissions.network?.status==="enabled"&&t.permissions.network.config.useOfficialDomain===!0;n.push({key:"network.useOfficialDomain",label:"官方域名",state:s?"approved":"unavailable",...s?{}:{reason:"不支持本地临时授权,获得线上批准后才能使用"}})}return n}function Gt(e){return JSON.stringify({source:e.source,miniProgramId:e.miniProgramId,devSessionId:e.devSessionId,contextRevision:e.contextRevision,declaredPermissions:e.declaredPermissions,runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant,companionManifestSha256:e.companionManifestSha256})}const Rd="__hb_sdk_mini_dev_console_installed__",gN=["log","debug","info","warn","error"];function pN(e,t=console){if(t[Rd])return;let r=!1;for(const n of gN){const i=t[n];if(typeof i!="function")continue;const o=function(...s){try{e(n,s)}catch{}return i.apply(this,s)};try{t[n]=o,r=!0}catch{break}}r&&(t[Rd]=!0)}const Jo=1,Cd=64*1024,yN=64,EN=/^[A-Za-z0-9_-]{22}$/;class We extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function wN(e,t=!1){const r=_N(e,t);switch(Xo(r,"Server message"),AN(r),r.type){case"grant":return Jr(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),Xr(r.connectionEpoch,"connectionEpoch"),Qt(r.nextClientSequence,"nextClientSequence"),Qt(r.nextServerSequence,"nextServerSequence"),kd(r.snapshot),r;case"event":return Jr(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),Xr(r.connectionEpoch,"connectionEpoch"),Qt(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&xt("event must be account.changed or status.changed"),kd(r.snapshot),r;case"heartbeat":return Jr(r,["version","type","connectionEpoch","sequence"],"heartbeat"),Xr(r.connectionEpoch,"connectionEpoch"),Qt(r.sequence,"sequence"),r;default:return xt("Unknown server message type")}}function IN(e){const t=e.connectionEpoch;Xr(t,"connectionEpoch"),Qt(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(Xr(n.connectionEpoch,"connectionEpoch"),Qt(n.sequence,"sequence"),n.connectionEpoch!==t)throw new We("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new We("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new We("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function _N(e,t){if(t)throw new We("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new We("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Cd)throw new We("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Cd)throw new We("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return DN(e),JSON.parse(e)}catch(r){throw r instanceof We?r:new We("INVALID_JSON","Channel frame must contain strict JSON")}}function kd(e){Xo(e,"snapshot"),Jr(e,["account","permissions"],"snapshot"),Xo(e.account,"snapshot.account"),Jr(e.account,["revision"],"snapshot.account"),Qt(e.account.revision,"snapshot.account.revision"),OD(e.permissions)||xt("snapshot.permissions is invalid")}function AN(e){e.version!==Jo&&xt("version must be 1")}function Xo(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&xt(`${t} must be a plain JSON object`)}function Jr(e,t,r,n=[]){const i=Object.keys(e);(t.some(o=>!Object.hasOwn(e,o))||i.some(o=>!t.includes(o)&&!n.includes(o)))&&xt(`${r} fields are invalid`)}function Qt(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&xt(`${t} must be a non-negative safe integer`)}function Xr(e,t){(typeof e!="string"||!EN.test(e))&&xt(`${t} must be a 22-character base64url value`)}function xt(e){throw new We("INVALID_MESSAGE",e)}function DN(e){new NN(e).scan()}class NN{constructor(t){this.source=t}position=0;scan(){if(this.skipWhitespace(),this.scanValue(),this.skipWhitespace(),this.position!==this.source.length)throw new SyntaxError("Unexpected trailing JSON data")}scanValue(t=0){const r=this.source[this.position];if(r==="{"||r==="["){if(t>=yN)throw new We("INVALID_JSON","Channel JSON exceeds maximum nesting depth");return r==="{"?this.scanObject(t):this.scanArray(t)}if(r==='"'){this.scanString();return}this.scanPrimitive()}scanObject(t){this.position+=1,this.skipWhitespace();const r=new Set;if(!this.consume("}"))for(;;){if(this.source[this.position]!=='"')throw new SyntaxError("JSON object key must be a string");const n=this.scanString(),i=JSON.parse(n);if(typeof i!="string")throw new SyntaxError("JSON object key must be a string");if(r.has(i))throw new We("INVALID_JSON","Channel JSON contains a duplicate key");if(r.add(i),this.skipWhitespace(),!this.consume(":"))throw new SyntaxError("Missing JSON object colon");if(this.skipWhitespace(),this.scanValue(t+1),this.skipWhitespace(),this.consume("}"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON object comma");this.skipWhitespace()}}scanArray(t){if(this.position+=1,this.skipWhitespace(),!this.consume("]"))for(;;){if(this.scanValue(t+1),this.skipWhitespace(),this.consume("]"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON array comma");this.skipWhitespace()}}scanString(){const t=this.position;for(this.position+=1;this.position<this.source.length;){const r=this.source[this.position];if(r==='"')return this.position+=1,this.source.slice(t,this.position);r==="\\"?this.position+=2:this.position+=1}throw new SyntaxError("Unterminated JSON string")}scanPrimitive(){const t=this.position;for(;this.position<this.source.length&&!/[\s,\]}]/.test(this.source[this.position]??"");)this.position+=1;if(t===this.position)throw new SyntaxError("Missing JSON value")}skipWhitespace(){for(;/[\t\n\r ]/.test(this.source[this.position]??"");)this.position+=1}consume(t){return this.source[this.position]!==t?!1:(this.position+=1,!0)}}const Ld=[1e3,2e3,4e3,8e3,15e3];function MN(e){const t=new Set,r=e.webSocketFactory??(b=>new WebSocket(b)),n=e.randomValues??(b=>crypto.getRandomValues(b)),i=e.timers??{clearTimeout:b=>window.clearTimeout(b),setTimeout:(b,U)=>window.setTimeout(b,U)},o=e.onlineTarget??(typeof window>"u"?void 0:window),s=e.visibilityTarget??(typeof document>"u"?void 0:document),a=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let c,d,u,l=!1,f=0,h,m=!1,E=!1;const N=new Set,A=(b,U)=>{if(!(!e.onDiagnostic||N.has(b))){N.add(b);try{e.onDiagnostic({phase:b,...U?{code:U}:{}})}catch{}}},R=(b,U,D=!1)=>{if(u&&b.account.revision<u.account.revision)return;const M=u&&JSON.stringify(b)===JSON.stringify(u);if(u=b,!(M&&!D))for(const O of t)O(b,U)},y=()=>{if(l||h!==void 0||c)return;const b=Ld[Math.min(f,Ld.length-1)];f+=1,h=i.setTimeout(()=>{h=void 0,S()},b)},T=()=>{l||!m||c||(h!==void 0&&(i.clearTimeout(h),h=void 0),S())},j=()=>{a()&&T()},I=()=>{s&&!s.hidden&&T()},_=()=>{E||(E=!0,o?.addEventListener("online",j),s?.addEventListener("visibilitychange",I))},w=()=>{E&&(E=!1,o?.removeEventListener("online",j),s?.removeEventListener("visibilitychange",I))},S=()=>{if(l||c)return;m=!0,_(),h!==void 0&&(i.clearTimeout(h),h=void 0);let b,U;try{b=r(e.url)}catch{A("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),y();return}try{U=SN(n)}catch{A("entropy","NONCE_GENERATION_FAILED");try{b?.close(1011,"channel initialization failed")}catch{}y();return}c=b;let D,M,O;const z=()=>{b.removeEventListener("open",L),b.removeEventListener("message",k),b.removeEventListener("close",H),b.removeEventListener("error",F),d===z&&(d=void 0)},x=()=>{if(c===b){c=void 0,z();try{b.close(1008,"invalid channel state")}catch{}y()}},L=()=>{if(!(l||c!==b))try{b.send(JSON.stringify({version:Jo,type:"hello",csrfToken:e.csrfToken,clientNonce:U}))}catch{A("send","HELLO_SEND_FAILED"),x()}},k=G=>{if(l||c!==b)return;if(typeof G.data!="string"){A("parse","TEXT_FRAME_REQUIRED"),x();return}let Z;try{Z=wN(G.data)}catch(g){A("parse",g instanceof We?g.code:"INVALID_MESSAGE"),x();return}if(Z.type==="grant"){if(O){A("sequence","DUPLICATE_GRANT"),x();return}D=Z.connectionEpoch,M=Z.nextClientSequence,O=IN({connectionEpoch:D,nextSequence:Z.nextServerSequence}),f=0,N.clear(),R(Z.snapshot,{type:"grant"});return}if(!O||!D||M===void 0){A("sequence","MESSAGE_BEFORE_GRANT"),x();return}try{O.accept(Z)}catch{A("sequence","INVALID_SEQUENCE"),x();return}if(Z.type==="heartbeat"){try{b.send(JSON.stringify({version:Jo,type:"heartbeat.ack",connectionEpoch:D,sequence:M}))}catch{A("send","HEARTBEAT_ACK_SEND_FAILED"),x()}M=M===Number.MAX_SAFE_INTEGER?void 0:M+1;return}R(Z.snapshot,{type:"event",event:Z.event},!0)},H=()=>{c===b&&(A("close","SOCKET_CLOSED"),c=void 0,z(),y())},F=()=>{A("open","SOCKET_ERROR"),x()};b.addEventListener("open",L),b.addEventListener("message",k),b.addEventListener("close",H),b.addEventListener("error",F),d=z};return{connect:S,subscribeUpdates(b){return t.add(b),()=>t.delete(b)},dispose(){if(l)return;l=!0,m=!1,w(),h!==void 0&&i.clearTimeout(h),h=void 0;const b=c;c=void 0,d?.(),b?.close(1e3,"client disposed"),t.clear()}}}function bN(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,o=e[n+1],s=e[n+2];r+=t[i>>2],r+=t[(i&3)<<4|(o??0)>>4],o!==void 0&&(r+=t[(o&15)<<2|(s??0)>>6]),s!==void 0&&(r+=t[s&63])}return r}function SN(e){const t=e(new Uint8Array(16));if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("Channel nonce source must fill 16 bytes");const r=bN(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let _e=!1,gf=!1,Ue;const pf=new AbortController;try{pN((e,t)=>{qt(`console.${e}`,{source:"host",message:t.map(r=>QN(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const TN="/__hb_sdk_bootstrap__",ON="/__hb_sdk__/mobile-launch-redirect",vN="/__hb_sdk__/network",PN="/session/status",RN="/session/request",CN="/session/events",kN=320,LN=1e3,xN=1e3,UN=15e3,xd="dark",jN=["windows","macos","linux","unknown"],yf=new URL(location.href).searchParams,Ef=yf.get("mini_url"),Ke=yf.get("ui_preview")==="1",Se={get device(){return Rn("#device")},get mobileLanSelect(){return Rn("#mobile-lan-select")},get mobileQrImage(){return Rn("#mobile-qr-image")},get mobileQrStatus(){return Rn("#mobile-qr-status")}};if(!Ef&&!Ke)throw Se.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const wf=Ef??"about:blank",Ne=await Qs(),Hs=Ke?void 0:await st.configure({csrfToken:Ne.csrfToken??"",diagnosticsToken:Ne.diagnosticsToken??"",signal:pf.signal,query:yM,onDropped:e=>{K.diagnosticsDropped=e},onOwnershipLost:bf});K.diagnosticTargetId=Hs?.targetId??"";K.diagnosticOwnerId=Hs?.ownerId??"";K.diagnosticTargetName=Hs?.metadata.displayName??"";K.openPlatformBaseUrl=Ne.openPlatformBaseUrl;K.devReadiness=Ne.devReadiness;K.miniProgramSupportsDesktop=Ne.miniProgramSupportsDesktop;K.desktopLaunch.workspaceCardsEnabled=Ne.workspaceCardsEnabled;ou(Ne.hostPlatform);su(Ne.windowForm);let Mt=Ne.lanAddresses,Hn=Ne.defaultLanAddressId,mr=Ne.mobileLaunchRedirect,Fs=Ne.nativeAppLaunchUnavailableReason,en=Ne.devSessionId,es=Ne.miniProgramManifestAccessToken,Fn=Ne.workspaceCardsEnabled,$n=Ne,$s=Oi(Ne),Ze=Ne.devContext,wr=Ne.browserDevContext,Le=Kr(wr);mi();let br=Ni(Le),bi=0;const Sr=new AbortController;let Vs=0,yt,Vn=0,St=0,kt=!1,Gn,ts,bo=!1;const Tr=ch({apply:dh,waitForLayout:async e=>{await Xn(),await mu(e),await hu(e)}});let Gs=!1;function So(e){if(e.throwIfAborted(),_e)throw new $t("SESSION_CLOSED","调试台已关闭");if(K.diagnosticOwnershipLost)throw new $t("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!Gs)throw new $t("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(yr)throw new $t("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const rs=oh({observe:()=>{const e=an()?{width:Jn.value.width,height:Jn.value.height}:{width:Co.value.screenWidth,height:Co.value.screenHeight};return{preset:K.deviceSelectionId,orientation:an()?e.width>=e.height?"landscape":"portrait":K.display.orientation,runtimeStatus:K.runtimeStatus,viewport:e,instanceId:Ue?.mounted?Ue.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:lh()}},async selectPreset(e,t){So(t),K.deviceSelectOpen=!1;const r=K.previewMode,n=Ue;uh(e),await Xn(),t.throwIfAborted(),K.previewMode!==r&&await Ud(n,t)},async applyOrientation(e,t){So(t),K.deviceSelectOpen=!1,await Tr.applyDisplay({mode:e,hideCapsule:K.display.capsuleHidden},t)},async reload(e){So(e),K.deviceSelectOpen=!1;const t=Ue;Lt("runtime.restart",{boundary:Vs+1}),er("manual restart").catch(()=>{}),await Ud(t,e)},async waitForLayout(e){await Xn(),e.throwIfAborted(),await mu(e),await hu(e)}}),Qn=_p(),If={...rs.bridge,prepareCapture:Qn.prepare,restoreCapture:Qn.restore,cancel(e){rs.bridge.cancel(e),Qn.cancel(e)}};window.__HB_SDK_PREVIEW__=If;async function Ud(e,t){for(;;){if(t.throwIfAborted(),_e)throw new $t("SESSION_CLOSED","调试台已关闭");if(Ue!==e&&yt===void 0){const r=K.runtimeStatus;if(r==="ready"||Ke&&r==="idle")return;if(r==="error")throw new $t("RUNTIME_START_FAILED","小程序 Runtime 启动失败,请查看调试日志");if(r==="closed")throw new $t("RUNTIME_CLOSED","预览窗口已关闭或最小化,请先恢复窗口")}await new Promise((r,n)=>{const i=()=>{clearTimeout(o),n(t.reason)},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},20);t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}}let ns,is,os,ss,as,jd=Date.now(),yr=!1,zd=Promise.resolve(),Ir=-1,sn=!1,At,cs,ds,qn,Ft;const li=new Set,Bd="hb-sdk:browser-dev-host:user-data-device";function zN(){try{const e=localStorage.getItem(Bd)?.trim();if(e)return e;const t=typeof crypto.randomUUID=="function"?crypto.randomUUID():`mock-${Date.now().toString(36)}`;return localStorage.setItem(Bd,t),t}catch{return"browser-mock-device"}}const BN=zN();function HN(){return{miniProgramId:Ze.miniProgramId?.trim().toLowerCase()||"anonymous-mini-program",userId:At?.trim()||"anonymous-user",deviceId:BN,environment:"development"}}function _f(){return uf(Le.runtimePermissions,br,Le)}function FN(){const e=Ve(_f());return e.valid&&e.permissions.network?.status==="enabled"?"upload":"no_network"}function $N(){return KD({declaredPermissions:Le.declaredPermissions,runtimePermissions:_f()})}const Et=sh({resolveScope:HN,egressTier:FN,declared:$N});function Or(){gf&&ah(Et.snapshot())}Et.subscribe(Or);gf=!0;Or();const Si=tN();Si.subscribe(e=>au(e));au(Si.recent(mf));function VN(e){return mh.includes(e)}qm({applyScenario(e){Et.setScenario(e),!(VN(e)||e==="cancelled")&&(e==="session"||e==="revoked"||Ue&&Kt("data permission mock scenario"))},revokeSession(){Et.revokeSession()},resetAll(){Et.resetAll()}});const us=dN({onDiagnostic:({action:e,alias:t,detail:r})=>Lt(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),vr=kD({applyStatus:e=>Pf(e,!0),fetchStatus:e=>vf(zf(Sr.signal,e)),getCanonicalRevision:()=>Ir,onError:wM,reconcile:()=>tM(bi)}),ls=LD({connectEvents:Rf,invalidate:()=>vr.invalidate(),isDisposed:()=>_e,maxDelayMs:UN,minDelayMs:xN,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let To=0,Pn="",Oo=!1,fs,ms;function Af(){Ke||_e||K.diagnosticOwnershipLost||st.poll().finally(()=>{!_e&&!K.diagnosticOwnershipLost&&(ms=window.setTimeout(Af,1e3))})}Af();await fi(!1);Lf();Uf(xf(Ne));Ke&&YN();vi();Ke||await Nf();await er("initial");Ke||(Rf(),XN());GN();Gs=!0;sM();function Df(){!Ke&&!_e&&(fs=window.setTimeout(()=>{Nf().finally(Df)},1e3))}Df();async function Nf(){if(!(Oo||_e)){Oo=!0;try{const e=await fetch(`${oa}?targetId=${encodeURIComponent(K.diagnosticTargetId)}&after=${To}&limit=500`,{headers:{"x-hb-sdk-csrf":Ne.csrfToken??""},signal:AbortSignal.any([Sr.signal,AbortSignal.timeout(5e3)])});if(!e.ok){K.diagnosticsStale=!0;return}const t=await e.json();if(_e)return;if(Pn&&t.epoch!==Pn){To=0,Pn=t.epoch;return}Pn=t.epoch,K.uploadSessions=t.uploadSessions;const r=await fetch(`${oa}?mode=inspect`,{headers:{"x-hb-sdk-csrf":Ne.csrfToken??""},signal:AbortSignal.any([Sr.signal,AbortSignal.timeout(5e3)])});if(r.ok){const o=await r.json();K.diagnosticInstances=o.instances,K.diagnosticTargets=o.targets,K.diagnosticPrimaryTargetId=o.primaryTargetId;const s=o.targets.find(a=>a.targetId===K.diagnosticTargetId);s&&(K.diagnosticTargetName=s.metadata.displayName),s&&(s.state==="closed"||s.ownerId!==K.diagnosticOwnerId)&&bf()}K.diagnosticsStale=!1,K.diagnosticsGap=K.diagnosticsGap||t.gap===!0;const n=new Map(K.diagnosticTargets.map(o=>[o.targetId,o.metadata.displayName])),i=new Map(K.diagnosticInstances.map(o=>[o.instanceId,n.get(o.targetId)]));for(const o of t.items){const s=Ym(o);s&&(s.targetName=n.get(o.targetId)??i.get(o.instanceId),s.uploadSessionId=o.uploadSessionId,s.uploadSessionName=t.uploadSessions.find(a=>a.id===o.uploadSessionId)?.name,s.dedupeKey=void 0,Wm(s,o.cursor))}To=t.nextCursor}catch{K.diagnosticsStale=!0}finally{Oo=!1}}}function GN(){window.addEventListener("beforeunload",IM),window.addEventListener("hb-sdk:refresh-storage",vi),window.addEventListener("hb-sdk:qr-open-change",Mf),ns=Zm(()=>document.querySelector("#host-fullscreen-exit-mount")),is=pn(()=>K.devicePresetId,()=>Tr.notifyViewportChange(),{flush:"post"}),os=pn(()=>K.previewMode,()=>{Dt("preview mode changed"),cu(!1),Km(!1),Kt("preview mode changed")},{flush:"sync"}),ss=pn(()=>Jn.value,()=>Tr.notifyViewportChange(),{flush:"post"}),as=pn(()=>K.desktopWindow.closed,(e,t)=>{if(an()){if(e){Dt("desktop window closed"),K.runtimeStatus="closed";return}t&&K.runtimeStatus==="closed"&&Kt("desktop window reopened")}},{flush:"sync"})}function QN(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
227
- `).slice(0,4).join(`
228
- `):"")||`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}return String(e)}function Mf(e){const t=e.detail?.open===!0;t!==kt&&(kt=t,St+=1,Pi(),t&&(Se.mobileLanSelect.addEventListener("change",qN),Cf(),hn()))}function qN(){kt&&hn()}function Kt(e){_e||yt!==void 0||(Lt("runtime.restart",{boundary:Vs+1}),yt=window.setTimeout(()=>{yt=void 0,_e||er(e)},0))}async function er(e,t=wf,r){if(_e||yr||K.diagnosticOwnershipLost)return;if(yt!==void 0&&window.clearTimeout(yt),yt=void 0,Dt(e),an()&&K.desktopWindow.closed){K.runtimeStatus="closed";return}const n=document.createElement("iframe");n.dataset.testid="device-iframe",n.title="小程序预览",n.allow="clipboard-read; clipboard-write",n.name="__hb_sdk_mini_dev__";const i=crypto.randomUUID(),o=Jm(i,c=>{Ke||st.event(i,c)}),s={instanceId:i,launchUrl:t,locationBasePath:r,interactions:o,sequence:++Vs,state:"starting",iframe:n,terminal:new AbortController,permissions:Ff(br),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(s.iframe.dataset.hbSdkInstanceId=s.instanceId,Ue=s,K.runtimeStatus="loading",Tf(),Ke||st.send({operation:"register",instanceId:s.instanceId}),await Xn(),!Be(s))return;const a=$f("#device");if(!a){vo(s,new Error("预览容器尚未挂载"));return}if(Ke){a.innerHTML='<div class="browser-mock-preview"><span class="browser-mock-preview__icon">UI</span><strong>Browser Mock</strong><small>mp_preview</small></div>',K.runtimeStatus="idle";return}a.replaceChildren(s.iframe),s.mounted=!0,st.send({operation:"activate",instanceId:s.instanceId});try{const c=await J0(WN(s));if(!Be(s)){c.dispose();return}s.assembly=c,c.ports.companion=us.port,c.ports.media=Xm({getMode:()=>K.mediaSimulation,signal:s.terminal.signal});const d=bD({signal:s.terminal.signal,csrfToken:()=>Ne.csrfToken??""}),u=k0({iframe:s.iframe,authorizationContext:SD({signal:s.terminal.signal,refreshAccount:l=>fi(!0,l),request:Of,readState:()=>({signed:Ze,browser:Le,userId:At,accountRevision:Ir,networkEnabled:s.permissions.networkRequest.status==="enabled"})}),ports:{...c.ports,...d},environment:c.environment,hostCapabilities:{...c.hostCapabilities,"media.pick":!0,...d?{"gameSaves.getFile":!0,"user.data.file":!0,"file.readBytes":!0,"file.readText":!0,"file.stat":!0,"file.exists":!0}:{},...cN},authPresentation:c.authPresentation,userDataPresentation:c.userDataPresentation,companionPresentation:us.presentation,resolveLaunchConfiguration:async()=>(await c.resolveLaunch()).configuration,dispose:()=>hs(s),onDevDocumentReload:(l,f)=>{Be(s)&&er("development document reloaded",l,f)},onDevUploadSession:l=>{Be(s)&&(s.uploadSessionId=l,Pr(s,{uploadSessionId:l}))},onReady:()=>{Be(s)&&(s.state="ready",s.hadReady=!0,Es.value=d?u.diagnostics.gameSaves:void 0,K.runtimeStatus="ready",Pr(s),qt("runtime.ready",{generation:s.sequence},Date.now(),void 0,s.instanceId))},onUserDataTelemetry:l=>{Si.record(l),Et.refresh();const f=nN(l);qt(f.method,f.detail,Date.now(),"info",s.instanceId)},onTrace:l=>JN(s,l),onError:l=>{Be(s)&&vo(s,l)},onCapabilityTrace:l=>{qt(l.method,{...l,source:"host"},l.timestamp,void 0,s.instanceId),Be(s)&&l.method==="storage.setStorage"&&l.outcome==="success"&&vi()}});s.runtime=u,await u.start(),Be(s)&&Et.bind(u.getDataPermissionBridge())}catch(c){if(!Be(s))return;vo(s,c),qt("runtime.start.failed",jf(c,s),Date.now(),"error",s.instanceId),s.terminal.abort(c),s.runtime?.destroy(),s.iframe.remove(),hs(s)}}function bf(){_e||K.diagnosticOwnershipLost||(K.diagnosticOwnershipLost=!0,Dt("预览页面授权已失效"),K.runtimeStatus="closed",Gs=!1)}function Be(e){return Ue===e&&!_e&&!e.terminal.signal.aborted&&e.state!=="closed"&&e.state!=="failed"}function Pr(e,t={}){st.send({operation:"update",instanceId:e.instanceId,state:e.state,...t})}function Sf(e,t){e.mounted&&(e.mounted=!1,st.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function hs(e){Ue===e&&(Es.value=void 0),e.interactions.dispose();const t=e.assembly;e.assembly=void 0,t?.dispose()}function vo(e,t){e.state==="failed"||e.state==="closed"||(e.state="failed",e.interactions.dispose(),Pr(e,{error:jf(t,e),...e.uploadSessionId?{uploadSessionId:e.uploadSessionId}:{}}),Sf(e,"Runtime failed"),Ue===e&&(K.runtimeStatus="error"))}function Dt(e){const t=Ue;t&&(Ue=void 0,Es.value=void 0,Et.clearSession(),t.state!=="failed"&&(t.state="closed",Pr(t,{reason:e})),Sf(t,e),Vn+=1,eh(),us.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),hs(t),Tr.reset())}function YN(){Lt("runtime.ready",{generation:1}),du(uu("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info")),Lt("user.getInfo",{durationMs:34,outcome:"success"}),Lt("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function WN(e){const t=e.terminal.signal,r=Le,n=en,i=uf(r.runtimePermissions,e.permissions,r),o=an();return{signal:t,account:{async getCurrentUserId(){return(await fi(!1,t)).user_id},async ensureAuthenticated({signal:s}){await fi(!1,s)},onChange(s){return li.add(s),()=>li.delete(s)}},authenticatedRequest:Of,storage:{area:"local",storage:localStorage},presentation:sN({close:async()=>{Be(e)&&(Dt("mini program closed"),Tf(),K.runtimeStatus="closed",o&&cu(!0))},reload:()=>{Be(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:s=>{Be(e)&&lu(s)},...o?{getViewportMetrics:()=>{const s=Jn.value;return{windowWidth:s.width,windowHeight:s.height,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio,safeArea:{left:0,right:s.width,top:0,bottom:s.height}}},getNavigationBarHeight:()=>fh}:{getDeviceMetrics:()=>Co.value,applyDisplay:(s,a)=>Tr.applyDisplay(s,a),isCapsuleHidden:()=>K.display.capsuleHidden},onViewportChange:s=>Tr.onViewportChange(s)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:s=>{document.title=s}},resolveLaunch:async()=>({configuration:VD({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,...K.miniProgram.bound&&K.miniProgram.name.trim()?{miniProgramName:K.miniProgram.name}:{},...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:o?K.hostPlatform:th.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:s=>$D(s),confirmFollowAuthor:s=>xD(s)},userDataPresentation:{confirmDataPermission:YD},protocol:ZN(e)}}function an(){return K.previewMode==="desktop"}function ZN(e){return{async invoke(t){qt("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:KN(t)},Date.now(),void 0,e.instanceId)}}}function KN(e){if(typeof e!="string")return typeof e.protocol_type=="string"?e.protocol_type:void 0;const t=/^heybox:\/\/(.+)$/i.exec(e.trim());if(t)try{const r=JSON.parse(decodeURIComponent(t[1]));return qe(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function Tf(){document.documentElement.dataset.navigationBarStyle=xd,lu(xd)}function JN(e,t){Be(e)&&t.type==="document_validation"&&typeof t.documentVerifying=="boolean"&&Pr(e,{documentVerifying:t.documentVerifying}),_e||st.event(e.instanceId,{source:"runtime",level:t.type==="error"||t.type==="security_violation"?"error":"info",timestamp:t.timestamp,phase:t.type,method:t.method??`runtime.${t.type}`,message:JSON.stringify(rh({...t,generation:e.sequence})),...t.errorCode?{errorCode:t.errorCode}:{}}),e.runtimeId!==t.runtimeId&&(e.runtimeId=t.runtimeId,Pr(e,{runtimeId:t.runtimeId})),Be(e)&&e.pendingNavigationReload&&t.type==="bridge_response"&&t.method==="navigation.reload"&&t.outcome==="success"&&(e.pendingNavigationReload=!1,Kt("navigation.reload"))}async function Of(e,t){const r=await JD(()=>Et.snapshot().dataScenario)(e);if(r)return r;if(e.redirectPolicy!=="error")throw new Error("Browser Dev Host network 只允许 no-follow redirect policy");const i=e.target.kind==="absolute-url"&&e.source==="public-sdk"&&e.target.kind==="absolute-url"?{url:e.target.url,method:e.method,params:e.params,data:e.data,bodyEncoding:e.bodyEncoding,headers:e.headers,timeout:e.timeout}:void 0;if(!i&&e.source!=="runtime-private")throw new Error("Browser Dev Host 的公开请求只支持 absolute URL");const o=await Ti(i?vN:RN,{method:"POST",body:JSON.stringify(i??{target:e.target,method:e.method,params:e.params,data:e.data,headers:e.headers,credentials:e.source==="runtime-private"?e.credentials:void 0,bodyEncoding:e.bodyEncoding,timeout:e.timeout}),signal:t.signal});!i&&o.status===401&&vr.invalidate();const s=await o.json();if(!o.ok)throw s;return s}async function fi(e,t){const r=bi,n=await vf(zf(Sr.signal,t));return Bf(r)?Pf(n,e).status:gs()}async function vf(e){return await(await fetch(PN,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Pf(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Ir)return{changed:!1,status:gs()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?Ce(e.nickname):void 0,i=e.authenticated?Ce(e.avatar):void 0,o=e.revision!==Ir||e.authenticated!==sn||r!==At||n!==cs||i!==ds;return Ir=e.revision,sn=e.authenticated,At=r,cs=n,ds=i,Lf(),Or(),t&&o&&li.forEach(s=>s(At)),{changed:o,status:gs()}}function gs(){return{authenticated:sn,revision:Ir,...sn&&At?{user_id:At}:{}}}function XN(){if(!(!Ne.csrfToken||_e))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Ft=MN({csrfToken:Ne.csrfToken,onDiagnostic:t=>Lt("channel.diagnostic",t),url:e.toString()}),Ft.subscribeUpdates((t,r)=>eM(t,r)),Ft.connect()}catch{Ft?.dispose(),Ft=void 0}}function eM(e,t){vr.invalidate(e.account.revision),DM(br,e.permissions)?t.type==="event"&&t.event==="status.changed"&&er("status changed"):(br=Ff(e.permissions),rM())}function Rf(){if(qn?.close(),qn=void 0,!At||_e)return;const e=new EventSource(CN);qn=e,e.addEventListener("account-invalidated",()=>{vr.invalidate()}),e.addEventListener("account-revision",()=>{vr.invalidate()}),e.onopen=()=>{ls.reset()},e.onerror=()=>{e.close(),ls.schedule()}}async function tM(e){Bf(e)&&await er("account revision changed")}async function rM(){_e||(await er("permission changed"),!_e&&await hn())}async function Qs(){const e=await fetch(TN,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error("Browser Dev Host bootstrap request failed");const t=await e.json();if(!qe(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Hf(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new Rr;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:oM(t.devReadiness),csrfToken:typeof t.csrfToken=="string"?t.csrfToken:void 0,diagnosticsToken:typeof t.diagnosticsToken=="string"?t.diagnosticsToken:void 0,defaultLanAddressId:typeof t.defaultLanAddressId=="string"?t.defaultLanAddressId:void 0,devSessionId:typeof t.devSessionId=="string"&&/^[a-f0-9]{32}$/.test(t.devSessionId)?t.devSessionId:void 0,devContext:Md(t.devContext,t.runtimePermissions),browserDevContext:Md(t.browserDevContext??t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(AM):[],loginAvailable:t.loginAvailable===!0,miniProgram:gM(t.miniProgram),miniProgramSupportsDesktop:t.miniProgramSupportsDesktop===!0,workspaceCardsEnabled:t.workspaceCardsEnabled===!0,mobileLaunchRedirect:r,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof t.miniProgramManifestAccessToken=="string"?t.miniProgramManifestAccessToken:void 0,windowForm:iM(t.windowForm),hostPlatform:nM(t.hostPlatform)}}function nM(e){return jN.includes(e)?e:"unknown"}function iM(e){if(!qe(e))return;const t=s=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:void 0,r=t(e.defaultWidth),n=t(e.defaultHeight),i=t(e.minWidth),o=t(e.minHeight);return{...r===void 0?{}:{defaultWidth:r},...n===void 0?{}:{defaultHeight:n},...i===void 0?{}:{minWidth:i},...o===void 0?{}:{minHeight:o},...typeof e.resizable=="boolean"?{resizable:e.resizable}:{}}}function oM(e){if(!qe(e))return;const t=s=>{if(!(!qe(s)||!["ready","pending","blocked","not-configured"].includes(String(s.state))))return{state:s.state,...typeof s.reason=="string"?{reason:s.reason.slice(0,240)}:{}}},r=t(e.browser),n=t(e.mobile),i=t(e.companion);if(!r||!n||!i||!qe(e.companion))return;const o=e.companion;return{browser:r,mobile:n,companion:{...i,...typeof o.digest=="string"&&/^[a-f0-9]{64}$/.test(o.digest)?{digest:o.digest}:{},artifacts:Array.isArray(o.artifacts)?o.artifacts.filter(s=>qe(s)&&typeof s.alias=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(s.alias)&&["windows-x64","macos-arm64"].includes(String(s.target))).map(({alias:s,target:a})=>({alias:s,target:a})):[]}}}async function Ti(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),Ne.csrfToken&&r.set("x-hb-sdk-csrf",Ne.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function sM(){qs(),Ke||(ts=window.setInterval(()=>{hM()},LN))}function Cf(e=Se.mobileLanSelect.options.length>0?Se.mobileLanSelect.value:void 0){Se.mobileLanSelect.replaceChildren();for(const t of Mt){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,Se.mobileLanSelect.appendChild(r)}e&&Mt.some(({id:t})=>t===e)?Se.mobileLanSelect.value=e:Hn&&Mt.some(({id:t})=>t===Hn)?Se.mobileLanSelect.value=Hn:Mt[0]&&(Se.mobileLanSelect.value=Mt[0].id),Se.mobileLanSelect.disabled=Mt.length===0}async function hn(){if(_e)return;const e=++St;if(Pi(),Ze.source!=="remote"||!Ze.localDevLaunchToken||Ze.expiresAt!==void 0&&Ze.expiresAt<=Date.now()){Se.mobileQrImage.removeAttribute("src"),Se.mobileQrStatus.textContent=Fs||"需要有效的本地调试启动票";return}const t=_M();if(!t?.mobileAppQrPayload){Se.mobileQrImage.removeAttribute("src"),Se.mobileQrStatus.textContent="未发现可用的局域网地址";return}Se.mobileQrStatus.textContent="正在生成二维码...";try{const r=await lM(t);if(e!==St||_e)return;const n=await aM(r.address,r.expiresAt);if(e!==St||_e)return;const i=await AD.toDataURL(n.payload,{width:kN,margin:1});if(e!==St||_e)return;Se.mobileQrImage.src=i,Se.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,mM(n.expiresAt,e)}catch(r){if(e!==St||_e)return;if(r instanceof Rr){Yn();return}Se.mobileQrImage.removeAttribute("src"),Se.mobileQrStatus.textContent=Ys(r)}}async function aM(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await cM(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:mN(fN({host:e.address,port:location.port,token:n.token}))}}catch{throw new Rr}}async function cM(e,t){if(mr?.addressId===e.id)return mr;if(!mr)return;const r=await Ti(ON,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:mr.token})});if(!r.ok)throw new Rr;const n=await r.json(),i=qe(n)?Hf({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new Rr;return mr=i,$n={...$n,mobileLaunchRedirect:i},$s=Oi($n),i}async function dM(e){const t=await Qs(),r=uM(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return kf(t),{...r,mobileAppQrPayload:n}}function uM(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function kf(e){const t=Gt(Le);K.devReadiness=e.devReadiness,K.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,ou(e.hostPlatform),su(e.windowForm),Fn=e.workspaceCardsEnabled,$n=e,$s=Oi(e),Ze=e.devContext,wr=e.browserDevContext,Le=Kr(wr),br=Ni(Le),mi(),Mt=e.lanAddresses,Hn=e.defaultLanAddressId,mr=e.mobileLaunchRedirect,Fs=e.nativeAppLaunchUnavailableReason,en=e.devSessionId,es=e.miniProgramManifestAccessToken,Uf(xf(e)),kt&&Cf(),qs(),t!==Gt(Le)&&(Dt("local permission context changed"),Kt("local permission context changed"))}function mi(){K.localPermissions=hN(Le),K.devContextWarning=Le.source==="anonymous"?"未连接线上上下文":Le.warning?"本地上下文受限,请检查 CLI 状态":"",Or()}function qs(){let e;try{e=nh(wf)}catch{}const t=Ze.miniProgramId?.trim().toLowerCase();let r=Fs?.trim()??"";!r&&(Ze.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!Ze.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&Fn&&!en&&(r="本地调试会话尚未就绪"),!r&&Ze.expiresAt!==void 0&&Ze.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),fu({...e?{address:e}:{},...t?{miniProgramId:t}:{},...Fn&&en?{devSessionId:en}:{},...es?{miniProgramManifestToken:es}:{},workspaceCardsEnabled:Fn,ready:r==="",...r?{unavailableReason:r}:{}})}class Rr extends Error{}async function lM(e){const t=zd.then(()=>fM(e));return zd=t.then(()=>{},()=>{}),t}async function fM(e){const t=new URL(e.appUrl),r=new URL(TD,location.origin),n=await Ti(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:PD(Ze)})}),i=await n.json();if(!n.ok||!qe(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await dM(e.id),expiresAt:i.expires_at}}function mM(e,t){Gn=window.setTimeout(()=>{!_e&&kt&&t===St&&hn()},Math.max(1e3,e-Date.now()-3e4))}async function hM(){if(!(bo||_e)){bo=!0;try{const e=await Qs();jd=Date.now();const t=yr;yr=!1;const r=Oi(e);if(!t&&r===$s&&Gt(Kr(e.browserDevContext))===Gt(Le)){wr=e.browserDevContext,Le=Kr(wr),mi();return}kf(e),t&&Kt("CLI dev session reconnected"),kt&&hn()}catch(e){e instanceof Rr&&Yn();const t=Kr(wr);Gt(t)!==Gt(Le)&&(Le=t,br=Ni(Le),mi(),Dt("local permission context expired"),Kt("local permission context expired"),qs(),kt&&Yn()),Date.now()-jd>=3e4&&!yr&&(yr=!0,Dt("CLI dev session disconnected"),$f("#device")?.replaceChildren(),K.runtimeStatus="closed",K.localPermissions=[],K.devContextWarning="调试会话已断开",fu({ready:!1,unavailableReason:"调试会话已断开"}),K.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},kt&&Yn())}finally{bo=!1}}}function Yn(){St+=1,Pi(),Se.mobileQrImage.removeAttribute("src"),Se.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Oi(e){return JSON.stringify({devReadiness:e.devReadiness,devSessionId:e.devSessionId,defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,devContext:{permissionContext:Gt(e.devContext),expiresAt:e.devContext.expiresAt,localDevLaunchToken:e.devContext.localDevLaunchToken,miniProgramId:e.devContext.miniProgramId,source:e.devContext.source},nativeAppLaunchUnavailableReason:e.nativeAppLaunchUnavailableReason,miniProgramManifestAccessToken:e.miniProgramManifestAccessToken,miniProgramSupportsDesktop:e.miniProgramSupportsDesktop,workspaceCardsEnabled:e.workspaceCardsEnabled,hostPlatform:e.hostPlatform,windowForm:e.windowForm})}function Lf(){if(!sn){K.account={authenticated:!1,avatar:"",nickname:"未登录"};return}K.account={authenticated:!0,avatar:ds??"",nickname:cs||At||"已登录"}}function xf(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Uf(e){if(!!!e?.miniProgramId||!e){K.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试"},Or();return}K.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")},Or()}function gM(e){if(e===null)return null;if(!qe(e))return;const t=Ce(e.miniProgramId)??Ce(e.mini_program_id);if(t)return{miniProgramId:t,...Ce(e.name)?{name:Ce(e.name)}:{},...Ce(e.iconUrl)??Ce(e.icon_url)?{iconUrl:Ce(e.iconUrl)??Ce(e.icon_url)}:{},...Ce(e.status)?{status:Ce(e.status)}:{},...Ce(e.version)?{version:Ce(e.version)}:{},...Ce(e.developerName)??Ce(e.developer_name)?{developerName:Ce(e.developerName)??Ce(e.developer_name)}:{}}}function Ce(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function vi(){const e=++Vn,t=Ue?.instanceId;if(!t){K.storage=[],K.storageError="";return}try{const r=await Ti(ih,{method:"POST",body:JSON.stringify({instanceId:t,resource:"storage"})}),n=await r.json();if(_e||e!==Vn||t!==Ue?.instanceId)return;if(!r.ok||n.code)throw new Error(n.error??"Storage 诊断查询失败");K.storage=n.value,K.storageError=""}catch(r){if(_e||e!==Vn||t!==Ue?.instanceId)return;K.storage=[],K.storageError=Ys(r)}}function jf(e,t=Ue){const r=(c,d)=>{if(!(!c||typeof c!="object"))try{return Object.getOwnPropertyDescriptor(c,d)?.value}catch{return}},n=(c,d)=>{const u=r(c,d);return typeof u=="string"?u.slice(0,8192):void 0},i=r(e,"cause"),o=n(e,"stack")??n(i,"stack"),s=n(e,"name")??n(i,"name"),a=typeof i=="string"?i:[n(i,"name"),n(i,"message")].filter(Boolean).join(": ");return{code:n(e,"code")??"RUNTIME_START_FAILED",message:n(e,"message")??(typeof e=="string"?e:"Runtime 启动失败"),phase:t?.hadReady?"running":"starting",...s?{name:s}:{},...o?{stack:o}:{},...a?{cause:a}:{}}}function qt(e,t,r=Date.now(),n,i){pM(uu(e,t,r,n==="debug"?"log":n),i)}function pM(e,t){if(_e)return;if(Ke){du(e);return}const r=qe(e.detail)?e.detail:{};st.event(t,{source:t&&e.source==="runtime"?"runtime":"host",level:e.level,timestamp:e.timestamp,message:e.summary,method:e.method,...typeof r.phase=="string"?{phase:r.phase}:{},...e.callId?{callId:e.callId}:{},...e.outcome?{outcome:e.outcome}:typeof r.outcome=="string"?{outcome:r.outcome}:{},...e.durationMs===void 0?{}:{durationMs:e.durationMs},...typeof r.startedAt=="number"?{startedAt:r.startedAt}:{},...e.errorCode?{errorCode:e.errorCode}:{},...qe(r.network)?{network:r.network}:{}})}async function yM(e){const t=Ue;if(!t||e.instanceId!==t.instanceId||!Be(t)||!t.runtime)return{code:"closed",error:"该实例已结束"};if(Date.now()>=e.deadline)return{code:"timeout",error:"查询已超过期限"};if(e.resource==="presentation")return{value:t.interactions.snapshot()};if(e.resource==="sandbox")return{code:"unsupported",error:"Browser Dev Host 不提供文件系统能力"};const r=t.runtime,n=r.diagnostics.storage;if(!n)return{code:"unsupported",error:"当前 Host 不支持 Storage 诊断"};const i=AbortSignal.any([Sr.signal,t.terminal.signal,AbortSignal.timeout(Math.max(1,e.deadline-Date.now()))]);let o,s;try{s=await Promise.race([n.getSnapshot(),new Promise((a,c)=>{o=()=>c(i.reason),i.addEventListener("abort",o,{once:!0}),i.aborted&&o()})])}catch{return{code:Date.now()>=e.deadline?"timeout":"closed",error:"实例查询已结束或超过期限"}}finally{o&&i.removeEventListener("abort",o)}return!Be(t)||r!==t.runtime||e.instanceId!==t.instanceId?{code:"closed",error:"查询期间实例已结束"}:{value:s}}function EM(e,t){Lt("host.message",{message:e,status:t})}function wM(e){_e||EM(Ys(e),"error")}function Lt(e,t){qt(e,t)}function IM(){st.close(),fs!==void 0&&window.clearTimeout(fs),ms!==void 0&&window.clearTimeout(ms),!_e&&(_e=!0,Qn.dispose(),rs.dispose(),window.__HB_SDK_PREVIEW__===If&&delete window.__HB_SDK_PREVIEW__,window.removeEventListener("hb-sdk:refresh-storage",vi),window.removeEventListener("hb-sdk:qr-open-change",Mf),bi+=1,Sr.abort(new DOMException("Browser Dev Host disposed","AbortError")),vr.dispose(),Dt("Browser Dev Host disposed"),Et.dispose(),Si.clear(),st.send({operation:"close-target",reason:"Browser Dev Host disposed"}),window.setTimeout(()=>pf.abort(),2e3),qn?.close(),Ft?.dispose(),Ft=void 0,ls.dispose(),yt!==void 0&&window.clearTimeout(yt),yt=void 0,Pi(),ts!==void 0&&window.clearInterval(ts),li.clear(),ns?.(),ns=void 0,is?.(),is=void 0,os?.(),os=void 0,ss?.(),ss=void 0,as?.(),as=void 0)}function Pi(){Gn!==void 0&&window.clearTimeout(Gn),Gn=void 0}function zf(e,t){return t?AbortSignal.any([e,t]):e}function Bf(e){return!_e&&e===bi}function _M(){return Mt.find(({id:e})=>e===Se.mobileLanSelect.value)}function AM(e){return qe(e)&&typeof e.address=="string"&&typeof e.appUrl=="string"&&typeof e.id=="string"&&typeof e.name=="string"&&(e.mobileAppQrPayload===void 0||typeof e.mobileAppQrPayload=="string")}function Hf(e){if(!(!qe(e)||typeof e.addressId!="string"||!e.addressId||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||typeof e.token!="string"||!/^[A-Za-z0-9_-]{22}$/.test(e.token)))return{addressId:e.addressId,expiresAt:e.expiresAt,token:e.token}}function Ff(e){return{networkRequest:{...e.networkRequest}}}function DM(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function Ys(e){return e instanceof Error&&e.message?e.message:"操作失败"}function qe(e){return Object.prototype.toString.call(e)==="[object Object]"}function Rn(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function $f(e){return document.querySelector(e)??void 0}