@heybox/hb-sdk 0.8.3-alpha.9 → 0.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -1
- package/README.md +1 -1
- package/dist/cli-chunks/{build-Dd5EmgU1.cjs → build-BMLuhvh9.cjs} +5 -5
- package/dist/cli-chunks/{context-Cm0U_oeb.cjs → context-BoNshqZO.cjs} +2 -2
- package/dist/cli-chunks/{create-Bj08BLVt.cjs → create-rUrkd162.cjs} +1 -1
- package/dist/cli-chunks/{dev-BQtFwaZ6.cjs → dev-BRx7xYck.cjs} +9 -9
- package/dist/cli-chunks/{doctor-C3LLR1Hq.cjs → doctor-DOCFSRjQ.cjs} +1 -1
- package/dist/cli-chunks/{index-D4KcCSeD.cjs → index-BrJ7364Q.cjs} +15 -15
- package/dist/cli-chunks/{index-B2kcpr9q.cjs → index-CbmIweP8.cjs} +2 -2
- package/dist/cli-chunks/{index.esm-Dog1YTU_.cjs → index.esm-CGFTxGm6.cjs} +7 -7
- package/dist/cli-chunks/{login-C7Q6SStX.cjs → login-DxtSW2QP.cjs} +2 -2
- package/dist/cli-chunks/{project-vite-BWhbvrXL.cjs → project-vite-D9tmGT59.cjs} +1 -1
- package/dist/cli-chunks/{remote-DrflbJjL.cjs → remote-DuiJdetu.cjs} +7 -7
- package/dist/cli-chunks/{runtime-gate-OEku3HCR.cjs → runtime-gate-CDh8XjRx.cjs} +1 -1
- package/dist/cli-chunks/{runtime-permission-env-D7X7T6VT.cjs → runtime-permission-env-D2pJlHds.cjs} +1 -1
- package/dist/cli-chunks/{session-BC8gfXbM.cjs → session-BAw6iix6.cjs} +1 -1
- package/dist/cli-chunks/{skill-BXzVRK6G.cjs → skill-Cu4QVawo.cjs} +2 -2
- package/dist/cli-chunks/{version-CHBZvmBz.cjs → version-BuPFCnrl.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/{browser-dev-host-D820rR5R.js → browser-dev-host-CE4o5TF5.js} +1 -1
- package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-C0HMYsbA.js → desktop-app-launch-DldUhS5Y.js} +1 -1
- package/dist/devtools/browser-dev-host/assets/index-0Ac39Njs.css +1 -0
- package/dist/devtools/browser-dev-host/assets/{index-BUsHRfad.js → index-DUhquRwB.js} +4 -4
- package/dist/devtools/browser-dev-host/index.html +3 -3
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/vite.cjs.js +1 -1
- package/dist/vite.esm.js +1 -1
- package/package.json +7 -7
- package/skill/skill.json +4 -4
- package/dist/devtools/browser-dev-host/assets/index-BrXEMo2-.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{H as fo,aw as Wc,aW as Kc,K as Yc,aF as Qc,aG as Xc,ak as Xt,b1 as B,ab as Jc,al as aa,an as Zc,c as ho,aC as ca,a9 as ed,as as da,p as td,ay as ua}from"./desktop-app-launch-C0HMYsbA.js";const Pn="auth.login",Rn="user.getInfo",Nn="user.revokeAuthorization",Cn="user.getSteamGameList",Tn="share.copyLink",Ln="share.showShareMenu",kn="share.screenshot",Je="viewport.setDisplay",Mn="viewport.getWindowInfo",Un="viewport.setNavigationBarStyle",xt="storage.getStorage",Ht="storage.setStorage",xn="network.request",Hn="network.download",Fn="files.pickFiles",Bn="files.pickDirectory",Vn="files.saveFile",Ft="file.create",Bt="file.remove",qn="file.exists",Vt="file.readText",zn="file.writeText",qt="file.readBytes",jn="file.writeBytes",zt="file.stat",Gn="directory.create",jt="directory.remove",$n="directory.exists",Wn="directory.list",Kn="ui.showToast",Yn="ui.showLoading",Qn="ui.hideLoading",Xn="device.vibrate",Jn="device.setClipboard",Zn="navigation.close",er="navigation.reload",tr="navigation.openAppPage",Pe="cloud.leaderboard.submit",me="cloud.leaderboard.getList",xe="cloud.leaderboard.getCurrentUserEntry",Ze="cloud.leaderboard.deleteCurrentUserEntry",Ae="cloud.leaderboard.getInfo",dr="companion.getInfo",ur="companion.getPreparationStatus",lr="companion.prepare",fr="companion.cancelPreparation",hr="companion.getActiveSession",mr="companion.launch",pr="companion.session.write",gr="companion.session.closeStdin",Er="companion.session.terminate",yr="companion.session.ackOutput",wr="companion.openAttachment",Ir="companion.showNotification",He=[{method:Pn,module:"auth",capability:Pn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Rn,module:"user",capability:Rn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Nn,module:"user",capability:Nn,requirement:{kind:"none"},risk:"high"},{method:Cn,module:"user",capability:Cn,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:Tn,module:"share",capability:Tn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Ln,module:"share",capability:Ln,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:kn,module:"share",capability:kn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Mn,module:"viewport",capability:Mn,requirement:{kind:"none"},risk:"low"},{method:Un,module:"viewport",capability:Un,requirement:{kind:"none"},risk:"low"},{method:Je,module:"viewport",capability:Je,requirement:{kind:"none"},risk:"low"},{method:xt,module:"storage",capability:xt,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:Ht,module:"storage",capability:Ht,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:xn,module:"network",capability:xn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Hn,module:"network",capability:Hn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Fn,module:"files",capability:Fn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Bn,module:"files",capability:Bn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Vn,module:"files",capability:Vn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ft,module:"file",capability:Ft,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Bt,module:"file",capability:Bt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:qn,module:"file",capability:qn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Vt,module:"file",capability:Vt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:zn,module:"file",capability:zn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:qt,module:"file",capability:qt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:jn,module:"file",capability:jn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:zt,module:"file",capability:zt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Gn,module:"directory",capability:Gn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:jt,module:"directory",capability:jt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:$n,module:"directory",capability:$n,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Wn,module:"directory",capability:Wn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Kn,module:"ui",capability:Kn,requirement:{kind:"none"},risk:"low"},{method:Yn,module:"ui",capability:Yn,requirement:{kind:"none"},risk:"low"},{method:Qn,module:"ui",capability:Qn,requirement:{kind:"none"},risk:"low"},{method:Xn,module:"device",capability:Xn,requirement:{kind:"none"},risk:"low"},{method:Jn,module:"device",capability:Jn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Zn,module:"navigation",capability:Zn,requirement:{kind:"none"},risk:"medium"},{method:er,module:"navigation",capability:er,requirement:{kind:"none"},risk:"medium"},{method:tr,module:"navigation",capability:tr,requirement:{kind:"none"},risk:"medium"},{method:Pe,module:"cloud",capability:Pe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:me,module:"cloud",capability:me,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:xe,module:"cloud",capability:xe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ze,module:"cloud",capability:Ze,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ae,module:"cloud",capability:Ae,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},...[dr,ur,lr,fr,hr,mr,pr,gr,Er,yr,wr,Ir].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],Ge="heybox:miniprogram",la=2,nd="hb_mini_bridge_nonce",fa="sdk.handshake",sn="runtime.location.probe",rd="sdk.location.report",id="sdk.csp.violation",ha="operation.progress",od="companion.session.output",sd="companion.session.exit",ad="companion.session.ownershipLost";function cd(e){return!je(e)||e.namespace!==Ge||e.version!==1&&e.version!==2||!ee(e.nonce)?!1:e.type==="handshake"?ee(e.id)&&e.method===fa&&e.error===void 0&&fd(e.payload):e.type==="request"?ee(e.id)&&ee(e.method)&&e.error===void 0:e.type==="response"?ee(e.id)&&(e.method===void 0||ee(e.method))&&(e.error===void 0||hd(e.error)):e.type==="event"?!ee(e.method)||e.error!==void 0?!1:e.method===ha?e.version===2&&ee(e.id)&&ld(e.payload):e.id===void 0||ee(e.id):e.type==="cancel"?e.version===2&&ee(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Bi(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function ma(e){return je(e)?e.kind==="sandbox"?Re(e,["kind"]):e.kind==="directory"&&ee(e.handleId)&&Re(e,["kind","handleId"]):!1}function Vi(e){return!je(e)||e.kind!=="file"?!1:ee(e.handleId)?Re(e,["kind","handleId"]):ma(e.root)&&Bi(e.relativePath)&&Re(e,["kind","root","relativePath"])}function pa(e){return!je(e)||e.kind!=="directory"?!1:ee(e.handleId)?Re(e,["kind","handleId"]):ma(e.root)&&(e.relativePath==="."||Bi(e.relativePath))&&Re(e,["kind","root","relativePath"])}function ga(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function dd(e){return!je(e)||!ht(e.loaded)||typeof e.lengthComputable!="boolean"||!Re(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?ht(e.total)&&e.loaded<=e.total:e.total===void 0}function ud(e){return je(e)?e.phase==="downloading"?ht(e.loaded)&&(e.total===void 0||ht(e.total)&&e.loaded<=e.total)&&Re(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:ht(e.processed)&&ht(e.total)&&e.processed<=e.total&&Re(e,["phase","processed","total"]):!1}function ld(e){return dd(e)||ud(e)}function fd(e){return je(e)&&ee(e.href)&&typeof e.userAgent=="string"&&ee(e.sdkVersion)}function hd(e){return je(e)&&ee(e.code)&&typeof e.message=="string"}function ht(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ee(e){return typeof e=="string"&&e.length>0}function Re(e,t){const n=new Set(t);return Object.keys(e).every(r=>n.has(r))}function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Gt=["userInfo","steamLibrary","share","storage","filesystem","clipboard","leaderboard","network","companion"];new Set(Gt);const md=new Set(Gt);function pd(e){return md.has(e)}function Ne(e){if(!an(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,n={};for(const r of e.entries){if(!an(r)||typeof r.key!="string"||!r.key.trim())return{valid:!1,permissions:{}};const i=r.key.trim(),o=i==="network.request"?"network":i;if(t.has(o)||r.status!=="enabled"&&r.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(o),!!pd(o)){if(o==="network"){const s=r.config;if(!an(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};n[o]={key:o,status:r.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(r.config!==null&&r.config!==void 0&&(!an(r.config)||Object.keys(r.config).length>0))return{valid:!1,permissions:{}};n[o]={key:o,status:r.status,config:{}}}}return{valid:!0,permissions:n}}function an(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const yn=["network","companion"];function Ea(e){if(!cn(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>yn.length)return{valid:!1};const t=[],n=new Set;for(const r of e.entries){if(!cn(r,["key","status","config"])||r.status!=="enabled")return{valid:!1};if(typeof r.key!="string"||n.has(r.key))return{valid:!1};if(n.add(r.key),r.key==="network"){if(!cn(r.config,["useOfficialDomain"])||r.config.useOfficialDomain!==!1)return{valid:!1};t.push({key:"network",status:"enabled",config:{useOfficialDomain:!1}})}else if(r.key==="companion"){if(!cn(r.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((r,i)=>yn.indexOf(r.key)-yn.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function gd(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Ne(e.runtimePermissions),n=new Set(e.eligiblePermissionKeys??["network"]),r=[];for(const i of yn)!n.has(i)||e.declaredPermissions[i]?.enabled!==!0||t.valid&&t.permissions[i]?.status==="enabled"||r.push(i==="network"?{key:i,status:"enabled",config:{useOfficialDomain:!1}}:{key:i,status:"enabled",config:{}});return{schema_version:1,revision:e.revision,entries:r}}function qi(e){const t=Ne(e.runtimePermissions),n=Ea(e.localDevGrant),r=t.valid?t.permissions:{};for(const s of Gt)e.declaredPermissions[s]?.enabled!==!0?delete r[s]:s==="network"&&r.network&&(r.network.config.useOfficialDomain=r.network.status==="enabled"&&r.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(n.valid)for(const s of n.grant.entries)e.declaredPermissions[s.key]?.enabled!==!0||r[s.key]?.status==="enabled"||(r[s.key]=s,i.push(s.key));const o=ya(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:Gt.flatMap(s=>r[s]?[r[s]]:[])},temporaryPermissionKeys:i,grantValid:n.valid}}function ya(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cn(e,t){return ya(e)&&Object.keys(e).length===t.length&&t.every(n=>Object.prototype.hasOwnProperty.call(e,n))}const gt=["identity","profile","steam_account"],Ed=/^[a-z][a-z0-9-]{0,31}$/,wa=["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"];He.map(e=>e.method);function F(e,t,n){return{code:e,message:t,data:n}}function zi(e){return yd(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?F("RUNTIME_ERROR",e.message):F("UNKNOWN_ERROR","小程序运行时异常",e)}function yd(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function wd(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Id=1e3;function Ad(e,t=wd()){if(t.userActivation)return t.userActivation.isActive===!0;const n=t.lastUserInteractionAt,r=t.now??Date.now();return t.activeElement===e&&n!==void 0&&r>=n&&r-n<=Id}const _d="runtime.gate.probe",Ia=new Set(He.map(e=>e.method));class bd{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=la;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,this.handleMessage=this.onMessage.bind(this),this.handleUserInteraction=this.onUserInteraction.bind(this),this.dispatcher=t.dispatcher,this.environmentInfo=t.environmentInfo,this.targetOrigin=t.targetOrigin||"*"}get protocolVersion(){return this.handshaken?this.bridgeVersion:void 0}start(){if(!(this.started||this.destroyed)){this.started=!0,window.addEventListener("message",this.handleMessage);for(const t of["pointerdown","touchend","mousedown","keydown"])window.addEventListener(t,this.handleUserInteraction,!0)}}setTargetOrigin(t){this.targetOrigin=t||"*"}destroy(){if(this.destroyed)return;const t=this.started;this.destroyed=!0,this.started=!1,this.handshaken=!1;try{t&&this.postMessage({namespace:Ge,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:"unload",payload:{timestamp:Date.now()}})}catch{}finally{window.removeEventListener("message",this.handleMessage);for(const n of["pointerdown","touchend","mousedown","keydown"])window.removeEventListener(n,this.handleUserInteraction,!0);this.lastUserInteractionAt=void 0;for(const n of this.operations.values())n.abort("bridge destroyed");this.operations.clear()}}postEvent(t,n){this.destroyed||this.postMessage({namespace:Ge,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:n})}postInternalRequest(t,n,r){this.destroyed||this.postMessage({namespace:Ge,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:n,method:t,payload:r})}postProgress(t,n){this.bridgeVersion===2&&this.postMessage({namespace:Ge,version:2,nonce:this.nonce,type:"event",id:t,method:ha,payload:n})}onMessage(t){if(!this.started||!this.isTrustedMiniProgramMessage(t))return;const n=t.data;if(n.type==="handshake"){this.handleHandshake(n,t.origin);return}if(n.type==="request"){let r=!1;try{r=Ad(this.iframe,{activeElement:document.activeElement,userActivation:navigator.userActivation,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{r=!1}this.handleRequest(n,r);return}if(n.type==="cancel"&&this.handshaken&&n.id){this.operations.get(n.id)?.abort();return}n.type==="event"&&this.handshaken&&this.onInternalEvent?.(n)}onUserInteraction(t){const n=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||n.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&cd(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,n){const r=t.payload,i=t.version,o=!this.handshaken;if(o){if(this.onHandshake?.(r)===!1)return;this.bridgeVersion=i,i===1&&this.targetOrigin!=="*"&&n&&n!=="null"&&(this.targetOrigin=n),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.environmentInfo&&t.id&&this.postMessage({namespace:Ge,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:fa,payload:{environment:this.environmentInfo}}),this.postEvent("ready",{timestamp:Date.now()}),o?this.onReady?.(r):this.onDuplicateHandshake?.()}async handleRequest(t,n){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===_d){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,F("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Ia.has(t.method)){this.postResponse(t,void 0,F("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,F("INVALID_PARAMS","bridge request id 重复"));return}const r=new AbortController;this.operations.set(t.id,r);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{postEvent:this.postEvent.bind(this),postProgress:o=>{this.operations.get(t.id)===r&&this.postProgress(t.id,o)},signal:r.signal,trustedUserGesture:n});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==r)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==r)return;const o=zi(i);this.postResponse(t,void 0,o),this.postEvent("error",o)}finally{this.operations.get(t.id)===r&&(this.operations.delete(t.id),r.signal.aborted||r.abort("operation terminal"))}}postResponse(t,n,r){if(!(!this.postMessage({namespace:Ge,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:n,error:r})||!Sd(t.method)))try{this.onResponsePosted?.({method:t.method,outcome:r?"error":"success",...r?{errorCode:r.code}:{}})}catch{}}postMessage(t){const n=this.iframe.contentWindow;return n?(n.postMessage(t,this.targetOrigin),!0):!1}}function Sd(e){return typeof e=="string"&&Ia.has(e)}const Aa="METHOD_FORBIDDEN";function Se(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Aa,t}class J extends Error{code="HOST_REQUEST_UNSUPPORTED";constructor(t="当前 Host 不支持该请求形状",n){super(t),this.name="HostRequestUnsupportedError",n&&"cause"in n&&Object.defineProperty(this,"cause",{configurable:!0,enumerable:!1,value:n.cause}),Object.setPrototypeOf(this,new.target.prototype)}}const mo={[Pn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Rn]:["account.getCurrentUserId","account.onChange","network.request"],[Nn]:["account.getCurrentUserId","account.onChange","network.request"],[Cn]:["account.getCurrentUserId","account.onChange","network.request"],[Tn]:["presentation.setClipboard"],[Ln]:["presentation.showShareMenu"],[kn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Je]:["presentation.applyOrientation"],[Mn]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Un]:["presentation.setNavigationBarStyle"],[xt]:["storage.getRaw"],[Ht]:["storage.setRaw"],[xn]:["network.request"],[Hn]:["network.stream","files.transfer","files.access"],[Fn]:["files.external"],[Bn]:["files.external"],[Vn]:["files.save"],[Ft]:["files.access"],[Bt]:["files.removeFile"],[qn]:["files.access"],[Vt]:["files.access"],[zn]:["files.access"],[qt]:["files.access"],[jn]:["files.access"],[zt]:["files.access"],[Gn]:["files.access"],[jt]:["files.removeDirectory"],[$n]:["files.access"],[Wn]:["files.access"],[Kn]:["presentation.showToast"],[Yn]:["presentation.showLoading"],[Qn]:["presentation.hideLoading"],[Xn]:["presentation.vibrate"],[Jn]:["presentation.setClipboard"],[Zn]:["presentation.close"],[er]:["presentation.reload"],[tr]:["presentation.openAppPage"],[Pe]:["account.getCurrentUserId","account.onChange","network.request"],[me]:["account.onChange","network.request"],[xe]:["account.getCurrentUserId","account.onChange","network.request"],[Ze]:["account.getCurrentUserId","account.onChange","network.request"],[Ae]:["account.onChange","network.request"],[dr]:["companion.getInfo"],[ur]:["companion.getPreparationStatus"],[lr]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[fr]:["companion.cancelPreparation"],[hr]:["companion.getActiveSession"],[mr]:["companion.getInfo","companion.launch"],[pr]:["companion.session.write"],[gr]:["companion.session.closeStdin"],[Er]:["companion.session.terminate"],[yr]:["companion.session.ackOutput"],[wr]:["companion.openAttachment"],[Ir]:["companion.showNotification"]};function vd(e,t){if(t[e]!==!0)throw Se(e)}const Od=32*1024*1024,Dd=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Pd(e){if(e.mode==="request-only")return{network:{request:(r,i)=>e.request(r,i)}};if(e.mode==="override-request")return{network:{request:(r,i)=>e.request(r,i)},...e.stream===void 0?{}:{stream:e.stream}};const{consume:t,stream:n}=e;return{stream:n,network:{async request(r,i){const o=await n.open(r,i);let s;try{const a=await t(o.body,{maxBytes:Od},i);return Rd(o,a)}catch(a){throw s=a,a}finally{try{await n.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Rd(e,t){const n=Object.fromEntries(Object.entries(e.headers).map(([r,i])=>[r,i.join(", ")]));return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:n,data:Nd(t,Td(e,"content-type"))}}function Nd(e,t){Cd(t);let n;try{n=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(r){throw new J("Host network response 不是合法 UTF-8 文本",{cause:r})}if(n.charCodeAt(0)===65279&&(n=n.slice(1)),!t||!Dd.test(t)||n==="")return n;try{return JSON.parse(n)}catch{return n}}function Cd(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new J(`Host network response 不支持 charset=${t}`)}function Td(e,t){return Object.entries(e.headers).find(([n])=>n.toLowerCase()===t)?.[1]?.[0]}function b(e){return typeof e=="function"}function po(e){return(...t)=>{throw Se(e)}}function Y(e){return async(...t)=>{throw Se(e)}}const Ld=(e,t)=>{},kd=()=>()=>{};function Md(e){const t={request:b(e.network?.request)?e.network.request.bind(e.network):Y("network.request")},n={getCurrentUserId:b(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):Y("account.getCurrentUserId"),ensureAuthenticated:b(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Y("account.ensureAuthenticated"),onChange:b(e.account?.onChange)?e.account.onChange.bind(e.account):kd},r={getRaw:b(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Y("storage.getRaw"),setRaw:b(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Y("storage.setRaw")},i={...b(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...b(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:b(e.presentation?.close)?e.presentation.close.bind(e.presentation):Y("presentation.close"),reload:b(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Y("presentation.reload"),openAppPage:b(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Y("presentation.openAppPage"),openWindow:b(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Y("presentation.openWindow"),getViewportMetrics:b(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):po("presentation.getViewportMetrics"),getNavigationBarHeight:b(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):po("presentation.getNavigationBarHeight"),setNavigationBarStyle:b(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Y("presentation.setNavigationBarStyle"),showShareMenu:b(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Y("presentation.showShareMenu"),setScreenshotChromeHidden:b(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):Ld,captureAndShare:b(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Y("presentation.captureAndShare"),showToast:b(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Y("presentation.showToast"),showLoading:b(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Y("presentation.showLoading"),hideLoading:b(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Y("presentation.hideLoading"),vibrate:b(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Y("presentation.vibrate"),setClipboard:b(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Y("presentation.setClipboard")},o=b(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(a=>[a,b(e.companion?.[a])?e.companion[a].bind(e.companion):Y(`companion.${a}`)]));return b(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion)),{network:t,account:n,storage:r,presentation:i,companion:s,...e.files===void 0?{}:{files:e.files},...e.picker===void 0?{}:{picker:e.picker},...e.transfer===void 0?{}:{transfer:e.transfer},...o?{storageDiagnostics:o}:{}}}function Ud(e){const t=xd(e.files?.sandbox),n=b(e.picker?.pickFiles)&&b(e.picker?.pickDirectory),r=b(e.picker?.saveFile),i=t||n||r||b(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getCurrentUserId":b(e.account?.getCurrentUserId),"account.ensureAuthenticated":b(e.account?.ensureAuthenticated),"account.onChange":b(e.account?.onChange),"network.request":b(e.network?.request),"network.stream":b(e.transfer?.network.open)&&b(e.transfer?.network.release),"files.sandbox":t,"files.external":n,"files.save":r,"files.access":i,"files.removeFile":b(o?.remove),"files.removeDirectory":b(e.files?.sandbox.remove),"files.transfer":b(e.transfer?.files.writeResource),"storage.getRaw":b(e.storage?.getRaw),"storage.setRaw":b(e.storage?.setRaw),"presentation.close":b(e.presentation?.close),"presentation.reload":b(e.presentation?.reload),"presentation.openAppPage":b(e.presentation?.openAppPage),"presentation.applyOrientation":b(e.presentation?.applyOrientation),"presentation.openWindow":b(e.presentation?.openWindow),"presentation.getViewportMetrics":b(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":b(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":b(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":b(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":b(e.presentation?.captureAndShare),"presentation.showToast":b(e.presentation?.showToast),"presentation.showLoading":b(e.presentation?.showLoading),"presentation.hideLoading":b(e.presentation?.hideLoading),"presentation.vibrate":b(e.presentation?.vibrate),"presentation.setClipboard":b(e.presentation?.setClipboard),"companion.getInfo":b(e.companion?.getInfo),"companion.getPreparationStatus":b(e.companion?.getPreparationStatus),"companion.prepare":b(e.companion?.prepare),"companion.cancelPreparation":b(e.companion?.cancelPreparation),"companion.getActiveSession":b(e.companion?.getActiveSession),"companion.launch":b(e.companion?.launch),"companion.session.write":b(e.companion?.write),"companion.session.closeStdin":b(e.companion?.closeStdin),"companion.session.terminate":b(e.companion?.terminate),"companion.session.ackOutput":b(e.companion?.ackOutput),"companion.openAttachment":b(e.companion?.openAttachment),"companion.showNotification":b(e.companion?.showNotification)}}function xd(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&b(t.file)&&b(t.directory)&&b(t.create)&&b(t.stat)&&b(t.list)}function go(e,t){return t?.[e]!==!1}function Hd(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("companion.")}function _a(e,t={}){const n={};for(const r of Object.keys(mo)){const o=mo[r].every(a=>e[a]),s=!Hd(r)||!!t.miniProgramDetail?.miniProgramId.trim();n[r]=go(r,t.callerCapabilities)&&go(r,t.hostCapabilities)&&o&&s}return n}function ba(e={},t={}){const n=Ud(e),r=_a(n,t);return{ports:Md(e),primitiveAvailability:n,availablePrimitives:n,effectiveCapabilities:r}}function ji(e,t){if(!t||t===e.signal)return e;const n=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):Fd(e.signal,t);return{...e,signal:n}}function Fd(e,t){const n=new AbortController,r=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",s)},i=a=>{n.signal.aborted||(r(),n.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})),n.signal}function Bd(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 Vd=4,qd=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],zd=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade"]),jd=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Gd=["/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 $d(e,t){const n=Yd(e);return n===null||Eo(n,jd)?!0:t&&Eo(n,Gd)}function Wd(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return qd.some(n=>t===n||t.endsWith(`.${n}`))}function Kd(e){const t=e.trim().toLowerCase();return zd.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Yd(e){let t=e;for(let n=0;n<Vd;n+=1){let r;try{r=decodeURIComponent(t)}catch{return null}if(r===t)return yo(t);t=r}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return yo(t)}function Eo(e,t){return t.some(n=>e===n||e.startsWith(`${n}/`))}function yo(e){const t=[];for(const n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return`/${t.join("/")}`}function l(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,data:n}}function M(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qd(e){return typeof e=="object"&&e!==null}function de(e,t){const n=e.data;if(!Qd(n)||typeof n.status!="string")throw new Error(t);return n}const Sa={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Xd={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.public.detail.get",method:"GET",path:"/user_miniprogram/public/detail",query(e){return{mini_program_id:e.mini_program_id,...e.miniprogram_version?{miniprogram_version:e.miniprogram_version}:{},...e.preview_token?{preview_token:e.preview_token}:{},...e.local_dev_launch_token?{local_dev_launch_token:e.local_dev_launch_token}:{},...e.entry?{entry:e.entry}:{},...e.h_src_parent?{h_src_parent:e.h_src_parent}:{},...e.extra!==void 0?{extra:e.extra}:{}}},parse(e,t){return de(e,"工坊小程序详情加载失败")}};function Jt(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Jd(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Zd(e){const t=de(e,"小程序登录授权接口响应异常"),n=t.result,r={};if(n.login_code&&typeof n.login_code=="object"){const i=n.login_code;r.loginCode={code:i.code,expiresIn:i.expires_in,scopes:i.scopes||[]}}return n.consent_challenge&&typeof n.consent_challenge=="object"&&(r.consentChallenge=Jd(n.consent_challenge)),{...t,result:r}}const eu={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=>({...Jt(e.runtimeContext),challenge:e.challenge}),parse:e=>de(e,"小程序授权取消接口响应异常")},tu={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=>Jt(e.runtimeContext),parse:e=>de(e,"小程序授权撤销接口响应异常")},nu={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=>Jt(e.runtimeContext),parse(e){const t=de(e,"小程序隔离身份接口响应异常"),n=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,...n?{steamId:n}:{}}}}},ru={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=>({...Jt(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Zd(e)},iu={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=>({...Jt(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=de(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}};function ou(e){const t=Ne(e);return t.valid&&t.permissions.network?.status==="enabled"}function va(e,t){return t?e?"server":"local":"legacy"}function su(e,t){return va(ou(e),t)}function wo(e,t){if(e==="server")throw l("SERVER_API_REQUIRED",`${t} 在联网模式下必须通过开发者服务端 OpenAPI 获取`)}function au(e,t){if(e==="local")throw l("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const cu=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],du=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),uu=/authorization|cookie|pkey|password|secret|token/i,Oa=/authorization|cookie|pkey|token|password|secret/i;function Ee(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function lu(e){for(const t of Object.keys(e))if(!du.has(t))throw new J(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of cu)if(Object.prototype.hasOwnProperty.call(e,t)&&Ee(e,t)!==void 0)throw new J(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Ee(e,"bodyEncoding")!==void 0&&Ee(e,"bodyEncoding")!=="json"&&Ee(e,"bodyEncoding")!=="form")throw new J("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Ee(e,"failurePresentation")!==void 0&&Ee(e,"failurePresentation")!=="none")throw new J("endpoint failurePresentation 必须为 none");if(Ee(e,"auth")!==void 0&&Ee(e,"auth")!=="none"&&Ee(e,"auth")!=="optional"&&Ee(e,"auth")!=="required")throw new J("endpoint auth 必须为 none、optional 或 required")}function Ct(e){if(Array.isArray(e))return e.map(Ct);if(!e||typeof e!="object")return e;const t=e,n={};for(const[r,i]of Object.entries(t))uu.test(r)||(n[r]=Ct(i));return n}function Io(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e))Oa.test(n)||(t[n]=r);return t}function fu(e){if(!e)return;const t=Object.keys(e).find(n=>Oa.test(n));if(t)throw new J(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Et extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,Object.setPrototypeOf(this,new.target.prototype)}}function Da(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class yt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Da(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Zt extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Da(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function hu(e,t,n,r,i,o,s,a){return{config:{auth:e.auth,body:Ct(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Io(o),method:e.method,metadata:{endpointId:e.id},query:Ct(r),timeout:e.timeout,url:n},data:Ct(a.data),headers:Io(a.headers)||{},status:a.status,statusText:a.statusText}}async function Ar(e,t,n,r){if(!r||!r.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(r.credentials!=="heybox-session"&&r.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(lu(t),typeof t.id!="string"||!t.id)throw new J("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new J("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(n):t.path;if(typeof i!="string"||!i)throw new J("endpoint path 必须为非空字符串");const o=t.query?await t.query(n):void 0,s=t.body?await t.body(n):void 0,a=t.headers?await t.headers(n):void 0;fu(a);let c;try{c=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:r.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:r.signal,...r.miniProgramDetail===void 0?{}:{miniProgramDetail:r.miniProgramDetail}})}catch(u){throw u instanceof J?u:new yt({endpointId:t.id,cause:u})}if(c.status<200||c.status>=300)throw new Et({endpointId:t.id,status:c.status});const d=hu(t,n,i,o,s,a,r,c);if(t.parse)try{return await t.parse(d,n)}catch(u){throw new Zt({endpointId:t.id,cause:u})}return d.data}const mu=new Set(gt),Gi="steam_account",Pa=new Set(gt.filter(e=>e!==Gi)),pu=1e3;function gu(e){const t=new Set,n=new Map,r=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??va(e.networkEnabled===!0,c);async function u(){if(!c)return{};if(!e.authorizationContext)throw l("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let g;try{g=await e.authorizationContext.get(e.operationContext)}catch{throw l("REQUEST_FAILED","读取 Runtime auth context 失败")}if(g.steamAccount!==c||g.userDataMode!==d)throw l("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const R=g.token.trim();if(!R)throw l("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:R}}const m=e.account.onChange(g=>{h(),f("heybox_app_login_change",{isHeyboxAppLoggedIn:!!g})});function h(){i+=1,a?.abort(),n.clear(),r.clear()}function f(g,R){for(const L of t)try{L(g,R)}catch{}}function I(){const g=e.identity.get()?.miniProgramId?.trim();if(!g)throw l("INVALID_STATE","当前能力缺少 canonical 小程序身份");return g}function E(){if(o||e.operationContext.signal.aborted)throw l("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function w(){E();let g;try{g=await e.account.getCurrentUserId(e.operationContext)}catch(R){throw So(R,e.operationContext.signal,"读取小黑盒账号失败")}return typeof g=="string"&&g.trim()?g.trim():void 0}async function p(g,R){const L=await w();if(i!==R||L!==g)throw l("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function _(g){E();try{await e.account.ensureAuthenticated({trustedUserGesture:g,reason:"runtime_auth",signal:e.operationContext.signal})}catch(L){throw So(L,e.operationContext.signal,"小黑盒登录失败")}const R=await w();if(!R)throw l("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return R}async function A(g,R,L=e.operationContext.signal){try{if(L.aborted)throw Ei();return await _u(Ar(e.network,g,R,{...e.operationContext,credentials:"heybox-session",signal:L}),L)}catch(k){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):k instanceof J?l("REQUEST_UNSUPPORTED",k.message):k instanceof Zt?l("INVALID_RESPONSE","授权接口响应不合法"):k instanceof yt?l("REQUEST_FAILED","授权请求失败"):k instanceof Et?l("REQUEST_FAILED",k.message):Ra(k)?k:l("REQUEST_FAILED","授权请求失败")}}async function v(g,R){await A(eu,{runtimeContext:{miniProgramId:g,...await u()},challenge:R}).catch(()=>{})}function x(g){const R=async()=>{const k=_o(e.operationContext.signal);a=k;try{return await g(k.signal)}finally{a===k&&(a=void 0),k.abort()}},L=s.then(R,R);return s=L.then(()=>{},()=>{}),L}async function S(g,R,L,k,U){if(!L)throw await v(g,R.challenge),l("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await v(g,R.challenge),l("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return x(async W=>{await p(k,U);const j=await T(g,R.displayedScopes,W);await p(k,U);let X;try{X=await e.authPresentation.confirmAuthorization({miniProgramId:g,scopes:R.displayedScopes,...j,signal:W})}catch(ne){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await p(k,U),await v(g,R.challenge),Eu("REQUEST_FAILED","授权确认界面执行失败",ne))}if(await p(k,U),X.status!=="granted")throw await v(g,R.challenge),l("AUTHORIZATION_CANCELLED","用户取消授权");const K=Iu(X.grantedScopes,R.displayedScopes,c);if(!K.includes("identity"))throw await v(g,R.challenge),l("AUTHORIZATION_CANCELLED","用户拒绝授权");return K})}async function T(g,R,L){const k=_o(L),U=setTimeout(()=>k.abort(),pu);try{const W=Au(e.miniProgramPresentation),[j,X]=await Promise.all([W?Promise.resolve(W):C(g,k.signal),R.includes("profile")?O(k.signal):Promise.resolve(void 0)]);return{...j?{miniProgram:j}:{},...X?{userProfile:X}:{}}}finally{clearTimeout(U),k.abort()}}async function C(g,R){try{const L=e.identity.get()?.version?.trim(),k=await A(Xd,{mini_program_id:g,...L?{miniprogram_version:L}:{}},R),U=st(k,"小程序公开资料"),W=mt(U.name),j=mt(U.icon_url);return W||j?{...W?{name:W}:{},...j?{avatarUrl:j}:{}}:void 0}catch{return}}async function O(g){try{const R=await A(Sa,void 0,g),L=st(R,"账号基础信息"),k=mt(L.display_username),U=mt(L.display_avatar);return k||U?{...k?{nickname:k}:{},...U?{avatar:U}:{}}:void 0}catch{return}}async function y(g,R){if(au(d,"auth.login"),!c&&g.includes(Gi))throw l("INVALID_PARAMS","auth.login 参数不合法");const L=I(),k=await _(R),U=i,W=await A(ru,{runtimeContext:{miniProgramId:L,...await u()},scopes:g});await p(k,U);const j=st(W,"小程序登录"),X=bo(j,"loginCode"),K=bo(j,"consentChallenge");if(X===K)throw l("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let ne;if(X)ne=Ao(j.loginCode,c);else{const rt=yu(j.consentChallenge,c),it=await S(L,rt,R,k,U);await p(k,U);const on=await A(iu,{runtimeContext:{miniProgramId:L,...await u()},challenge:rt.challenge,selectedScopes:it});if(await p(k,U),ne=Ao(st(on,"小程序登录确认"),c),ne.scopes.some(fe=>!it.includes(fe)))throw l("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}r.clear();for(const rt of ne.scopes)r.add(rt);return f("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),f("user_info_authorization_change",Tr(r,c)),ne}async function D(g,R){const L=i,k=await A(nu,{runtimeContext:{miniProgramId:R,...await u()}});await p(g,L);const U=wu(st(k,"用户本地身份"),c);for(const W of c?gt:Pa)r.add(W);return f("user_info_authorization_change",Tr(r,c)),U}function N(g){E();const R=I(),L=`${g}\0${R}`,k=n.get(L);if(k)return k;const U=D(g,R).finally(()=>{n.get(L)===U&&n.delete(L)});return n.set(L,U),U}async function P(g){if(!g)throw l("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const R=I(),L=i,k=await w();if(!k)throw l("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const U=await A(tu,{runtimeContext:{miniProgramId:R,...await u()}});await p(k,L),st(U,"用户授权撤销"),h(),f("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{login:y,getOrCreateLocalIdentity:N,getAuthorization:()=>Tr(r,c),revoke:P,onEvent(g){return t.add(g),()=>t.delete(g)},dispose(){o||(o=!0,h(),m(),t.clear())}}}function Eu(e,t,n){const r=l(e,t);return Object.defineProperty(r,"cause",{configurable:!0,enumerable:!1,value:n}),r}function st(e,t){if(!M(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const n=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,r=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(r,n)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Ao(e,t){if(!M(e))throw l("INVALID_RESPONSE","login code 必须是对象");const n=nr(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!n.includes("identity"))throw l("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:n}}function yu(e,t){if(!M(e))throw l("INVALID_RESPONSE","授权 challenge 必须是对象");const n=nr(e.requestedScopes,"challenge requestedScopes",t),r=nr(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||!n.length||!n.includes("identity")||!r.length||!r.includes("identity")||n.some(i=>!r.includes(i)))throw l("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:n,displayedScopes:r}}function wu(e,t){if(!M(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw l("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const n=e.appUserId.trim();if(!t)return{appUserId:n};if(e.steamId!==void 0&&typeof e.steamId!="string")throw l("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const r=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return r?{appUserId:n,steamId:r}:{appUserId:n}}function Iu(e,t,n){const r=nr(e,"授权选择 scopes",n);if(r.some(i=>!t.includes(i)))throw l("INVALID_RESPONSE","授权选择包含未展示的 scope");return r}function mt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Au(e){const t=mt(e?.name),n=mt(e?.avatarUrl);return t||n?{...t?{name:t}:{},...n?{avatarUrl:n}:{}}:void 0}function _o(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 _u(e,t){return t.aborted?Promise.reject(Ei()):new Promise((n,r)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>r(Ei()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>n(a)),a=>o(()=>r(a)))})}function Ei(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function nr(e,t,n){const r=n?mu:Pa;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!r.has(i))||new Set(e).size!==e.length)throw l("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Tr(e,t){const n=t?gt:gt.filter(r=>r!==Gi);return Object.fromEntries(n.map(r=>[r,e.has(r)?"granted":"not_requested"]))}function bo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ra(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function So(e,t,n){return t.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Ra(e)?e:l("REQUEST_FAILED",n)}const bu=new Set(gt);function Su(e){return{[Pn]:async(t,n)=>e.authorization.login(vu(t),n.trustedUserGesture)}}function vu(e){if(e===void 0)return["identity"];if(!M(e)||Object.keys(e).some(t=>t!=="scopes"))throw vo();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!bu.has(t))||new Set(e.scopes).size!==e.scopes.length)throw vo();return[...e.scopes]}function vo(){return l("INVALID_PARAMS","auth.login 参数不合法")}const Ou={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.delete.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/current/delete",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return de(e,"排行榜记录删除接口响应异常")}},Du={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/current",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return de(e,"当前排行榜记录接口响应异常")}},Pu={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.info.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/info",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return de(e,"排行榜信息接口响应异常")}},Ru={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.list.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/list",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{},limit:e.limit,...e.cursor?{cursor:e.cursor}:{}}},parse(e,t){return de(e,"排行榜列表接口响应异常")}},Nu={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.submit.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/submit",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{},score:e.score,...e.extra===void 0?{}:{extra:JSON.stringify(e.extra)}}},parse(e,t){return de(e,"排行榜提交接口响应异常")}};function wn(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Oo(e){return e instanceof J?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function $(e){if(e.aborted)throw wn()}function z(e,t,n={}){if(t.aborted&&!n.invokeWhenAborted)return Promise.reject(wn());let r;try{r=e()}catch(i){return Promise.reject(Oo(i))}return t.aborted?(Promise.resolve(r).catch(()=>{}),Promise.reject(wn())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(wn()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(r).then(d=>a(()=>i(d)),d=>a(()=>o(Oo(d))))})}const Cu="default",Tu=/^[A-Za-z0-9_-]{1,64}$/,Lu=300*1e3,ku=250,Mu=3,Uu={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"};class xu{constructor(t){this.options=t,this.unsubscribeAccountChange=Fu(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;disposed=!1;handleTerminalAbort=()=>this.dispose();async submit(t){this.assertUsable();const n=this.accountGeneration,r=this.readMiniProgramId();await this.requireCurrentUser(n);const i=await this.request(Nu,{miniProgramId:r,...t});this.assertAccountGeneration(n);const o=bt(i,Pe);return this.invalidateMutableReads(this.createBucketKey(r,t.key)),Lr(o,Pe)}getList(t){this.assertUsable();const n=this.readMiniProgramId(),r=this.createBucketKey(n,t.key),i=St("list",t.limit,t.cursor??null);return this.read(r,"list",i,async()=>{const o=await this.request(Ru,{miniProgramId:n,...t}),s=bt(o,me);if(!_e(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw G(`${me} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw G(`${me} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>Lr(a,me)),...typeof s.cursor=="string"&&s.cursor?{cursor:s.cursor}:{},hasMore:s.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const n=this.accountGeneration,r=this.readMiniProgramId(),i=await this.requireCurrentUser(n),o=this.createBucketKey(r,t.key),s=St("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(Du,{miniProgramId:r,...t}),c=bt(a,xe);if(!_e(c))throw G(`${xe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Lr(c.entry,xe)})}async deleteCurrentUserEntry(t){this.assertUsable();const n=this.accountGeneration,r=this.readMiniProgramId();await this.requireCurrentUser(n);const i=await this.request(Ou,{miniProgramId:r,...t});this.assertAccountGeneration(n);const o=bt(i,Ze);if(this.invalidateMutableReads(this.createBucketKey(r,t.key)),!_e(o)||typeof o.deleted!="boolean")throw G(`${Ze} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const n=this.readMiniProgramId(),r=this.createBucketKey(n,t.key);return this.read(r,"info",St("info"),async()=>{const i=await this.request(Pu,{miniProgramId:n,...t}),o=bt(i,Ae);if(!_e(o)||typeof o.key!="string"||!Tu.test(o.key))throw G(`${Ae} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw G(`${Ae} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw G(`${Ae} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw G(`${Ae} 返回的 rankLimit 必须是非负整数`);return{key:o.key,order:o.order,rankLimit:o.rank_limit}})}read(t,n,r,i){this.assertUsable();const o=this.getOrCreateBucket(t),s=o?.caches[n],a=s?.get(r);if(a&&a.expiresAt>Date.now())return Promise.resolve(a.value);s?.delete(r);const c=St(t,r),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,m=o?.generation,h=i().then(f=>(this.assertAccountGeneration(u),o&&s&&o.generation===m&&(n==="list"?s.size>=ku&&s.delete(s.keys().next().value):s.clear(),s.set(r,{expiresAt:Date.now()+Lu,value:f})),f)).finally(()=>{this.inflight.get(c)?.promise===h&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:h}),h}getOrCreateBucket(t){const n=this.buckets.get(t);if(n)return n;if(this.pruneExpiredBuckets(),this.buckets.size>=Mu)return;const r={generation:0,caches:{list:new Map,current:new Map,info:new Map}};return this.buckets.set(t,r),r}invalidateMutableReads(t){this.invalidateInflight(t);const n=this.buckets.get(t);n&&(n.generation+=1,n.caches.list.clear(),n.caches.current.clear())}invalidateForAccountChange(){this.accountGeneration+=1,this.buckets.clear(),this.inflight.clear()}invalidateInflight(t){for(const[n,r]of this.inflight)r.bucketKey===t&&this.inflight.delete(n)}pruneExpiredBuckets(){const t=Date.now();for(const[n,r]of this.buckets)Po(r,t),this.isBucketEmpty(n,r)&&this.buckets.delete(n)}removeEmptyBucket(t,n){Po(n,Date.now()),this.buckets.get(t)===n&&this.isBucketEmpty(t,n)&&this.buckets.delete(t)}isBucketEmpty(t,n){return![...this.inflight.values()].some(r=>r.bucketKey===t)&&Object.values(n.caches).every(r=>r.size===0)}async requireCurrentUser(t){this.assertUsable();let n;try{n=await z(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(r){throw No(r)?r:Ro()}if(this.assertAccountGeneration(t),typeof n!="string"||!n.trim())throw he("UNAUTHORIZED","当前用户未登录");return n.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw he("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,n){return St(t,n??Cu)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw he("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,n){this.assertUsable();const r={request:async(i,o)=>(this.assertUsable(),this.options.network.request(i,o))};try{return await z(()=>Ar(r,t,n,{...this.options.operationContext,credentials:"heybox-session"}),this.options.operationContext.signal)}catch(i){throw No(i)||yi(i,"REQUEST_UNSUPPORTED")?i:i instanceof J?he("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求"):i instanceof yt&&yi(i.cause,"INVALID_STATE")?i.cause:i instanceof Et&&(i.status===401||i.status===403)?he("UNAUTHORIZED","当前用户未登录"):i instanceof yt||i instanceof Et?Ro():i instanceof Zt?G(i.cause instanceof Error?i.cause.message:"排行榜响应不合法"):G(i instanceof Error?i.message:"排行榜响应不合法")}}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($(this.options.operationContext.signal),this.disposed)throw he("INVALID_STATE","Cloud capability 已释放")}}function Hu(e){return new xu(e)}function Fu(e,t){try{return e.onChange(t)}catch(n){if(yi(n,Aa))return()=>{};throw n}}function bt(e,t){if(!_e(e)||typeof e.status!="string")throw G(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Bu(e);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw G(`${t} 响应缺少 result`);return e.result}function Lr(e,t){if(!_e(e))throw G(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw G(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw G(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw G(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw G(`${t} 返回的 score 必须是有限数字`);if(!_e(e.extra))throw G(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw G(`${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 Bu(e){if(e.status==="login"||e.status==="relogin")throw he("UNAUTHORIZED",Pt(e.msg)||"当前用户未登录");const t=Do(e.result)??Do(e),n=Pt(t?.user_message)||Pt(e.msg)||Pt(t?.developer_message)||"排行榜请求失败";throw t?he(Vu(t),n,{status:e.status,sbe:t}):he("HEYBOX_API_ERROR",n,{status:e.status})}function Do(e){return _e(e)&&_e(e.sbe)?e.sbe:void 0}function Vu(e){const t=Pt(e.developer_message);if(t&&/^[A-Z][A-Z0-9_]+$/.test(t))return t;const n=e.code;if(typeof n=="number"&&Number.isInteger(n))return Uu[n]||t||"HEYBOX_API_ERROR";if(typeof n=="string"){const r=/^([A-Za-z][A-Za-z0-9_]*)(?:\(\d+\))?$/.exec(n.trim());if(r?.[1])return r[1]}return t||"HEYBOX_API_ERROR"}function Po(e,t){for(const n of Object.values(e.caches))for(const[r,i]of n)i.expiresAt<=t&&n.delete(r)}function St(...e){return JSON.stringify(e)}function _e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function yi(e,t){return _e(e)&&e.code===t}function he(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,data:n}}function G(e){return he("INVALID_RESPONSE",e)}function Ro(){return he("REQUEST_FAILED","排行榜请求失败")}function No(e){return e instanceof Error&&e.name==="AbortError"}const qu=/^[A-Za-z0-9_-]{1,64}$/,Co=20,zu=100,To=2048;function ju(e){const t=Hu(e);return{handlers:{[Pe]:async r=>t.submit(Gu(r)),[me]:async r=>t.getList($u(r)),[xe]:async r=>t.getCurrentUserEntry(kr(r,xe)),[Ze]:async r=>t.deleteCurrentUserEntry(kr(r,Ze)),[Ae]:async r=>t.getInfo(kr(r,Ae))},dispose:()=>t.dispose()}}function Gu(e){const t=$i(e,Pe,!1);if(Wi(t,["key","score","extra"],Pe),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw be("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Ki(t.key,Pe),score:t.score,...t.extra===void 0?{}:{extra:Wu(t.extra)}}}function $u(e){if(e===void 0)return{limit:Co};const t=$i(e,me,!0);Wi(t,["key","limit","cursor"],me);const n=t.limit===void 0?Co:t.limit;if(typeof n!="number"||!Number.isInteger(n)||n<=0||n>zu)throw be("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw be("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Ki(t.key,me),limit:n,...t.cursor===void 0?{}:{cursor:t.cursor}}}function kr(e,t){if(e===void 0)return{};const n=$i(e,t,!0);return Wi(n,["key"],t),Ki(n.key,t)}function $i(e,t,n){if(e===void 0&&n)return{};if(!Na(e))throw be("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Wi(e,t,n){const r=Object.keys(e).find(i=>!t.includes(i));if(r)throw be("INVALID_PARAMS",`${n} 不支持参数 ${r}`)}function Ki(e,t){if(e===void 0)return{};if(typeof e!="string"||!qu.test(e))throw be("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function Wu(e){if(!Na(e))throw be("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw be("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw be("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>To)throw be("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${To} 字节`);return e}function Na(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function be(e,t){return{code:e,message:t}}const Ku=new Set(["stdio","attachments","notifications"]),Ca=new Set(["windows-x64","macos-arm64"]),Yu=new Set(["unsigned","valid","invalid","unknown"]),Qu=/^[a-f0-9]{64}$/,Xu=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Ju=new Set(wa),Zu=new Set([...wa,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Ta=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 el(e){const t=async(r,i,o,s)=>{const a=tl(r);try{Ie(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Ie(i.signal),c}catch(c){throw Ii(c,s)}},n=async(r,i,o)=>{if(!o.trustedUserGesture)throw l("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw l("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>nl(d,i)).catch(d=>{throw Ii(d)});Ie(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:r,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Ie(o.signal),c.status!=="granted")throw l("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[dr]:(r,i)=>t(r,i,async(o,s)=>wi(await e.companion.getInfo(o,s),o)),[ur]:(r,i)=>t(r,i,async(o,s)=>Lo(await e.companion.getPreparationStatus(o,s))),[lr]:(r,i)=>t(r,i,async(o,s)=>{const a=Lo(await e.companion.getPreparationStatus(o,s));return Ie(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await n("prepare",o,i),Ie(i.signal),wi(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(ka(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[fr]:(r,i)=>t(r,i,(o,s)=>e.companion.cancelPreparation(o,s)),[hr]:(r,i)=>t(r,i,async(o,s)=>ko(await e.companion.getActiveSession(o,s),o)),[mr]:(r,i)=>t(r,i,async(o,s)=>{const a=ko(await e.companion.getActiveSession(o,s),o);return Ie(i.signal),a||(await n("launch",o,i),Ie(i.signal),Ma(await e.companion.launch(o,s),o))}),[pr]:(r,i)=>at(r,i,e,"write"),[gr]:(r,i)=>at(r,i,e,"closeStdin"),[Er]:(r,i)=>at(r,i,e,"terminate"),[yr]:(r,i)=>at(r,i,e,"ackOutput"),[wr]:async(r,i)=>{const o=await at(r,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Ir]:(r,i)=>at(r,i,e,"showNotification")}}function tl(e){if(!M(e)||typeof e.alias!="string"||!Ed.test(e.alias))throw l("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Ie(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function at(e,t,n,r){if(!M(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw l("INVALID_PARAMS","Companion Session controller 不合法");try{Ie(t.signal);const i=await n.companion[r](rl(e,r),{...n.operationContext,signal:t.signal});return Ie(t.signal),i}catch(i){throw Ii(i)}}function pe(){throw l("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function La(e){return!Array.isArray(e)||e.some(t=>!Ku.has(t))?pe():Object.freeze([...new Set(e)])}function wi(e,t){return!M(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Ca.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!Yu.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?pe():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:La(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function nl(e,t){const n=wi(e,t);return!M(e)||e.sha256===void 0?n:typeof e.sha256!="string"||!Qu.test(e.sha256)?pe():Object.freeze({...n,sha256:e.sha256})}function ka(e){return M(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):pe():pe()}function Lo(e){return M(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:ka(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&M(e.error)&&typeof e.error.code=="string"&&Ju.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:Ta[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):pe():pe()}function Ma(e,t){return!M(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Ca.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?pe():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:La(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function ko(e,t){return e===void 0?void 0:Ma(e,t)}function rl(e,t){const n=e,r={sessionId:n.sessionId,controllerGeneration:n.controllerGeneration};if(t==="write"){if(!ga(n.data))throw l("INVALID_PARAMS","Companion write data 不合法");return{...r,data:new Uint8Array(n.data)}}if(t==="ackOutput"){if(n.stream!=="stdout"&&n.stream!=="stderr"||!Number.isSafeInteger(n.sequence)||Number(n.sequence)<0)throw l("INVALID_PARAMS","Companion output ack 不合法");return{...r,stream:n.stream,sequence:n.sequence}}if(t==="openAttachment"){if(typeof n.id!="string"||!n.id)throw l("INVALID_PARAMS","Companion Attachment ID 不合法");return{...r,id:n.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(n.category)))throw l("INVALID_PARAMS","Companion notification category 不合法");return{...r,category:n.category}}return r}function il(e){return!M(e)||!Xu.has(String(e.reason))?pe():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):pe():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?pe():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function ol(e){if(!M(e)||!M(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,n=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||!ga(t.data)?void 0:{type:e.type,payload:{sessionId:n,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:n,exit:il(t.exit)}}}catch{return}if(e.type==="companion.session.ownershipLost"&&Number.isSafeInteger(t.controllerGeneration)&&Number(t.controllerGeneration)>=0)return{type:e.type,payload:{sessionId:n,controllerGeneration:t.controllerGeneration}}}function Ii(e,t){return M(e)&&typeof e.code=="string"&&Zu.has(e.code)?l(e.code,Ta[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&M(e)&&e.name==="AbortError"?l(t,"Companion 准备已取消"):l("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Mo=5e3,Uo=1e4;function Qe(e){throw{code:"INVALID_PARAMS",message:e}}function Ua(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xa(e,t,n){const r=Object.keys(e).filter(i=>!t.includes(i));r.length&&Qe(`${n} 不支持字段: ${r.join(", ")}`)}function sl(e){if(e===void 0)return{intensity:"light",delay:0};if(!Ua(e))return Qe("device.vibrate 参数必须是对象");xa(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return Qe("device.vibrate intensity 必须是 light、medium 或 heavy");const n=t,r=e.delay??0;return typeof r!="number"||!Number.isInteger(r)||r<0||r>Mo?Qe(`device.vibrate delay 必须是 0-${Mo} 的整数毫秒`):{intensity:n,delay:r}}function al(e){return Ua(e)?(xa(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?Qe("device.setClipboard text 必须是非空字符串"):e.text.length>Uo?Qe(`device.setClipboard text 不能超过 ${Uo} 字符`):{text:e.text}):Qe("device.setClipboard 参数必须是对象")}function cl(e){return{[Xn]:async t=>{$(e.operationContext.signal),await z(()=>e.presentation.vibrate(sl(t),e.operationContext),e.operationContext.signal)},[Jn]:async t=>{$(e.operationContext.signal),await z(()=>e.presentation.setClipboard(al(t),e.operationContext),e.operationContext.signal)}}}const dl=new Set(["METHOD_FORBIDDEN","FILE_PICKER_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_ENCODING_INVALID","DIRECTORY_LIST_LIMIT_EXCEEDED","DIRECTORY_NOT_EMPTY","FILE_IO_FAILED"]),ul={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 Yi(e){const t=Ha(e),n=t&&dl.has(t)?l(t,ul[t]??"文件操作失败"):l("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(n,"cause",{value:e,enumerable:!1}),n}function De(e){try{return e()}catch(t){throw Yi(t)}}function Ha(e){try{if(!M(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function Fa(e,t,n={}){const r=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=r==="readwrite",o=n.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:r,create:i?(s,a)=>e.create(s,a):Ai,remove:o?s=>e.remove(s):Va,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Ai,stat:s=>e.stat(s)})}function Ba(e,t,n={}){const r=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=r==="readwrite",o=n.allowRemove!==!1,s=o&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:r,file:a=>Fa(e.file(a),r,{allowRemove:o}),directory:a=>Ba(e.directory(a),r,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Ai,remove:s?(a,c)=>e.remove(a,c):Va,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Ai(){return Promise.reject(l("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Va(){return Promise.reject(l("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const xo=1024;class ll{constructor(t,n){this.files=t,this.miniProgramDetail=n}handles=new Map;disposed=!1;dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,n="external",r){this.assertCanonicalDetail();const i=this.prepareFile(t,n,r),[o]=this.registerMany([i]);return dn(i.handle,{kind:"file",handleId:o})}registerFiles(t,n="external",r,i){this.assertCanonicalDetail();const o=De(()=>{if(!Array.isArray(t))throw l("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw l("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>xo)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw l("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],n,r))}return c}),s=this.registerMany(o);return o.map((a,c)=>dn(a.handle,{kind:"file",handleId:s[c]}))}registerDirectory(t,n="external",r){this.assertCanonicalDetail();const i=this.prepareDirectory(t,n,r),[o]=this.registerMany([i]);return Fo(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Vi(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const n=hl(t);if("handleId"in n){const s=this.readDirect(n.handleId,"file");return{ref:n,...s}}const r=this.resolveRoot(n.root),i=$t(n.relativePath),o=this.prepareFile(De(()=>r.hostHandle.file(i)),r.origin,r.handle.mode);return{ref:n,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const n=ml(t);if("handleId"in n){const s=this.readDirect(n.handleId,"directory");return{ref:n,...s}}const r=this.resolveRoot(n.root),i=n.relativePath==="."?".":$t(n.relativePath),o=this.prepareDirectory(i==="."?r.hostHandle:De(()=>r.hostHandle.directory(i)),r.origin,r.handle.mode,!0);return{ref:n,...o}}describeFile(t,n){return Vo(t),dn(t,n)}describeListedEntries(t,n,r){return this.assertCanonicalDetail(),De(()=>{if(!Array.isArray(n))throw l("FILE_IO_FAILED","Host 返回了无效目录列表");const i=n.length;if(i>r)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(n,s))throw l("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,n[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,n){return De(()=>{if(M(n)&&n.kind==="file"){const r=this.prepareFile(n,t.origin,t.handle.mode);return dn(r.handle,Ho(t.ref,r.handle.name))}if(M(n)&&n.kind==="directory"){const r=this.prepareDirectory(n,t.origin,t.handle.mode);return Fo(r.handle,fl(t.ref,r.handle.name))}throw l("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,n){this.assertCanonicalDetail();const r=en(n),i=this.prepareFile(De(()=>t.hostHandle.file(r)),t.origin,t.handle.mode);return{ref:Ho(t.ref,r),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw l("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,n,r){return De(()=>{Vo(t);const i=r??t.mode;return Bo(t.mode,i),{handle:Fa(t,i,{allowRemove:n==="sandbox"}),hostHandle:t,origin:n}})}prepareDirectory(t,n,r,i=!1){return De(()=>{El(t,i);const o=r??t.mode;return Bo(t.mode,o),{handle:Ba(t,o,{allowRemove:n==="sandbox"}),hostHandle:t,origin:n}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>xo)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const n=new Set,r=t.map(()=>{for(let i=0;i<8;i+=1){const o=pl();if(!this.handles.has(o)&&!n.has(o))return n.add(o),o}throw l("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(r[o],i)),r}readDirect(t,n){if(!gl(t))throw l("FILE_ACCESS_REVOKED","文件授权句柄无效");const r=this.handles.get(t);if(!r)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(r.handle.kind!==n||r.hostHandle.kind!==n)throw l("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return r}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Se("files.sandbox");return this.prepareDirectory(De(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Se("files")}}function $t(e){if(!Bi(e))throw l("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function en(e,t="文件名"){const n=$t(e);if(n.includes("/"))throw l("INVALID_PARAMS",`${t} 只能是 basename`);return n}function Ho(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:$t(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function fl(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:$t(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function dn(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function Fo(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Bo(e,t){if(t==="readwrite"&&e!=="readwrite")throw l("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function hl(e){return Vi(e)||qa(),e}function ml(e){return pa(e)||qa(),e}function qa(){throw l("INVALID_PARAMS","文件引用不合法")}function pl(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw l("FILE_IO_FAILED","当前环境缺少安全随机数能力");const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function gl(e){return/^[0-9a-f]{32}$/.test(e)}function Vo(e){if(!M(e)||e.kind!=="file"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.create!="function"||typeof e.read!="function"||typeof e.write!="function"||typeof e.stat!="function")throw l("FILE_IO_FAILED","Host 返回了无效 File handle");en(e.name,"Host File name")}function El(e,t=!1){if(!M(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 l("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw l("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&en(e.name,"Host Directory name")}const qo=1e3,yl=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function wl(e){const t=n=>ji(e.operationContext,n.signal);return{files:{[Fn]:async(n,r)=>{Mr(r);const i=Ur(e.picker),o=Il(n),s=await se(()=>i.pickFiles(o,t(r)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Bn]:async(n,r)=>{Mr(r);const i=Ur(e.picker),o=Al(n),s=await se(()=>i.pickDirectory(o,t(r)));return e.registry.registerDirectory(s,"external",o.mode)},[Vn]:async(n,r)=>{Mr(r);const i=Ur(e.picker),o=_l(n).suggestedName,s=t(r);if(!i.saveFile)throw Se("files.saveFile");const a=await se(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[Ft]:async(n,r)=>{const i=ue(n,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);ct(o.mode),await se(()=>o.create(zo(i),t(r)))},[Bt]:async(n,r)=>{const i=ue(n),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),ct(o.handle.mode),!o.handle.remove)throw Se(Bt);await se(()=>o.handle.remove(t(r)))},[qn]:async(n,r)=>{const i=ue(n);return jo(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(r));if(!M(o)||o.kind!=="file")throw $o()})},[Vt]:async(n,r)=>{const i=ue(n),o=Go(await se(()=>e.registry.resolveFile(i.target).read(t(r))));try{const s=new TextDecoder("utf-8",{fatal:!0}).decode(o);return s.charCodeAt(0)===65279?s.slice(1):s}catch{throw l("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[zn]:async(n,r)=>{const i=ue(n,["content"]);typeof i.content!="string"&&le("content 必须是字符串");const o=e.registry.resolveFile(i.target);ct(o.mode),await se(()=>o.write(new TextEncoder().encode(i.content),t(r)))},[qt]:async(n,r)=>{const i=ue(n),o=await se(()=>e.registry.resolveFile(i.target).read(t(r)));return Go(o)},[jn]:async(n,r)=>{const i=ue(n,["content"]),o=e.registry.resolveFile(i.target);ct(o.mode),await se(()=>o.write(Sl(i.content),t(r)))},[zt]:async(n,r)=>{const i=ue(n),o=await se(()=>e.registry.resolveFile(i.target).stat(t(r)));return vl(o)}},directory:{[Gn]:async(n,r)=>{const i=ue(n,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);ct(o.mode),await se(()=>o.create(zo(i),t(r)))},[jt]:async(n,r)=>{const i=ue(n,["recursive"]);if(M(i.target)&&i.target.relativePath===".")throw l("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),ct(o.handle.mode),!o.handle.remove)throw Se(jt);await se(()=>o.handle.remove({recursive:i.recursive===void 0?!1:rr(i.recursive,"recursive")},t(r)))},[$n]:async(n,r)=>{const i=ue(n);return jo(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(r));if(!M(o)||o.kind!=="directory")throw $o()})},[Wn]:async(n,r)=>{const i=ue(n,["limit"]),o=bl(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await se(()=>s.handle.list({limit:o},t(r)));return e.registry.describeListedEntries(s,a,o)}}}}function Il(e){if(e===void 0)return{mode:"read",multiple:!1};M(e)||le("pickFiles 参数必须是对象"),_r(e,["mode","accept","multiple"]);const t=za(e.mode,"read"),n=e.multiple===void 0?!1:rr(e.multiple,"multiple");let r;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)))&&le("accept 必须是规范扩展名数组"),r=[...new Set(e.accept)]),{mode:t,multiple:n,...r===void 0?{}:{accept:r}}}function Al(e){return e===void 0?{mode:"read"}:(M(e)||le("pickDirectory 参数必须是对象"),_r(e,["mode"]),{mode:za(e.mode,"read")})}function _l(e){return M(e)||le("saveFile 参数必须是对象"),_r(e,["suggestedName"]),{suggestedName:en(e.suggestedName,"suggestedName")}}function ue(e,t=[]){return(!M(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&le("文件操作参数必须包含 target"),_r(e,["target",...t]),e}function zo(e){return{recursive:e.recursive===void 0?!1:rr(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:rr(e.exclusive,"exclusive")}}function za(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&le("mode 必须是 read 或 readwrite"),e)}function rr(e,t){return typeof e!="boolean"&&le(`${t} 必须是布尔值`),e}function bl(e){if(e===void 0)return qo;if((!Number.isSafeInteger(e)||e<=0)&&le("limit 必须是正整数"),e>qo)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function _r(e,t){const n=Object.keys(e).filter(r=>!t.includes(r));n.length&&le(`不支持字段: ${n.join(", ")}`)}function ct(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Mr(e){if(!e.trustedUserGesture)throw l("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Ur(e){if(!e)throw Se("files.external");return e}async function jo(e){try{return await e(),!0}catch(t){if(yl.has(Ha(t)??""))return!1;throw Yi(t)}}async function se(e){try{return await e()}catch(t){throw Yi(t)}}function Sl(e){return e instanceof Uint8Array||le("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&le("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Go(e){if(!(e instanceof Uint8Array))throw l("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function $o(){return l("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function vl(e){if(!M(e)||e.kind!=="file"||!Ol(e.size))throw l("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Dl(e[t]))throw l("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 Ol(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Dl(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function le(e){throw l("INVALID_PARAMS",e)}const un=4294967296;function Pl(e){const t=new Rl;return t.write(e),t.finish()}class Rl{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<un?(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 n=Nl(t),r=n.byteLength;if(r<32)this.writeUint8(160+r);else if(r<256)this.writeUint8(217),this.writeUint8(r);else if(r<65536)this.writeUint8(218),this.writeUint16(r);else if(r<un)this.writeUint8(219),this.writeUint32(r);else throw new Error("share extra string is too long");this.writeBytes(n)}writeArray(t){const n=t.length;n<16?this.writeUint8(144+n):n<65536?(this.writeUint8(220),this.writeUint16(n)):(this.writeUint8(221),this.writeUint32(n));for(const r of t)this.write(r)}writeMap(t){const n=Object.keys(t),r=n.length;r<16?this.writeUint8(128+r):r<65536?(this.writeUint8(222),this.writeUint16(r)):(this.writeUint8(223),this.writeUint32(r));for(const i of n)this.writeString(i),this.write(t[i])}ensureCapacity(t){const n=this.offset+t;if(n<=this.bytes.byteLength)return;const r=new Uint8Array(Math.max(n,this.bytes.byteLength*2));r.set(this.bytes),this.bytes=r,this.view=new DataView(r.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/un),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/un)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Nl(e){const t=new Uint8Array(Cl(e));let n=0,r=0;for(;n<e.length;){let i=e.charCodeAt(n++);if(i>=55296&&i<=56319&&n<e.length){const o=e.charCodeAt(n);o>=56320&&o<=57343&&(n+=1,i=((i&1023)<<10)+(o&1023)+65536)}i<128?t[r++]=i:i<2048?(t[r++]=i>>6&31|192,t[r++]=i&63|128):i<65536?(t[r++]=i>>12&15|224,t[r++]=i>>6&63|128,t[r++]=i&63|128):(t[r++]=i>>18&7|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=i&63|128)}return t}function Cl(e){let t=0,n=0;for(;n<e.length;){let r=e.charCodeAt(n++);if(r<128)t+=1;else if(r<2048)t+=2;else{if(r>=55296&&r<=56319&&n<e.length){const i=e.charCodeAt(n);i>=56320&&i<=57343&&(n+=1,r=((r&1023)<<10)+(i&1023)+65536)}t+=r<65536?3:4}}return t}function ja(e){_i(e);const t=Pl(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 _i(e,t=0,n=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(n.has(e))throw new Error("extra value must not contain cycles");if(n.add(e),Array.isArray(e)){if(e.length>64)throw new Error("extra array is too large");for(const o of e)_i(o,t+1,n);n.delete(e);return}const r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==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");_i(s,t+1,n)}n.delete(e)}const Tl=["pc","console","mobile"],Ll=["game","wiki"];function ir(e){throw{code:"INVALID_PARAMS",message:e}}function kl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fe(e,t){return typeof e!="string"||!e.trim()?ir(t):e.trim()}function Wo(e,t,n){return typeof e!="string"||!t.includes(e)?ir(n):e}function Ml(e){const t={target:"game_detail",appId:Fe(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Wo(e.gameType,Tl,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Wo(e.page,Ll,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Fe(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Fe(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Ul(e){return{target:"user_detail",userId:Fe(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function xl(e){const t={target:"post_detail",linkId:Fe(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Fe(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Fe(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Hl(e){const t={target:"mini_program",miniProgramId:Fe(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Fl(e){return kl(e)?e.target==="game_detail"?Ml(e):e.target==="user_detail"?Ul(e):e.target==="post_detail"?xl(e):e.target==="mini_program"?Hl(e):ir("navigation.openAppPage target 不支持"):ir("navigation.openAppPage options 必须是对象")}function Bl(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 Vl(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function ql(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 zl(e){const t=e;return t.target==="game_detail"?Bl(t):t.target==="user_detail"?Vl(t):ql(t)}function Ga(e){throw{code:"INVALID_PARAMS",message:e}}function Ko(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Ga(`${t} 不支持参数`)}function jl(e){return{[Zn]:async t=>{$(e.operationContext.signal),Ko(t,"navigation.close"),await z(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[er]:async t=>{$(e.operationContext.signal),Ko(t,"navigation.reload"),await z(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[tr]:async t=>{$(e.operationContext.signal);const n=Fl(t);if(n.target==="mini_program"){let r;if(n.extra!==void 0)try{r=ja(n.extra)}catch{Ga("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}await z(()=>e.presentation.openWindow({miniProgramId:n.miniProgramId,...r===void 0?{}:{extra:r}},e.operationContext),e.operationContext.signal);return}await z(()=>e.presentation.openAppPage(zl(n),e.operationContext),e.operationContext.signal)}}}const Gl=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),$l=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Wl=new Set(["range","if-range","a-im"]),Kl=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"]),Yl=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,ln={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Ql{constructor(t){this.signal=t}phase="initial";transition(t){if(ln[t]<=ln[this.phase])throw l("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(ln[this.phase]<ln.committed&&this.signal.aborted)throw Ka()}normalizeHostError(t,n){return this.throwIfCancelled(),Qi(t,n,this.signal)}}async function Xl(e,t,n){const r=n.transfer,i=n.fileRegistry;if(!r||!i)throw Se("network.download");const o=ji(n.operationContext,t.signal),s=new Ql(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await tf(e,i,o)}catch(u){throw s.normalizeHostError(u,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await r.network.open(e.request,o)}catch(u){throw s.normalizeHostError(u,"network")}let d=!1;try{s.throwIfCancelled(),s.transition("validate");const u=rf(c);of(c,u);const m=sf(c.status,u);if(e.maxBytes!==void 0&&m.expectedBytes!==void 0&&m.expectedBytes>e.maxBytes)throw l("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const h=nf(e,a,u,i);let f=0;const I=Zl(m.expectedBytes,e.maxBytes);Hr(t,xr(0,m));const E={...o,onProgress(_){!Number.isSafeInteger(_)||_<f||I!==void 0&&_>I||(f=_,Hr(t,xr(f,m)))}};s.transition("transfer"),d=!0;let w;try{w=await r.files.writeResource(h.hostHandle,c.body,{mode:h.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...m.expectedBytes===void 0?{}:{expectedBytes:m.expectedBytes}},E)}catch(_){throw s.normalizeHostError(_,"transfer")}s.transition("committed"),f=Jl(w,m,f,e.maxBytes),Hr(t,xr(f,m));const p=i.describeFile(h.handle,h.ref);return s.transition("completed"),p}finally{d||ef(r.network,c.body)}}function Jl(e,t,n,r){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=r===void 0?n:Math.min(n,r);try{const o=e?.committedBytes;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=i&&(r===void 0||o<=r))return o}catch{}return i}function Zl(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function ef(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function tf(e,t,n){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return bi(i.handle.mode),await hf(i.handle,n),{kind:"file",...i}}const r=t.resolveDirectoryEntry(e.to);return bi(r.handle.mode),await mf(r.handle,n),{kind:"directory",...r}}function nf(e,t,n,r){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=cf(e,n),o=r.deriveFile(t,i);return bi(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function rf(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 l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!M(e.headers))throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[n,r]of Object.entries(e.headers)){if(n!==n.toLowerCase()||!Gl.has(n)||!Array.isArray(r)||r.length===0)throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(r.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[n]=[...r]}return t}function of(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw l("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:ff(t,$l)});if((t["content-range"]?.length??0)>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function sf(e,t){const n=t["content-length"]??[],r=t["transfer-encoding"]??[];if(n.length>0&&r.length>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&n.some(d=>d!=="0"))throw l("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&r.length>0)throw l("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=n.length===1&&/^(?:0|[1-9]\d*)$/.test(n[0])?Number(n[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=af(t["content-encoding"]),a=e===204||e===205?0:r.length===0&&s?o:void 0,c=a!==void 0;return{...a===void 0?{}:{expectedBytes:a},...c?{total:a}:{},lengthComputable:c}}function af(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function xr(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Hr(e,t){try{e.postProgress(t)}catch{}}function cf(e,t){const n=t["content-disposition"]??[];for(const i of n){const o=df(i);if(o&&In(o))return o}for(const i of n){const o=uf(i);if(o&&In(o))return o}if(e.suggestedName!==void 0)return $a(e.suggestedName);const r=lf(e.url);return r&&In(r)?r:"download.bin"}function df(e){const t=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(e);if(!t)return;const n=t[1].trim().replace(/^"|"$/g,""),r=/^utf-8'[^']*'(.*)$/i.exec(n);if(r)try{return decodeURIComponent(r[1])}catch{return}}function uf(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 lf(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function $a(e){try{en(e,"suggestedName")}catch{throw l("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!In(e))throw l("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function In(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Yl.test(e))}function ff(e,t){return Object.fromEntries(Object.entries(e).filter(([n])=>t.has(n)).map(([n,r])=>[n,r.join(", ")]))}async function hf(e,t){try{const n=await e.stat(t);if(!n||n.kind!=="file")throw Wa()}catch(n){throw Qi(n,"file",t.signal)}}async function mf(e,t){try{const n=await e.stat(t);if(!n||n.kind!=="directory")throw Wa()}catch(n){throw Qi(n,"file",t.signal)}}function bi(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","下载目标只允许读取")}const pf={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 Qi(e,t,n){if(n.aborted)return Ka();const r=gf(e);if(r&&Kl.has(r)){const o=l(r,pf[r]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?l("DOWNLOAD_TIMEOUT","下载网络请求超时"):l("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?l("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):l("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function gf(e){return M(e)&&typeof e.code=="string"?e.code:void 0}function Wa(){return l("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Ka(){return l("DOWNLOAD_CANCELLED","下载已取消")}function Ef(e){if(!e)return;const t=Object.keys(e).find(n=>Wl.has(n.trim().toLowerCase()));if(t)throw l("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Xi="withCredentials",yf=new Set(["url","method","params","data","headers","timeout",Xi]),wf=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Xi]),If=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Yo=3e4,Qo=2*1024*1024,Af=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,_f=/[\u0000-\u0008\u000A-\u001F\u007F]/,bf=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Sf="network.request 不支持 multipart/form-data,请使用专用上传能力";function vf(e){const t=Of(e.runtimePermissions),n=Ff(e.allowedHttpOrigins);return{[Hn]:async(r,i)=>{const o=Pf(r,{permission:t,allowedHttpOrigins:n});return Xl(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[xn]:async(r,i)=>{const o=ji(e.operationContext,i?.signal);$(o.signal);const s=Df(r,{permission:t,allowedHttpOrigins:n});let a;try{a=await z(()=>e.network.request(s,o),o.signal)}catch(c){throw qf(c)?c:zf(c,"REQUEST_UNSUPPORTED")?H("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):H("REQUEST_FAILED","网络请求失败")}return Vf(a)}}}function Of(e){const t=Ne(e),n=t.permissions.network;return{enabled:t.valid&&n?.status==="enabled",useOfficialDomain:t.valid&&n?.status==="enabled"&&n.config.useOfficialDomain===!0}}function Df(e,t){const n=br(e,"network.request 参数必须是对象"),r=Object.keys(n).filter(c=>!yf.has(c));if(r.length>0)throw H("INVALID_PARAMS",`network.request 不支持字段: ${r.join(", ")}`);Qa(n,"network.request");const i=Ya(n,t,"network.request"),o=Nf(n.method),s=n.data;s!==void 0&&Lf(s),Mf(i.headers,s);const a=Uf(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 Pf(e,t){const n=br(e,"network.download 参数必须是对象"),r=Object.keys(n).filter(c=>!wf.has(c));if(r.length>0)throw H("INVALID_PARAMS",`network.download 不支持字段: ${r.join(", ")}`);Qa(n,"network.download");const i=Ya(n,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw H("INVALID_PARAMS","network.download timeout 必须是有限正数");Ef(i.headers);const o=Vi(n.to),s=pa(n.to);if(!o&&!s)throw H("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(n.suggestedName!==void 0||n.overwrite!==void 0))throw H("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(n.suggestedName!==void 0){if(typeof n.suggestedName!="string")throw H("INVALID_PARAMS","suggestedName 必须是字符串");a=$a(n.suggestedName)}if(n.overwrite!==void 0&&typeof n.overwrite!="boolean")throw H("INVALID_PARAMS","overwrite 必须是布尔值");if(n.maxBytes!==void 0&&(!Number.isSafeInteger(n.maxBytes)||n.maxBytes<=0))throw H("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:n.to,targetKind:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...n.overwrite===void 0?{}:{overwrite:n.overwrite},...n.maxBytes===void 0?{}:{maxBytes:n.maxBytes}}}function Ya(e,t,n){const r=Rf(e.url,t.allowedHttpOrigins,n),i=Wd(r);if(i&&!t.permission.useOfficialDomain)throw H("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if($d(r.pathname,i))throw H("PERMISSION_DENIED",`${n} 不允许访问 Runtime 或账号敏感接口`);return{url:r,official:i,params:e.params===void 0?void 0:{...br(e.params,`${n} params 必须是对象`)},headers:e.headers===void 0?void 0:Cf(e.headers,n),timeout:Tf(e.timeout,n)}}function Rf(e,t,n="network.request"){if(typeof e!="string"||!e.trim())throw H("INVALID_PARAMS",`${n} url 必须是 HTTP(S) URL`);let r;try{r=new URL(e)}catch{throw H("INVALID_PARAMS",`${n} url 必须是 HTTP(S) URL`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw H("INVALID_PARAMS",`${n} url 必须是 HTTP(S) URL`);if(r.username||r.password)throw H("INVALID_PARAMS",`${n} url 不允许包含用户信息`);if(r.protocol==="http:"&&!t.has(r.origin))throw H("PERMISSION_DENIED",`${n} 生产环境只允许 HTTPS`);return r}function Nf(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw H("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!If.has(t))throw H("INVALID_PARAMS","network.request method 不合法");return t}function Cf(e,t="network.request"){const n=br(e,`${t} headers 必须是 Record<string, string>`),r={};for(const[i,o]of Object.entries(n)){const s=i.trim();if(!s||s!==i||!Af.test(s)||typeof o!="string"||_f.test(o))throw H("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Kd(s))throw H("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);r[s]=o}return r}function Qa(e,t){const n=e[Xi];if(n!==void 0&&typeof n!="boolean")throw H("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Tf(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw H("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Yo)throw H("INVALID_PARAMS",`${t} timeout 不能超过 ${Yo}ms`);return e}}function Lf(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw H("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(kf(e)>Qo)throw H("INVALID_PARAMS",`network.request data 不能超过 ${Qo} 字节`)}function kf(e){if(typeof e=="string")return Fr(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return Fr(e.toString());try{const t=JSON.stringify(e);return t?Fr(t):0}catch{throw H("INVALID_PARAMS","network.request data 必须可序列化")}}function Mf(e,t){const n=Xa(e),r=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(n?.includes("multipart/form-data")||r)throw H("INVALID_PARAMS",Sf)}function Uf(e,t,n){if(t===void 0)return;const r=Xa(e);return r?.includes("application/x-www-form-urlencoded")?"form":r?.includes("application/json")?"json":typeof URLSearchParams<"u"&&t instanceof URLSearchParams||n&&(Array.isArray(t)||Hf(t))?"form":xf(t)?"json":void 0}function Xa(e){return e?Object.entries(e).find(([n])=>n.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function xf(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function Hf(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ff(e){const t=new Set;for(const n of e??[])try{const r=new URL(n);r.protocol==="http:"&&!r.username&&!r.password&&r.pathname==="/"&&!r.search&&!r.hash&&Bf(r.hostname)&&t.add(r.origin)}catch{}return t}function Bf(e){const t=e.toLowerCase();if(t==="[::1]")return!0;const n=t.split(".").map(Number);return n.length!==4||n.some((r,i)=>!/^\d+$/.test(t.split(".")[i])||r<0||r>255)?!1:n[0]===127||n[0]===10||n[0]===172&&n[1]>=16&&n[1]<=31||n[0]===192&&n[1]===168}function Vf(e){return Object.keys(e.headers).some(Xo)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Xo(t)))}:e}function Xo(e){const t=e.trim().toLowerCase();return bf.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function qf(e){return e instanceof Error&&e.name==="AbortError"}function zf(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function br(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw H("INVALID_PARAMS",t);return e}function Fr(e){return new TextEncoder().encode(e).length}function H(e,t){return{code:e,message:t}}function jf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gf(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 $f(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topicIds 必须是数组"],values:[]};const t=[],n=new Set,r=[];for(const i of e){const o=Gf(i);o?n.has(o)||(n.add(o),r.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:r}}function Wf(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topics 必须是数组"],values:[]};const t=[],n=new Set,r=[];for(const i of e){const o=typeof i=="string"?i.trim():"";!o||o.startsWith("#")||o.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):n.has(o)||(n.add(o),r.push(o))}return{invalidMessages:t,values:r}}function Ja(e,t){if(e==null)return{};if(!jf(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const n=$f(e.topicIds),r=Wf(e.topics),i=[...n.invalidMessages,...r.invalidMessages];let o=n.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||r.values.length?{...o.length?{topicIds:o}:{},...r.values.length?{topics:r.values}:{}}:void 0;return s||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:s}}function Kf(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function Yf(e){try{if(Kf(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function te(e){throw{code:"INVALID_PARAMS",message:e}}function tn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Si(e,t){return typeof e!="string"||!e.trim()?te(t):e}function Qf(e,t){const n=Si(e,t);try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?te(t):n}catch{return te(t)}}function Xf(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Za(e,t,n){const r=e.identity.get(),i=r?.miniProgramId.trim();if(!i)return te(`${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=r?.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),n!==void 0&&s.searchParams.set("extra",n),s.href}catch{return te(`${t} 缺少有效的小程序分享地址`)}}function Jf(e,t){if(!tn(e))return te("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return te("share.showShareMenu 不支持自定义 url");const n=e.channel;if(n!==void 0&&!Xf(n))return te("share.showShareMenu channel 不合法");const r=ec(e.extra,"share.showShareMenu");return{title:Si(e.title,"share.showShareMenu title 必须是非空字符串"),description:Si(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Za(t,"share.showShareMenu",r),...e.imageUrl===void 0?{}:{imageUrl:Qf(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...n===void 0?{}:{channel:n}}}function ec(e,t){if(e!==void 0)try{return ja(e)}catch{return te(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function tc(e,t){return e.invalidMessage&&await z(()=>Yf(t.environment),t.operationContext.signal)?te(e.invalidMessage):e.post}function Jo(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?n:t}function Zf(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Jo(t.windowWidth,0),height:Jo(t.windowHeight,0)}}function vi(e,t){const n=Number(e);return!Number.isFinite(n)||n<0?te(t):n}function Zo(e,t){const n=Number(e);return!Number.isFinite(n)||n<=0?te(t):n}function eh(e){return tn(e)?{left:vi(e.left,"share.screenshot rect.left 必须是非负数字"),top:vi(e.top,"share.screenshot rect.top 必须是非负数字"),width:Zo(e.width,"share.screenshot rect.width 必须是正数"),height:Zo(e.height,"share.screenshot rect.height 必须是正数")}:te("share.screenshot rect 必须是对象")}function th(e,t){if(e!=null&&!tn(e))return te("share.screenshot 参数必须是对象");const n=e??{};return n.saveToAlbum!==void 0&&typeof n.saveToAlbum!="boolean"?te("share.screenshot saveToAlbum 必须是布尔值"):{rect:n.rect===void 0?Zf(t):eh(n.rect),...n.delay===void 0?{}:{delay:vi(n.delay,"share.screenshot delay 必须是非负数字")},...n.saveToAlbum===void 0?{}:{saveToAlbum:n.saveToAlbum}}}async function nh(e,t){$(t.operationContext.signal);const n=Jf(e,t);let r=Ja(e.post,{maxTopicIds:1,method:"share.showShareMenu"});n.channel&&r.post&&(r={invalidMessage:r.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await tc(r,t);return z(()=>t.presentation.showShareMenu({...n,post:i},t.operationContext),t.operationContext.signal)}async function rh(e,t){if($(t.operationContext.signal),e!==void 0&&!tn(e))return te("share.copyLink 参数必须是对象");const n=ec(e?.extra,"share.copyLink"),r=Za(t,"share.copyLink",n);return await z(()=>t.presentation.setClipboard({text:r},t.operationContext),t.operationContext.signal),r}async function ih(e,t){$(t.operationContext.signal);const n=th(e,t.presentation),r=Ja(tn(e)?e.post:void 0,{method:"share.screenshot"}),i=await tc(r,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=oh();let a=!1,c;try{a=!0,await z(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),c={status:"fulfilled",value:await z(()=>t.presentation.captureAndShare({...n,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(u){c={status:"rejected",error:u}}const d=a?await sh(t.presentation,s,t.operationContext.signal):void 0;if(c.status==="rejected")throw c.error;if(d)throw d;return c.value}function oh(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function sh(e,t,n){let r;try{r=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await z(()=>r,n,{invokeWhenAborted:!0})}catch(i){if(n.aborted)return i}}function ah(e){return{[Tn]:(t,n)=>rh(t,e),[Ln]:(t,n)=>nh(t,e),[kn]:(t,n)=>ih(t,e)}}const ch=128,dh=/^[A-Za-z0-9_-]+$/;function uh(e){const t=lh(e),n={[xt]:async r=>{$(e.operationContext.signal);const i=es(r,xt,e.storageLimits?.maxKeyLength),o=await z(()=>e.storage.getRaw(Br(t(),i),e.operationContext),e.operationContext.signal);return{data:ts(o)}},[Ht]:async r=>{$(e.operationContext.signal);const i=nc(r,"storage.setStorage 参数必须是对象"),o=es(i,Ht,e.storageLimits?.maxKeyLength),s=fh(i.data,e.storageLimits?.maxValueBytes);await z(()=>e.storage.setRaw(Br(t(),o),s,e.operationContext),e.operationContext.signal)}};return e.storageDiagnostics?{handlers:n,diagnostics:{getSnapshot:async()=>{$(e.operationContext.signal);let r;try{r=t()}catch{throw Be("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const i=Br(r,"");return(await z(()=>e.storageDiagnostics.listRaw(e.operationContext),e.operationContext.signal)).filter(s=>s.key.startsWith(i)).map(s=>{const a=s.value;return{area:s.area,key:s.key.slice(i.length),value:ts(a),serializedValue:a,bytes:rc(a)}}).sort((s,a)=>s.key.localeCompare(a.key))}}}:{handlers:n}}function lh(e){let t=!1,n;return()=>{if(!t){const r=e.identity.get()?.miniProgramId.trim();if(r)n=`id_${ns(r)}`;else{const i=e.anonymousStorageScope?.trim();i&&(n=`anon_${ns(i)}`)}t=n!==void 0}if(!n)throw Be("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return n}}function Br(e,t){return`hb_miniprogram_${e}_${t}`}function es(e,t,n=ch){const i=nc(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Be("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>n||!dh.test(i))throw Be("INVALID_PARAMS",`storage key 仅支持 1-${n} 位字母、数字、下划线和连字符`);return i}function fh(e,t){let n;try{n=JSON.stringify(e)}catch{throw Be("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof n!="string")throw Be("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&rc(n)>t)throw Be("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return n}function ts(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function nc(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Be("INVALID_PARAMS",t);return e}function ns(e){return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:hh(e)}function hh(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function rc(e){return new TextEncoder().encode(e).length}function Be(e,t){return{code:e,message:t}}const rs=120;function Me(e){throw{code:"INVALID_PARAMS",message:e}}function Ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ic(e,t,n){const r=Object.keys(e).filter(i=>!t.includes(i));r.length&&Me(`${n} 不支持字段: ${r.join(", ")}`)}function mh(e){if(!Ji(e))return Me("ui.showToast 参数必须是对象");if(ic(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Me("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>rs)return Me(`ui.showToast message 不能超过 ${rs} 字符`);const n=e.status;if(n!==void 0&&n!=="success"&&n!=="error")return Me("ui.showToast status 必须是 success 或 error");const r=n;return{message:t,...r===void 0?{}:{status:r}}}function ph(e){return e===void 0?{dismissible:!1}:Ji(e)?(ic(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Me("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Me("ui.showLoading 参数必须是对象")}function gh(e){e!==void 0&&(!Ji(e)||Object.keys(e).length)&&Me("ui.hideLoading 不支持参数")}function Eh(e){return{[Kn]:async t=>{$(e.operationContext.signal),await z(()=>e.presentation.showToast(mh(t),e.operationContext),e.operationContext.signal)},[Yn]:async t=>{$(e.operationContext.signal),await z(()=>e.presentation.showLoading(ph(t),e.operationContext),e.operationContext.signal)},[Qn]:async t=>{$(e.operationContext.signal),gh(t),await z(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const yh={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return de(e,"当前用户首页资料接口响应异常")}},wh=3e4;function Ih(e,t,n={}){const r=n.ttlMs??wh;let i=0,o,s;async function a(){let d;try{d=await Ar(e,yh,void 0,{...t,credentials:"heybox-session"})}catch(u){throw t.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):u instanceof J?l("REQUEST_UNSUPPORTED",u.message):u instanceof Zt?l("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof yt?l("REQUEST_FAILED","user home_v2 请求失败"):u instanceof Et?l("REQUEST_FAILED",u.message):_h(u)?u:l("REQUEST_FAILED","user home_v2 请求失败")}return Ah(d,"user home_v2")}function c(d){const u=Date.now();if(o?.userId===d&&o.expiresAt>u)return Promise.resolve(o.value);if(s?.userId===d&&s.generation===i)return s.promise;const m=i,h=a().then(f=>(i===m&&(o={userId:d,value:f,expiresAt:Date.now()+r}),f)).finally(()=>{s?.promise===h&&(s=void 0)});return s={userId:d,generation:m,promise:h},h}return{get:c,clear(){i+=1,o=void 0,s=void 0}}}function Ah(e,t){if(!M(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const n=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,r=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(r,n)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function _h(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}const bh={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.game.steam.get_game_list.get",method:"GET",path:"/game/steam/get_game_list",query(e){return{userid:e.userId,...e.steamId?{steam_id:e.steamId}:{},limit:e.limit,offset:e.offset,sort:e.sort,need_hidden:e.includeHidden,...e.personalInformationOpen===void 0?{}:{personal_infomation_open:e.personalInformationOpen},...e.q?{q:e.q}:{}}},parse(e,t){return de(e,"Steam 游戏库接口响应异常")}},oc=20,Sh=100,sc=0,ac="weeks",vh=100,Oh=new Set(["weeks","all","achieved"]);function Dh(e){const t=Ih(e.network,e.operationContext),n=new Map;let r=0,i=!1;const o=e.account.onChange(()=>{r+=1,t.clear(),n.clear()}),s=e.authorization.onEvent((E,w)=>{E==="user_info_authorization_change"&&"identity"in w&&w.identity==="denied"&&(r+=1,t.clear(),n.clear())});function a(){if(i||e.operationContext.signal.aborted)throw l("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function c(){const E=e.identity.get()?.miniProgramId?.trim();if(!E)throw l("INVALID_STATE","用户能力缺少 canonical 小程序身份");return E}async function d(){a();let E;try{E=await e.account.getCurrentUserId(e.operationContext)}catch(w){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):os(w)?w:l("REQUEST_FAILED","读取小黑盒账号失败")}return typeof E=="string"&&E.trim()?E.trim():void 0}async function u(E,w){const p=await d();if(r!==w||p!==E)throw l("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function m(E,w){try{return await Ar(e.network,E,w,{...e.operationContext,credentials:"heybox-session"})}catch(p){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):p instanceof J?l("REQUEST_UNSUPPORTED",p.message):p instanceof Zt?l("INVALID_RESPONSE","用户接口响应不合法"):p instanceof yt?l("REQUEST_FAILED","用户请求失败"):p instanceof Et?l("REQUEST_FAILED",p.message):os(p)?p:l("REQUEST_FAILED","用户请求失败")}}async function h(){c();const E=r,w=await d();if(!w)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[p,_]=await Promise.all([e.authorization.getOrCreateLocalIdentity(w),f(w)]);return await u(w,E),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:p.appUserId,profile:_,...p.steamId?{steam_id:p.steamId}:{}}}}function f(E){const w=n.get(E);if(w)return w;const p=m(Sa,void 0).then(_=>{const A=is(_,"账号基础信息");if(A.display_username!==void 0&&typeof A.display_username!="string")throw l("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(A.display_avatar!==void 0&&typeof A.display_avatar!="string")throw l("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:A.display_username??"",avatar:A.display_avatar??""}}).catch(()=>({nickname:"",avatar:""})).finally(()=>{n.get(E)===p&&n.delete(E)});return n.set(E,p),p}async function I(E){const w=Ph(E);c();const p=r,_=await d();if(!_)return{isLogin:!1,isBound:!1,data:null};const A=await t.get(_);await u(_,p);const v=Zi(A.steam_id_info);if(Object.keys(v).length===0)return{isLogin:!0,isBound:!1,data:null};const x=await m(bh,{userId:_,...w,personalInformationOpen:cc(v.personal_infomation_open??v.personal_information_open)});await u(_,p);const S=is(x,"Steam 游戏库");return{isLogin:!0,isBound:!0,data:Lh(S,w)}}return{getInfo:h,getSteamGameList:I,dispose(){i||(i=!0,r+=1,o(),s(),t.clear(),n.clear())}}}function Ph(e){if(e==null)return{limit:oc,offset:sc,sort:ac,includeHidden:!1};if(!M(e))throw Ue("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(r=>!["steamId","limit","offset","sort","q","includeHidden"].includes(r));if(t)throw Ue(`user.getSteamGameList 不支持字段: ${t}`);const n={limit:Rh(e.limit),offset:Nh(e.offset),sort:Ch(e.sort),includeHidden:Th(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim())throw Ue("user.getSteamGameList steamId 必须是非空字符串");n.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ue("user.getSteamGameList q 必须是字符串");const r=e.q.trim();r&&(n.q=r.slice(0,vh))}return n}function Rh(e){if(e===void 0)return oc;if(!Number.isInteger(e)||Number(e)<1)throw Ue("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Sh)}function Nh(e){if(e===void 0)return sc;if(!Number.isInteger(e)||Number(e)<0)throw Ue("user.getSteamGameList offset 必须是非负整数");return Number(e)}function Ch(e){if(e===void 0)return ac;if(typeof e!="string"||!Oh.has(e))throw Ue("user.getSteamGameList sort 不支持");return e}function Th(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ue("user.getSteamGameList includeHidden 必须是 boolean");return e}function Lh(e,t){if(!Array.isArray(e.game_list))throw l("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const n=e.game_list.map(kh).filter(a=>a!==void 0),r=or(e.total),i=t.offset+n.length,o={gameList:n,hasMore:n.length>=t.limit,nextOffset:i};r!==void 0&&(o.total=r,o.hasMore=i<r);const s=cc(e.is_me);return s!==void 0&&(o.isMe=s),o}function kh(e){const t=Zi(e),n=or(t.appid),r=or(t.steam_appid)??n,i=eo(t.name);if(n===void 0||r===void 0||!i)return;const o={appid:n,steamAppid:r,name:i};Tt(o,"image",t.image),Tt(o,"icon",t.appicon??t.icon),Lt(o,"playtimeForever",t.playtime_forever),Lt(o,"playtime2Weeks",t.playtime_2weeks);const s=Uh(t.external_tags??t.tags);s.length&&(o.tags=s);const a=Mh(t.price);return a&&(o.price=a),o}function Mh(e){const t=Zi(e),n={};return Tt(n,"current",t.current),Tt(n,"initial",t.initial),Lt(n,"discount",t.discount),Lt(n,"lowestPrice",t.lowest_price),Tt(n,"deadlineDate",t.deadline_date),Lt(n,"deadlineTimestamp",t.deadline_timestamp),Object.keys(n).length?n:void 0}function is(e,t){if(!M(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const n=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,r=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(r,n)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Zi(e){return M(e)?e:{}}function eo(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Uh(e){return Array.isArray(e)?e.map(eo).filter(Boolean):[]}function or(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function cc(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function Tt(e,t,n){const r=eo(n);r&&Object.assign(e,{[t]:r})}function Lt(e,t,n){const r=or(n);r!==void 0&&Object.assign(e,{[t]:r})}function Ue(e){return l("INVALID_PARAMS",e)}function os(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function xh(e){const t=e.userDataMode??su(e.runtimePermissions,e.steamAccount===!0);return{[Rn]:async n=>(ss(n,"user.getInfo"),wo(t,"user.getInfo"),e.user.getInfo()),[Nn]:async(n,r)=>{ss(n,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Cn]:async n=>(wo(t,"user.getSteamGameList"),e.user.getSteamGameList(n))}}function ss(e,t){if(e!==void 0)throw l("INVALID_PARAMS",`${t} 不接收入参`)}const Hh="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K";function Fh(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute("aria-label","退出全屏"),t.style.cssText=["position:fixed","right:0","top:50%","z-index:2147483647","box-sizing:border-box","width:48px","height:44px","padding:5px 4px","border:0","border-radius:5px","display:flex","flex-direction:column","align-items:center","justify-content:center","gap:3px","background:rgba(57,61,64,.9)","color:#fff",'font:400 9px/12px "PingFang SC",sans-serif',"cursor:pointer","touch-action:manipulation","opacity:1","transform:translateY(-50%)","transition:opacity .2s,transform .2s"].join(";");const n=document.createElement("img");n.src=Hh,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const r=document.createElement("span");r.textContent="退出全屏",r.style.whiteSpace="nowrap",t.append(n,r);let i=!0,o=!1,s=!1,a;function c(){clearTimeout(a),a=setTimeout(()=>{i=!1,t.style.opacity="0.18",t.style.transform="translate(38px, -50%)",t.setAttribute("aria-label","展开退出全屏按钮")},1e3)}function d(){i=!0,t.style.opacity="1",t.style.transform="translateY(-50%)",t.setAttribute("aria-label","退出全屏"),c()}async function u(){if(!(o||s)){if(!i){d();return}s=!0,clearTimeout(a);try{await e()}catch{}finally{s=!1,o||d()}}}return t.addEventListener("click",u),document.body.append(t),c(),{dispose(){o=!0,clearTimeout(a),t.removeEventListener("click",u),t.remove()}}}const dc=1e4;function Bh(e){const t=new AbortController;let n;const r=()=>{n??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},t.abort()};e.addEventListener("abort",r,{once:!0}),e.aborted&&r();const i=setTimeout(()=>{n??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},t.abort()},dc);return{signal:t.signal,async run(o){try{return await z(o,t.signal)}catch(s){throw n??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",r)}}}function uc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 参数必须是对象"};const{orientation:t,fullscreen:n}=e;if(t!==void 0&&t!=="portrait"&&t!=="landscape")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay orientation 必须是 portrait 或 landscape"};if(n!==void 0&&typeof n!="boolean")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay fullscreen 必须是布尔值"};if(t===void 0&&n===void 0)throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 至少设置 orientation 或 fullscreen"};return{orientation:t,fullscreen:n}}function Vr(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function fn(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function Vh(e){let t,n,r={mode:"portrait",hideCapsule:!1},i={mode:"portrait",hideCapsule:!1},o;function s(){o?.dispose(),o=void 0}function a(h){if(!h.hideCapsule){s();return}o??=Fh(()=>m.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(h,f){if(t===h){if(t=void 0,clearTimeout(h.timer),e.operationContext.signal.removeEventListener("abort",d),"error"in f)h.controller.abort();else if(n={options:h.options,result:f.result},r=h.options,a(h.options),e.onApplied?.(h.options),f.result.supported&&!Vr(i,h.options)){i={...h.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:h.source})}catch{}}for(const I of h.subscribers)I.dispose(),"error"in f?I.reject(f.error):I.resolve(f.result);h.subscribers.clear()}}function d(){t&&c(t,{error:fn()})}function u(h,f){return new Promise((I,E)=>{const w=()=>{h.subscribers.delete(p),p.dispose(),E(fn()),h.subscribers.size===0&&c(h,{error:fn()})},p={resolve:I,reject:E,dispose:()=>f?.removeEventListener("abort",w)};h.subscribers.add(p),f?.addEventListener("abort",w,{once:!0}),f?.aborted&&w()})}const m={async apply(h,f,I="api"){if($(e.operationContext.signal),f?.aborted)throw fn();const E=uc(h),w=t?.options??r,p={mode:E.orientation??w.mode,hideCapsule:E.fullscreen??w.hideCapsule};p.mode==="landscape"&&(p.hideCapsule=!0);const _=e.presentation.applyOrientation;if(!_)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&Vr(t.options,p))return u(t,f);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),n&&Vr(n.options,p))return n.result;n=void 0;const A={options:p,source:I,controller:new AbortController,subscribers:new Set};t=A;const v=u(A,f);return e.operationContext.signal.addEventListener("abort",d,{once:!0}),f||(A.timer=setTimeout(()=>{c(A,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},dc)),z(()=>_.call(e.presentation,p,{...e.operationContext,signal:A.controller.signal}),A.controller.signal).then(x=>c(A,{result:x??{supported:!0}}),x=>c(A,{error:x})),v},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return m}function as(e){throw{code:"INVALID_PARAMS",message:e}}function vt(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?n:t}function lc(e,t){const n=Number(e);return Number.isFinite(n)&&n>=0?n:t}function hn(e,t,n){return Math.min(lc(e,t),n)}async function qh(e){try{return lc(await e.getNavigationBarHeight(),0)}catch{return 0}}function zh(e,t,n,r){const i=hn(e.safeArea?.left,0,t),o=Math.max(i,hn(e.safeArea?.right,t,t)),s=hn(e.safeArea?.top,r,n),a=Math.max(s,hn(e.safeArea?.bottom,n,n));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function cs(e){const t=e.getViewportMetrics(),n=vt(t.windowWidth,0),r=vt(t.windowHeight,0),i=await qh(e);return{pixelRatio:vt(t.pixelRatio,1),screenWidth:vt(t.screenWidth,n),screenHeight:vt(t.screenHeight,r),windowWidth:n,windowHeight:r,statusBarHeight:i,safeArea:zh(t,n,r,i),screenTop:i}}function jh(e){const t=new AbortController,n={...e,operationContext:{...e.operationContext,signal:t.signal}};let r=!1,i=0,o,s;const a=()=>{if(r||n.operationContext.signal.aborted||!n.onViewportChange)return;const m=++i;cs(n.presentation).then(h=>{if(r||n.operationContext.signal.aborted||m!==i)return;const f=JSON.stringify(h);f!==o&&(o=f,n.onViewportChange?.(h))}).catch(()=>{})},c=Vh({...n,onApplied:a}),d=()=>{r||(r=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?d():(s=n.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[Je]:async(m,h)=>c.apply(m,h?.signal),[Mn]:async()=>($(n.operationContext.signal),cs(n.presentation)),[Un]:async m=>{if($(n.operationContext.signal),typeof m!="object"||m===null||Array.isArray(m))return as("viewport.setNavigationBarStyle 参数必须是对象");const h=m.foregroundStyle;if(h!=="light"&&h!=="dark")return as("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await z(()=>n.presentation.setNavigationBarStyle(h,e.operationContext),n.operationContext.signal)}},applyOrientation:(m,h)=>c.apply({orientation:m.mode,fullscreen:m.hideCapsule},h),notifyChange:()=>{o=void 0,a()},dispose:d}}const Gh=new Map(He.map(e=>[e.method,e]));function mn(e,t,n){return{code:e,message:t,...n===void 0?{}:{data:n}}}function $h(e){const t=Ne(e);return n=>{if(n.requirement.kind==="none")return{allowed:!0};for(const r of n.requirement.permissions){const i=t.valid?t.permissions[r]:void 0;if(!i)return{allowed:!1,code:"PERMISSION_NOT_DECLARED",message:`小程序未声明权限: ${r}`,data:{permission:r,method:n.method}};if(i.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${r}`,data:{permission:r,method:n.method}}}return{allowed:!0}}}function Wh(e,t,n,r){let i;try{i=Promise.resolve(e(t,n))}catch(o){return r.aborted?Promise.resolve({status:"dropped"}):Promise.reject(o)}return r.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((o,s)=>{let a=!1;const c=u=>{a||(a=!0,r.removeEventListener("abort",d),u())},d=()=>c(()=>o({status:"dropped"}));r.addEventListener("abort",d,{once:!0}),i.then(u=>c(()=>o({status:"handled",value:u})),u=>c(()=>s(u)))})}function Kh(e){const t=$h(e.runtimePermissions),n=Ne(e.runtimePermissions);let r=0,i=0,o=0;return{async dispatch(s,a,c){const d=e.now??Yh,u=e.onTrace?d():0,m=e.onTrace?`cap_${++r}`:"",h=s===Je?++i:void 0;let f;try{if(e.terminalSignal.aborted)throw mn("RUNTIME_DESTROYED","小程序 Runtime 已终止");vd(s,e.effectiveCapabilities);const I=Gh.get(s);if(!I)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const E=t(I),w=!E.allowed&&n.valid&&n.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!E.allowed&&!w)throw mn(E.code,E.message,E.data);const p=e.handlers[s];if(!p)throw new Error(`Capability method ${s} 缺少 handler`);h!==void 0&&(f=Bh(c.signal));const _=f?{...c,signal:f.signal}:c,A=async()=>{for(const x of e.policies??[]){const S=await x.evaluate({method:s,payload:a,capability:I});if(e.terminalSignal.aborted||f?.signal.aborted)throw ls();if(!S.allowed)throw mn(S.code,S.message,S.data)}if(e.terminalSignal.aborted||f?.signal.aborted)throw ls();if(h!==void 0){if(uc(a),h<o)throw mn("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=h}return p(a,_)},v=await Wh(()=>f?f.run(A):A(),void 0,c,e.terminalSignal);return ds(e.onTrace,us(m,s,a,u,v),d),v}catch(I){throw ds(e.onTrace,us(m,s,a,u,{status:"error",error:I}),d),I}finally{f?.dispose()}}}}function Yh(){return typeof performance>"u"?Date.now():performance.now()}function ds(e,t,n){if(!e)return;const r=n();try{e({...t,timestamp:r,durationMs:Math.max(0,Number.isFinite(r-t.startedAt)?r-t.startedAt:0)})}catch{}}function us(e,t,n,r,i){const o=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:r,outcome:o,...i.status==="error"?{errorCode:Qh(i.error)}:{},...Xh(t,n,i)}}function Qh(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function Xh(e,t,n){if(e!=="network.request"||typeof t!="object"||t===null||!("url"in t)||typeof t.url!="string")return{};try{const r=new URL(t.url);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.username||r.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=n.status==="handled"&&fc(n.value)&&typeof n.value.status=="number"?n.value.status:void 0;return{network:{method:o,origin:r.origin,pathname:r.pathname,...s===void 0?{}:{responseStatus:s}}}}catch{return{}}}function fc(e){return typeof e=="object"&&e!==null}function ls(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Jh(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},n=new ll(e.files,e.miniProgramDetail),r=wl({registry:n,picker:e.picker,operationContext:t}),i=gu({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});let o,s,a,c=()=>{},d=()=>{};try{o=jh({operationContext:t,presentation:e.hostPresentation,onDisplayChange:p=>e.eventSink.postEvent("display_change",p),onViewportChange:p=>e.eventSink.postEvent("viewport_change",p)}),s=Dh({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:i}),c=i.onEvent((p,_)=>e.eventSink.postEvent(p,_)),d=e.hostCompanion?.onSessionEvent?.(p=>{const _=ol(p);!e.terminalSignal.aborted&&_&&e.eventSink.postEvent(_.type,_.payload)})??(()=>{}),a=ju({account:e.account,identity:e.identity,network:e.network,operationContext:t});const u=uh({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),m=[{name:"auth",handlers:Su({authorization:i})},{name:"user",handlers:xh({user:s,authorization:i,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:ah({environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:o.handlers},{name:"storage",handlers:u.handlers},{name:"network",handlers:vf({network:e.network,transfer:e.transfer,fileRegistry:n,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"files",handlers:r.files},{name:"file",handlers:r.file},{name:"directory",handlers:r.directory},{name:"ui",handlers:Eh({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:cl({operationContext:t,presentation:e.hostPresentation})},{name:"navigation",handlers:jl({operationContext:t,presentation:e.hostPresentation})},{name:"cloud",handlers:a.handlers},{name:"companion",handlers:el({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:n})}],h=Zh(m);let f=!1;const I=()=>{f||(f=!0,e.terminalSignal.removeEventListener("abort",I),o?.dispose(),a?.dispose(),c(),d(),s?.dispose(),i.dispose(),n.dispose())};e.terminalSignal.aborted?I():e.terminalSignal.addEventListener("abort",I,{once:!0});const E=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:m,handlers:h,allowsCompanionAttachmentAccess:(p,_)=>E.has(p)&&fc(_)&&n.isCompanionAttachmentRef(_.target),applyOrientation:o.applyOrientation,notifyViewportChange:o.notifyChange,...u.diagnostics?{storageDiagnostics:u.diagnostics}:{},dispose:I}}catch(u){throw o?.dispose(),a?.dispose(),c(),d(),s?.dispose(),i.dispose(),n.dispose(),u}}function Zh(e){const t=new Map(He.map(i=>[i.method,i.module])),n=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(n.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);n.set(a,s)}const r=He.map(i=>i.method).filter(i=>!n.has(i));if(r.length>0)throw new Error(`Capability registry 缺少 method: ${r.join(", ")}`);if(n.size!==He.length)throw new Error(`Capability registry method 数量不合法: ${n.size}`);return Object.freeze(Object.fromEntries(n))}const em="heybox-mini-dev:";function fs(e){try{return tm(new URL(e))}catch{return!1}}function tm(e){return e.protocol===em}function nm(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||rm(e)}function rm(e){const t=e.split(".");if(t.length!==4)return!1;const n=t.map(r=>/^\d+$/.test(r)?Number(r):Number.NaN);return n.some(r=>!Number.isInteger(r)||r<0||r>255)?!1:n[0]===10||n[0]===172&&n[1]>=16&&n[1]<=31||n[0]===192&&n[1]===168}const im=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function om(e,t){const n=[],r=sm(e.environmentInfo,n),i=An(r?.appVersion,"host.appVersion",n),o=cm(r?.operatingSystem,n);return{info:Object.freeze({runtime:Object.freeze({mode:am(e.sdkVersionPolicy?.releaseChannel,n)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:An(t.miniProgramId),version:An(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(n)}}function sm(e,t){if(e!=null){if(hc(e))return e;t.push("environmentInfo")}}function am(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function cm(e,t){if(e==null)return{name:"unknown",version:null};if(!hc(e))return t.push("operatingSystem"),{name:"unknown",version:null};const n=im.has(e.name)?e.name:"unknown";return n==="unknown"&&e.name!==void 0&&e.name!==null&&e.name!=="unknown"&&t.push("operatingSystem.name"),{name:n,version:An(e.version,"operatingSystem.version",t)}}function An(e,t,n){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&n&&n.push(t),null)}function hc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const dm=1,mc="allow-scripts allow-same-origin",um="",lm="no-referrer";function fm(e=mc){return!e.split(/\s+/).includes("allow-same-origin")}function hs(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const hm=new Set(["javascript:","data:","blob:","file:"]),ms="xiaoheihe.cn";function mm(e,t=window.location.href,n={}){const r=e.trim();if(!r)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(r)}catch{throw new Error("小程序链接必须是绝对 URL")}if(hm.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!wm(i,t,n))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function pm(e,t){const n=new URL(e);return n.searchParams.set(nd,t),n.toString()}function gm(e,t,n){try{const r=new URL(e),i=new URL(t);if(r.origin!==i.origin)return!1;const o=Em(n)??ym(r.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Em(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function ym(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const n=e.lastIndexOf("/");return n>=0?e.slice(0,n+1):"/"}function ps(e){const t=new URL(e);return to(t)?"loopback":no(t)?"lan":"production"}function wm(e,t,n){return Im(e)||to(e)||no(e)&&_m(t,n)}function Im(e){return e.protocol==="https:"&&vm(e.hostname)}function to(e){return e.protocol==="http:"&&Am(e.hostname)}function Am(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function no(e){return e.protocol==="http:"&&bm(e.hostname)}function _m(e,t){if(t.allowPrivateNetwork)return!0;try{const n=new URL(e);return to(n)||no(n)}catch{return!1}}function bm(e){const t=Sm(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Sm(e){const t=e.split(".");if(t.length!==4)return;const n=t.map(r=>{if(!/^\d+$/.test(r))return;const i=Number(r);return Number.isInteger(i)&&i>=0&&i<=255?i:void 0});return n.every(r=>r!==void 0)?n:void 0}function vm(e){return e===ms||e.endsWith(`.${ms}`)}const Om=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"]),Dm=new Set(["url","inline","eval","unknown"]),Pm=/^\/(?:\:segment(?:\/\:segment)*)?$/,Rm=/^[a-f0-9]{64}$/,Nm=255,Cm=160,Tm=256;function Lm(e,t){const n=e;if(!n||typeof n.sdkVersion!="string"||n.sdkVersion!==t||typeof n.effectiveDirective!="string"||!Om.has(n.effectiveDirective)||typeof n.violatedDirective!="string"||n.violatedDirective.length>Tm||n.violatedDirective.split(/\s/,1)[0]!==n.effectiveDirective||!["enforce","report"].includes(n.disposition??"")||typeof n.blockedResourceType!="string"||!Dm.has(n.blockedResourceType)||typeof n.timestamp!="number"||!Number.isFinite(n.timestamp)||n.timestamp<0)return;const r=km(n.blockedOrigin);if(n.blockedOrigin!==void 0&&!r)return;const i=n.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>Cm||!Pm.test(i)))return;const o=n.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Rm.test(o)||i===void 0)))return{effectiveDirective:n.effectiveDirective,violatedDirective:n.effectiveDirective,blockedResourceType:n.blockedResourceType,origin:r,sanitizedPathname:i,sanitizedPathnameHash:o,sdkVersion:n.sdkVersion,timestamp:n.timestamp}}function km(e){if(e!==void 0&&!(typeof e!="string"||e.length>Nm))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Mm=/^(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 Um(e){if(!e?.minimumSdkVersion)throw F("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=We(e.minimumSdkVersion),n=e.sdkVersion?We(e.sdkVersion):void 0;if(!t)throw F("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!n)throw F("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const r=We("0.6.0");if(!n){if(_n(t,r)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw F("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&n.prerelease.length>0)throw F("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(_n(n,t)<0)throw F("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:_n(n,We("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function xm(e,t){if(typeof t!="string"||!We(t))throw F("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw F("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function Hm(e,t){const n=We(e),r=We(t);if(!(!n||!r))return _n(n,r)}function We(e){const t=Mm.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(n=>/^\d+$/.test(n)?Number(n):n)??[]}}function _n(e,t){for(const r of["major","minor","patch"])if(e[r]!==t[r])return e[r]<t[r]?-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 n=Math.max(e.prerelease.length,t.prerelease.length);for(let r=0;r<n;r+=1){const i=e.prerelease[r],o=t.prerelease[r];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const Sr=["android","ios","ohos","windows","macos","linux"],Fm="0.9.0",Bm=Object.freeze(["android","ios","ohos","windows","macos"]),pc="该小程序暂不支持当前平台",Vm="PLATFORM_UNSUPPORTED";function qm(e){return typeof e=="string"&&Sr.includes(e)}function zm(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 jm(e){const t=e.manifest;if(!Ym(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const r=Es(e.sdkVersion)??Es(t.sdkVersion);return Wm(r)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:$m()}const n=gc(t.platforms);return"reason"in n?{status:"invalid",reason:n.reason}:{status:"resolved",declaredPlatforms:n.platforms,effectivePlatforms:n.platforms,platformsDeclared:!0,policy:"explicit"}}function Gm(e){const t=zm(e.operatingSystemName);if(!t)return lt("host_operating_system_unknown");const n=e.platformAccess;if(!n)return lt("platform_access_missing",{platform:t});if(n.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Sr,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:n.reason};if(n.source==="manifest"){const s=jm({manifest:n.manifest,...n.sdkVersion===void 0?{}:{sdkVersion:n.sdkVersion}});return s.status==="invalid"?lt("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):gs(t,s)}if(n.effectivePlatforms===void 0)return lt("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const r=gc(n.effectivePlatforms);if("reason"in r)return lt("platform_declaration_invalid",{invalidReason:r.reason,platform:t});const i=typeof n.platformsDeclared=="boolean"?n.platformsDeclared:!0,o=Km(n.platformPolicy)?n.platformPolicy:i?"explicit":"legacy_mobile_default";return gs(t,{declaredPlatforms:i?r.platforms:[],effectivePlatforms:r.platforms,platformsDeclared:i,policy:o})}function gs(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:lt("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function lt(e,t={}){return{status:"denied",reason:e,message:pc,...t}}function $m(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:Bm,platformsDeclared:!1,policy:"legacy_mobile_default"}}function gc(e){if(!Array.isArray(e))return{reason:"platforms_not_array"};if(e.length===0)return{reason:"platforms_empty"};const t=new Set;for(const n of e){if(!qm(n))return{reason:"platform_unknown_value"};if(t.has(n))return{reason:"platform_duplicate_value"};t.add(n)}return{platforms:Object.freeze(Sr.filter(n=>t.has(n)))}}function Wm(e){if(typeof e!="string"||!e.trim())return!1;const t=Hm(e.trim(),Fm);return t!==void 0&&t>=0}function Es(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Km(e){return e==="explicit"||e==="legacy_mobile_default"}function Ym(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Qm=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Xm(e,t,n){const r=Date.now();try{const i=new URL(t);return{type:"security_violation",errorCode:e,timestamp:r,sdkVersion:n,origin:i.origin,sanitizedPathname:Jm(i.pathname),sanitizedPathnameHash:Zm(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:r,sdkVersion:n}}}function Jm(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(n=>n?":segment":"").join("/")}function Zm(e){const t=new TextEncoder().encode(e),n=Math.ceil((t.length+9)/64)*64,r=new Uint8Array(n);r.set(t),r[t.length]=128,new DataView(r.buffer).setUint32(n-4,t.length*8,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64),s=new DataView(r.buffer);for(let a=0;a<n;a+=64){for(let w=0;w<16;w+=1)o[w]=s.getUint32(a+w*4,!1);for(let w=16;w<64;w+=1){const p=o[w-15],_=o[w-2],A=ye(p,7)^ye(p,18)^p>>>3,v=ye(_,17)^ye(_,19)^_>>>10;o[w]=o[w-16]+A+o[w-7]+v>>>0}let[c,d,u,m,h,f,I,E]=i;for(let w=0;w<64;w+=1){const p=E+(ye(h,6)^ye(h,11)^ye(h,25))+(h&f^~h&I)+Qm[w]+o[w]>>>0,_=(ye(c,2)^ye(c,13)^ye(c,22))+(c&d^c&u^d&u);E=I,I=f,f=h,h=m+p>>>0,m=u,u=d,d=c,c=p+_>>>0}[c,d,u,m,h,f,I,E].forEach((w,p)=>{i[p]=i[p]+w>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ye(e,t){return e>>>t|e<<32-t}const ep=1e4,qr=2e3,tp=2,np="open-with-native-credential-policy",Ec="安全提示",yc="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class rp{nonce=hs();runtimeId=hs();terminalController=new AbortController;options;handshakeTimeout;ports;primitiveAvailability;effectiveCapabilities;identity;identityRef;iframe;iframeErrorListener;iframeLoadListener;bridgeServer=null;miniProgramSrc="";launchUrl="";startPromise=null;readyContext=null;resolveReady;rejectReady;terminalError;status="idle";stateValue="idle";handshakeTimeoutTimer;lifecycleDisposer;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;sdkVersionDecision;platformGateDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;unexpectedDocumentLoadTimer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const n=ba(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities});this.ports=n.ports,this.primitiveAvailability=n.primitiveAvailability,this.effectiveCapabilities=n.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const r=this.identity.miniProgramId?.trim();if(r)return{miniProgramId:r,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??ep,this.iframeErrorListener=r=>{this.onIframeError(r)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics;return t?{storage:t}:{}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??F("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??F("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(fp(),this.startPromise=this.createReadyPromise(),this.setState("starting"),this.setStatus("starting"),this.launch().catch(t=>{this.failRuntime(t)}),this.startPromise)}destroy(){if(this.stateValue==="destroyed")return;const t=F("RUNTIME_DESTROYED","小程序运行时已销毁");this.terminalError=t,this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.teardownIframe(),this.rejectReady?.(t)}show(){const t=this.hostVisible;this.hostVisible=!0,this.emitLifecycleEvent("show"),this.capabilityGraph?.notifyViewportChange(),!t&&this.stateValue==="ready"&&this.sdkVersionDecision?.heartbeatEnabled&&(this.documentRevalidationPending?(this.armDocumentRevalidationTimer(this.documentRevalidationGeneration),this.resendDocumentRevalidationProbe()):this.sendLocationProbe())}hide(){this.hostVisible=!1,this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.emitLifecycleEvent("hide")}prepareForHistoryTraversal(){if(this.stateValue!=="ready"||this.bridgeServer?.protocolVersion!==2||!this.sdkVersionDecision?.heartbeatEnabled)return()=>{};const t=this.beginDocumentRevalidation({deferProbe:!0});return this.preparedHistoryTraversalGeneration=t,()=>{this.preparedHistoryTraversalGeneration===t&&this.cancelPreparedHistoryTraversal()}}createReadyPromise(){return new Promise((t,n)=>{this.resolveReady=t,this.rejectReady=n})}async launch(){const t=await this.resolveRuntimeLaunchConfiguration();if(this.isInactive())return;this.runtimePermissions=t.runtimePermissions,this.runtimeFeatures=t.runtimeFeatures,this.miniProgramPresentation=t.miniProgramPresentation,this.locationBasePath=t.locationBasePath,this.anonymousStorageScope=t.anonymousStorageScope??this.options.anonymousStorageScope,this.allowedHttpOrigins=t.allowedHttpOrigins??this.options.allowedHttpOrigins,this.bindCanonicalIdentity(t.canonicalIdentity),this.sdkVersionDecision=Um(t.sdkVersionPolicy);const n=om(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=Gm({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw pp(this.platformGateDecision);if(this.miniProgramDetail=gp(t),this.effectiveCapabilities=_a(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),ap(this.options.onLaunchConfigurationResolved,t,this.sdkVersionDecision),this.isInactive())return;this.applyIframeDefaults(),this.startBridgeServer(),this.installSubscriptions();const r=await this.normalizeLaunchUrl(t.launchUrl);if(this.isInactive())return;const i=await this.confirmDevMiniProgramLaunch(r);if(!this.isInactive()){if(!i){await this.closeAfterDevLaunchCancellation();return}if(this.bridgeServer?.setTargetOrigin(dp(r)),this.launchUrl=r,this.miniProgramSrc=pm(r,this.nonce),this.traceSecurityPolicy(r),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(o){if(this.isInactive())return;const s=zi(o);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:Je,errorCode:s.code,message:`默认展示设置失败,沿用宿主当前布局:${s.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ce(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(r,i)=>{this.stateValue==="ready"&&(r!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(r!=="display_change"||this.effectiveCapabilities[Je])&&this.bridgeServer?.postEvent(r,i)}};this.capabilityGraph=Jh({account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,transfer:this.ports.transfer,storage:this.ports.storage,storageDiagnostics:this.ports.storageDiagnostics,hostPresentation:this.ports.presentation,hostCompanion:this.ports.companion,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins});const n=Kh({handlers:this.capabilityGraph.handlers,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:r,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:u})=>{const m={type:"capability",runtimeId:this.runtimeId,callId:r,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...u?{network:u}:{}};Ce(this.options.onCapabilityTrace,m)}}:{}});this.bridgeServer=new bd({iframe:this.iframe,nonce:this.nonce,dispatcher:n,environmentInfo:this.environmentInfo,onHandshake:r=>this.handleBridgeHandshake(r),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:r=>{this.handleInternalBridgeEvent(r)},onResponsePosted:({method:r,outcome:i,errorCode:o})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:r,outcome:i,...o?{errorCode:o}:{}})}}),this.bridgeServer.start(),this.setStatus("bridge_started"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge_started"})}onIframeError(t=new Error("小程序 iframe 加载失败")){if(this.isInactive())return;const n=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(F("IFRAME_LOAD_ERROR",n,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 sp(t)?t:wc(F("STARTUP_ERROR",t instanceof Error?t.message:"获取小程序启动配置失败"),t)}}bindCanonicalIdentity(t){const n=t?.miniProgramId?.trim();n&&(this.identity.miniProgramId=n);const r=t?.miniProgramVersion?.trim();r&&(this.identity.miniProgramVersion=r)}async normalizeLaunchUrl(t){try{const n=this.options.environment.getCurrentHref();return mm(t,n,{allowPrivateNetwork:fs(n)||ys(n)||await this.isDevRuntime()})}catch(n){throw F("INVALID_LAUNCH_URL",n instanceof Error?n.message:"小程序链接不合法",n)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??lp)({message:yc,title:Ec,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(ps(t)==="production")return!1;const n=this.options.environment.getCurrentHref();return!fs(n)&&!ys(n)}async closeAfterDevLaunchCancellation(){const t=F("LAUNCH_CANCELLED","小程序启动已取消");this.terminalError=t,this.destroyBridgeServer();const n=new AbortController;let r;try{r=Promise.resolve(this.ports.presentation.close({signal:n.signal}))}catch{ws(),r=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 r.catch(()=>ws())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",um),this.iframe.setAttribute("referrerpolicy",lm),this.iframe.setAttribute("sandbox",mc)}removeIframeListeners(){this.iframe.removeEventListener("error",this.iframeErrorListener),this.iframe.removeEventListener("load",this.iframeLoadListener)}installSubscriptions(){if(this.options.lifecycle&&!this.lifecycleDisposer){const t=this.options.lifecycle.subscribe({show:this.show.bind(this),hide:this.hide.bind(this)});this.lifecycleDisposer=typeof t=="function"?t:null}}clearLifecycleDisposer(){const t=[this.lifecycleDisposer];this.lifecycleDisposer=null;for(const n of t)try{n?.()}catch{}}handleBridgeReady(){if(this.isInactive())return;if(this.readyContext){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"});return}this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge",method:"ready"}),this.setState("ready"),this.sdkVersionDecision?.heartbeatEnabled&&this.hostVisible&&this.sendLocationProbe(),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),Ce(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(),Ce(this.options.onReady,t)}handleBridgeHandshake(t){const n=this.sdkVersionDecision?.sdkVersion;if(n)try{xm(n,t?.sdkVersion)}catch(r){return this.failRuntime(r),!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(F("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>=tp)){this.failRuntime(F("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(sn,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},qr),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:sn})}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 n=++this.documentRevalidationGeneration;return this.iframeHiddenForRevalidation||(this.iframeVisibilityBeforeRevalidation=this.iframe.style.visibility,this.iframe.style.visibility="hidden",this.iframeHiddenForRevalidation=!0),this.armDocumentRevalidationTimer(n),t.deferProbe||this.sendDocumentRevalidationProbe(),n}sendDocumentRevalidationProbe(){if(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)return;const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(sn,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:sn})}armDocumentRevalidationTimer(t){this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&(this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(F("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 文档再验证超时")))},qr))}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()},qr))}clearDocumentRevalidation(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1}cancelPreparedHistoryTraversal(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.iframeHiddenForRevalidation&&this.iframe.style.visibility==="hidden"&&(this.iframe.style.visibility=this.iframeVisibilityBeforeRevalidation??""),this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1,this.hostVisible&&this.sdkVersionDecision?.heartbeatEnabled&&this.sendLocationProbe()}handleDuplicateBridgeHandshake(){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"}),this.documentRevalidationPending&&this.resendDocumentRevalidationProbe()}handleInternalBridgeEvent(t){if(t.method===id){this.handleCspViolation(t.payload);return}if(t.method!==rd)return;const n=this.sdkVersionDecision?.sdkVersion;if(!n)return;const r=t.payload;if(!r||r.sdkVersion!==n){this.failRuntime(F("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(r.probeId!==void 0&&r.probeId!==this.pendingProbeId)){if(typeof r.href!="string"||!gm(this.launchUrl,r.href,this.locationBasePath)){typeof r.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",r.href),this.failRuntime(F("URL_OUT_OF_SCOPE","小程序页面地址超出允许范围"));return}r.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 n=Lm(t,this.sdkVersionDecision?.sdkVersion);n&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:n.timestamp,sdkVersion:n.sdkVersion,origin:n.origin,sanitizedPathname:n.sanitizedPathname,sanitizedPathnameHash:n.sanitizedPathnameHash,effectiveDirective:n.effectiveDirective,violatedDirective:n.violatedDirective,blockedResourceType:n.blockedResourceType})}emitSecurityViolation(t){Ce(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,n){const r=Xm(t,n,this.sdkVersionDecision?.sdkVersion);this.emitSecurityViolation(r)}scheduleUnexpectedDocumentLoadFailure(){this.clearUnexpectedDocumentLoadFailure(),this.unexpectedDocumentLoadTimer=setTimeout(()=>{this.unexpectedDocumentLoadTimer=void 0,this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(F("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:dm,launchUrlType:ps(t),networkPolicy:np})}failRuntime(t){const n=ip(t);return this.isInactive()||(this.terminalError=n,this.terminalController.abort(n),this.postBridgeError(n),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:n.code,message:n.message}),this.setState("failed"),this.teardownIframe(n),Ce(this.options.onError,op(n)),this.rejectReady?.(n)),n}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0,this.clearHandshakeTimeout(),this.clearHeartbeat(),this.clearUnexpectedDocumentLoadFailure(),this.clearDocumentRevalidation(),this.destroyBridgeServer(),this.capabilityGraph?.dispose(),this.capabilityGraph=void 0,this.clearLifecycleDisposer(),this.removeIframeListeners();try{this.options.dispose?.()}catch{}}}teardownIframe(t){if(!this.iframeTornDown){this.iframeTornDown=!0;try{this.options.teardownIframe?this.options.teardownIframe(this.iframe,t):this.iframe.remove()}catch{}}}setStatus(t){this.status!==t&&(this.status=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:t}))}setState(t){this.stateValue!==t&&(this.stateValue=t,Ce(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ce(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 ip(e){const t=zi(e);return sr(e)&&"cause"in e&&wc(t,e.cause),t}function wc(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function op(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function sp(e){return sr(e)&&typeof e.code=="string"&&typeof e.message=="string"}function sr(e){return!!e&&typeof e=="object"}function Ce(e,t){try{e?.(t)}catch{}}function ap(e,t,n){try{e?.(t,n)}catch{}}function ys(e){try{const t=new URL(e);return t.protocol==="http:"&&nm(t.hostname)}catch{return!1}}function cp(e){try{return new URL(e).origin}catch{return}}function dp(e){return fm()?"*":cp(e)}function up(e){return`${Ec}
|
|
1
|
+
import{H as fo,aw as Wc,aW as Kc,K as Yc,aF as Qc,aG as Xc,ak as Xt,b1 as B,ab as Jc,al as aa,an as Zc,c as ho,aC as ca,a9 as ed,as as da,p as td,ay as ua}from"./desktop-app-launch-DldUhS5Y.js";const Pn="auth.login",Rn="user.getInfo",Nn="user.revokeAuthorization",Cn="user.getSteamGameList",Tn="share.copyLink",Ln="share.showShareMenu",kn="share.screenshot",Je="viewport.setDisplay",Mn="viewport.getWindowInfo",Un="viewport.setNavigationBarStyle",xt="storage.getStorage",Ht="storage.setStorage",xn="network.request",Hn="network.download",Fn="files.pickFiles",Bn="files.pickDirectory",Vn="files.saveFile",Ft="file.create",Bt="file.remove",qn="file.exists",Vt="file.readText",zn="file.writeText",qt="file.readBytes",jn="file.writeBytes",zt="file.stat",Gn="directory.create",jt="directory.remove",$n="directory.exists",Wn="directory.list",Kn="ui.showToast",Yn="ui.showLoading",Qn="ui.hideLoading",Xn="device.vibrate",Jn="device.setClipboard",Zn="navigation.close",er="navigation.reload",tr="navigation.openAppPage",Pe="cloud.leaderboard.submit",me="cloud.leaderboard.getList",xe="cloud.leaderboard.getCurrentUserEntry",Ze="cloud.leaderboard.deleteCurrentUserEntry",Ae="cloud.leaderboard.getInfo",dr="companion.getInfo",ur="companion.getPreparationStatus",lr="companion.prepare",fr="companion.cancelPreparation",hr="companion.getActiveSession",mr="companion.launch",pr="companion.session.write",gr="companion.session.closeStdin",Er="companion.session.terminate",yr="companion.session.ackOutput",wr="companion.openAttachment",Ir="companion.showNotification",He=[{method:Pn,module:"auth",capability:Pn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Rn,module:"user",capability:Rn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Nn,module:"user",capability:Nn,requirement:{kind:"none"},risk:"high"},{method:Cn,module:"user",capability:Cn,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:Tn,module:"share",capability:Tn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Ln,module:"share",capability:Ln,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:kn,module:"share",capability:kn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Mn,module:"viewport",capability:Mn,requirement:{kind:"none"},risk:"low"},{method:Un,module:"viewport",capability:Un,requirement:{kind:"none"},risk:"low"},{method:Je,module:"viewport",capability:Je,requirement:{kind:"none"},risk:"low"},{method:xt,module:"storage",capability:xt,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:Ht,module:"storage",capability:Ht,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:xn,module:"network",capability:xn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Hn,module:"network",capability:Hn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Fn,module:"files",capability:Fn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Bn,module:"files",capability:Bn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Vn,module:"files",capability:Vn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ft,module:"file",capability:Ft,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Bt,module:"file",capability:Bt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:qn,module:"file",capability:qn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Vt,module:"file",capability:Vt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:zn,module:"file",capability:zn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:qt,module:"file",capability:qt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:jn,module:"file",capability:jn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:zt,module:"file",capability:zt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Gn,module:"directory",capability:Gn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:jt,module:"directory",capability:jt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:$n,module:"directory",capability:$n,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Wn,module:"directory",capability:Wn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Kn,module:"ui",capability:Kn,requirement:{kind:"none"},risk:"low"},{method:Yn,module:"ui",capability:Yn,requirement:{kind:"none"},risk:"low"},{method:Qn,module:"ui",capability:Qn,requirement:{kind:"none"},risk:"low"},{method:Xn,module:"device",capability:Xn,requirement:{kind:"none"},risk:"low"},{method:Jn,module:"device",capability:Jn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Zn,module:"navigation",capability:Zn,requirement:{kind:"none"},risk:"medium"},{method:er,module:"navigation",capability:er,requirement:{kind:"none"},risk:"medium"},{method:tr,module:"navigation",capability:tr,requirement:{kind:"none"},risk:"medium"},{method:Pe,module:"cloud",capability:Pe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:me,module:"cloud",capability:me,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:xe,module:"cloud",capability:xe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ze,module:"cloud",capability:Ze,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ae,module:"cloud",capability:Ae,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},...[dr,ur,lr,fr,hr,mr,pr,gr,Er,yr,wr,Ir].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],Ge="heybox:miniprogram",la=2,nd="hb_mini_bridge_nonce",fa="sdk.handshake",sn="runtime.location.probe",rd="sdk.location.report",id="sdk.csp.violation",ha="operation.progress",od="companion.session.output",sd="companion.session.exit",ad="companion.session.ownershipLost";function cd(e){return!je(e)||e.namespace!==Ge||e.version!==1&&e.version!==2||!ee(e.nonce)?!1:e.type==="handshake"?ee(e.id)&&e.method===fa&&e.error===void 0&&fd(e.payload):e.type==="request"?ee(e.id)&&ee(e.method)&&e.error===void 0:e.type==="response"?ee(e.id)&&(e.method===void 0||ee(e.method))&&(e.error===void 0||hd(e.error)):e.type==="event"?!ee(e.method)||e.error!==void 0?!1:e.method===ha?e.version===2&&ee(e.id)&&ld(e.payload):e.id===void 0||ee(e.id):e.type==="cancel"?e.version===2&&ee(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Bi(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function ma(e){return je(e)?e.kind==="sandbox"?Re(e,["kind"]):e.kind==="directory"&&ee(e.handleId)&&Re(e,["kind","handleId"]):!1}function Vi(e){return!je(e)||e.kind!=="file"?!1:ee(e.handleId)?Re(e,["kind","handleId"]):ma(e.root)&&Bi(e.relativePath)&&Re(e,["kind","root","relativePath"])}function pa(e){return!je(e)||e.kind!=="directory"?!1:ee(e.handleId)?Re(e,["kind","handleId"]):ma(e.root)&&(e.relativePath==="."||Bi(e.relativePath))&&Re(e,["kind","root","relativePath"])}function ga(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function dd(e){return!je(e)||!ht(e.loaded)||typeof e.lengthComputable!="boolean"||!Re(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?ht(e.total)&&e.loaded<=e.total:e.total===void 0}function ud(e){return je(e)?e.phase==="downloading"?ht(e.loaded)&&(e.total===void 0||ht(e.total)&&e.loaded<=e.total)&&Re(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:ht(e.processed)&&ht(e.total)&&e.processed<=e.total&&Re(e,["phase","processed","total"]):!1}function ld(e){return dd(e)||ud(e)}function fd(e){return je(e)&&ee(e.href)&&typeof e.userAgent=="string"&&ee(e.sdkVersion)}function hd(e){return je(e)&&ee(e.code)&&typeof e.message=="string"}function ht(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ee(e){return typeof e=="string"&&e.length>0}function Re(e,t){const n=new Set(t);return Object.keys(e).every(r=>n.has(r))}function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Gt=["userInfo","steamLibrary","share","storage","filesystem","clipboard","leaderboard","network","companion"];new Set(Gt);const md=new Set(Gt);function pd(e){return md.has(e)}function Ne(e){if(!an(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,n={};for(const r of e.entries){if(!an(r)||typeof r.key!="string"||!r.key.trim())return{valid:!1,permissions:{}};const i=r.key.trim(),o=i==="network.request"?"network":i;if(t.has(o)||r.status!=="enabled"&&r.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(o),!!pd(o)){if(o==="network"){const s=r.config;if(!an(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};n[o]={key:o,status:r.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(r.config!==null&&r.config!==void 0&&(!an(r.config)||Object.keys(r.config).length>0))return{valid:!1,permissions:{}};n[o]={key:o,status:r.status,config:{}}}}return{valid:!0,permissions:n}}function an(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const yn=["network","companion"];function Ea(e){if(!cn(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>yn.length)return{valid:!1};const t=[],n=new Set;for(const r of e.entries){if(!cn(r,["key","status","config"])||r.status!=="enabled")return{valid:!1};if(typeof r.key!="string"||n.has(r.key))return{valid:!1};if(n.add(r.key),r.key==="network"){if(!cn(r.config,["useOfficialDomain"])||r.config.useOfficialDomain!==!1)return{valid:!1};t.push({key:"network",status:"enabled",config:{useOfficialDomain:!1}})}else if(r.key==="companion"){if(!cn(r.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((r,i)=>yn.indexOf(r.key)-yn.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function gd(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Ne(e.runtimePermissions),n=new Set(e.eligiblePermissionKeys??["network"]),r=[];for(const i of yn)!n.has(i)||e.declaredPermissions[i]?.enabled!==!0||t.valid&&t.permissions[i]?.status==="enabled"||r.push(i==="network"?{key:i,status:"enabled",config:{useOfficialDomain:!1}}:{key:i,status:"enabled",config:{}});return{schema_version:1,revision:e.revision,entries:r}}function qi(e){const t=Ne(e.runtimePermissions),n=Ea(e.localDevGrant),r=t.valid?t.permissions:{};for(const s of Gt)e.declaredPermissions[s]?.enabled!==!0?delete r[s]:s==="network"&&r.network&&(r.network.config.useOfficialDomain=r.network.status==="enabled"&&r.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(n.valid)for(const s of n.grant.entries)e.declaredPermissions[s.key]?.enabled!==!0||r[s.key]?.status==="enabled"||(r[s.key]=s,i.push(s.key));const o=ya(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:Gt.flatMap(s=>r[s]?[r[s]]:[])},temporaryPermissionKeys:i,grantValid:n.valid}}function ya(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cn(e,t){return ya(e)&&Object.keys(e).length===t.length&&t.every(n=>Object.prototype.hasOwnProperty.call(e,n))}const gt=["identity","profile","steam_account"],Ed=/^[a-z][a-z0-9-]{0,31}$/,wa=["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"];He.map(e=>e.method);function F(e,t,n){return{code:e,message:t,data:n}}function zi(e){return yd(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?F("RUNTIME_ERROR",e.message):F("UNKNOWN_ERROR","小程序运行时异常",e)}function yd(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function wd(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Id=1e3;function Ad(e,t=wd()){if(t.userActivation)return t.userActivation.isActive===!0;const n=t.lastUserInteractionAt,r=t.now??Date.now();return t.activeElement===e&&n!==void 0&&r>=n&&r-n<=Id}const _d="runtime.gate.probe",Ia=new Set(He.map(e=>e.method));class bd{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=la;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,this.handleMessage=this.onMessage.bind(this),this.handleUserInteraction=this.onUserInteraction.bind(this),this.dispatcher=t.dispatcher,this.environmentInfo=t.environmentInfo,this.targetOrigin=t.targetOrigin||"*"}get protocolVersion(){return this.handshaken?this.bridgeVersion:void 0}start(){if(!(this.started||this.destroyed)){this.started=!0,window.addEventListener("message",this.handleMessage);for(const t of["pointerdown","touchend","mousedown","keydown"])window.addEventListener(t,this.handleUserInteraction,!0)}}setTargetOrigin(t){this.targetOrigin=t||"*"}destroy(){if(this.destroyed)return;const t=this.started;this.destroyed=!0,this.started=!1,this.handshaken=!1;try{t&&this.postMessage({namespace:Ge,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:"unload",payload:{timestamp:Date.now()}})}catch{}finally{window.removeEventListener("message",this.handleMessage);for(const n of["pointerdown","touchend","mousedown","keydown"])window.removeEventListener(n,this.handleUserInteraction,!0);this.lastUserInteractionAt=void 0;for(const n of this.operations.values())n.abort("bridge destroyed");this.operations.clear()}}postEvent(t,n){this.destroyed||this.postMessage({namespace:Ge,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:n})}postInternalRequest(t,n,r){this.destroyed||this.postMessage({namespace:Ge,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:n,method:t,payload:r})}postProgress(t,n){this.bridgeVersion===2&&this.postMessage({namespace:Ge,version:2,nonce:this.nonce,type:"event",id:t,method:ha,payload:n})}onMessage(t){if(!this.started||!this.isTrustedMiniProgramMessage(t))return;const n=t.data;if(n.type==="handshake"){this.handleHandshake(n,t.origin);return}if(n.type==="request"){let r=!1;try{r=Ad(this.iframe,{activeElement:document.activeElement,userActivation:navigator.userActivation,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{r=!1}this.handleRequest(n,r);return}if(n.type==="cancel"&&this.handshaken&&n.id){this.operations.get(n.id)?.abort();return}n.type==="event"&&this.handshaken&&this.onInternalEvent?.(n)}onUserInteraction(t){const n=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||n.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&cd(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,n){const r=t.payload,i=t.version,o=!this.handshaken;if(o){if(this.onHandshake?.(r)===!1)return;this.bridgeVersion=i,i===1&&this.targetOrigin!=="*"&&n&&n!=="null"&&(this.targetOrigin=n),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.environmentInfo&&t.id&&this.postMessage({namespace:Ge,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:fa,payload:{environment:this.environmentInfo}}),this.postEvent("ready",{timestamp:Date.now()}),o?this.onReady?.(r):this.onDuplicateHandshake?.()}async handleRequest(t,n){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===_d){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,F("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Ia.has(t.method)){this.postResponse(t,void 0,F("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,F("INVALID_PARAMS","bridge request id 重复"));return}const r=new AbortController;this.operations.set(t.id,r);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{postEvent:this.postEvent.bind(this),postProgress:o=>{this.operations.get(t.id)===r&&this.postProgress(t.id,o)},signal:r.signal,trustedUserGesture:n});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==r)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==r)return;const o=zi(i);this.postResponse(t,void 0,o),this.postEvent("error",o)}finally{this.operations.get(t.id)===r&&(this.operations.delete(t.id),r.signal.aborted||r.abort("operation terminal"))}}postResponse(t,n,r){if(!(!this.postMessage({namespace:Ge,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:n,error:r})||!Sd(t.method)))try{this.onResponsePosted?.({method:t.method,outcome:r?"error":"success",...r?{errorCode:r.code}:{}})}catch{}}postMessage(t){const n=this.iframe.contentWindow;return n?(n.postMessage(t,this.targetOrigin),!0):!1}}function Sd(e){return typeof e=="string"&&Ia.has(e)}const Aa="METHOD_FORBIDDEN";function Se(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Aa,t}class J extends Error{code="HOST_REQUEST_UNSUPPORTED";constructor(t="当前 Host 不支持该请求形状",n){super(t),this.name="HostRequestUnsupportedError",n&&"cause"in n&&Object.defineProperty(this,"cause",{configurable:!0,enumerable:!1,value:n.cause}),Object.setPrototypeOf(this,new.target.prototype)}}const mo={[Pn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Rn]:["account.getCurrentUserId","account.onChange","network.request"],[Nn]:["account.getCurrentUserId","account.onChange","network.request"],[Cn]:["account.getCurrentUserId","account.onChange","network.request"],[Tn]:["presentation.setClipboard"],[Ln]:["presentation.showShareMenu"],[kn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Je]:["presentation.applyOrientation"],[Mn]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Un]:["presentation.setNavigationBarStyle"],[xt]:["storage.getRaw"],[Ht]:["storage.setRaw"],[xn]:["network.request"],[Hn]:["network.stream","files.transfer","files.access"],[Fn]:["files.external"],[Bn]:["files.external"],[Vn]:["files.save"],[Ft]:["files.access"],[Bt]:["files.removeFile"],[qn]:["files.access"],[Vt]:["files.access"],[zn]:["files.access"],[qt]:["files.access"],[jn]:["files.access"],[zt]:["files.access"],[Gn]:["files.access"],[jt]:["files.removeDirectory"],[$n]:["files.access"],[Wn]:["files.access"],[Kn]:["presentation.showToast"],[Yn]:["presentation.showLoading"],[Qn]:["presentation.hideLoading"],[Xn]:["presentation.vibrate"],[Jn]:["presentation.setClipboard"],[Zn]:["presentation.close"],[er]:["presentation.reload"],[tr]:["presentation.openAppPage"],[Pe]:["account.getCurrentUserId","account.onChange","network.request"],[me]:["account.onChange","network.request"],[xe]:["account.getCurrentUserId","account.onChange","network.request"],[Ze]:["account.getCurrentUserId","account.onChange","network.request"],[Ae]:["account.onChange","network.request"],[dr]:["companion.getInfo"],[ur]:["companion.getPreparationStatus"],[lr]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[fr]:["companion.cancelPreparation"],[hr]:["companion.getActiveSession"],[mr]:["companion.getInfo","companion.launch"],[pr]:["companion.session.write"],[gr]:["companion.session.closeStdin"],[Er]:["companion.session.terminate"],[yr]:["companion.session.ackOutput"],[wr]:["companion.openAttachment"],[Ir]:["companion.showNotification"]};function vd(e,t){if(t[e]!==!0)throw Se(e)}const Od=32*1024*1024,Dd=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Pd(e){if(e.mode==="request-only")return{network:{request:(r,i)=>e.request(r,i)}};if(e.mode==="override-request")return{network:{request:(r,i)=>e.request(r,i)},...e.stream===void 0?{}:{stream:e.stream}};const{consume:t,stream:n}=e;return{stream:n,network:{async request(r,i){const o=await n.open(r,i);let s;try{const a=await t(o.body,{maxBytes:Od},i);return Rd(o,a)}catch(a){throw s=a,a}finally{try{await n.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Rd(e,t){const n=Object.fromEntries(Object.entries(e.headers).map(([r,i])=>[r,i.join(", ")]));return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:n,data:Nd(t,Td(e,"content-type"))}}function Nd(e,t){Cd(t);let n;try{n=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(r){throw new J("Host network response 不是合法 UTF-8 文本",{cause:r})}if(n.charCodeAt(0)===65279&&(n=n.slice(1)),!t||!Dd.test(t)||n==="")return n;try{return JSON.parse(n)}catch{return n}}function Cd(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new J(`Host network response 不支持 charset=${t}`)}function Td(e,t){return Object.entries(e.headers).find(([n])=>n.toLowerCase()===t)?.[1]?.[0]}function b(e){return typeof e=="function"}function po(e){return(...t)=>{throw Se(e)}}function Y(e){return async(...t)=>{throw Se(e)}}const Ld=(e,t)=>{},kd=()=>()=>{};function Md(e){const t={request:b(e.network?.request)?e.network.request.bind(e.network):Y("network.request")},n={getCurrentUserId:b(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):Y("account.getCurrentUserId"),ensureAuthenticated:b(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Y("account.ensureAuthenticated"),onChange:b(e.account?.onChange)?e.account.onChange.bind(e.account):kd},r={getRaw:b(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Y("storage.getRaw"),setRaw:b(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Y("storage.setRaw")},i={...b(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...b(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:b(e.presentation?.close)?e.presentation.close.bind(e.presentation):Y("presentation.close"),reload:b(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Y("presentation.reload"),openAppPage:b(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Y("presentation.openAppPage"),openWindow:b(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Y("presentation.openWindow"),getViewportMetrics:b(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):po("presentation.getViewportMetrics"),getNavigationBarHeight:b(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):po("presentation.getNavigationBarHeight"),setNavigationBarStyle:b(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Y("presentation.setNavigationBarStyle"),showShareMenu:b(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Y("presentation.showShareMenu"),setScreenshotChromeHidden:b(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):Ld,captureAndShare:b(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Y("presentation.captureAndShare"),showToast:b(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Y("presentation.showToast"),showLoading:b(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Y("presentation.showLoading"),hideLoading:b(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Y("presentation.hideLoading"),vibrate:b(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Y("presentation.vibrate"),setClipboard:b(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Y("presentation.setClipboard")},o=b(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(a=>[a,b(e.companion?.[a])?e.companion[a].bind(e.companion):Y(`companion.${a}`)]));return b(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion)),{network:t,account:n,storage:r,presentation:i,companion:s,...e.files===void 0?{}:{files:e.files},...e.picker===void 0?{}:{picker:e.picker},...e.transfer===void 0?{}:{transfer:e.transfer},...o?{storageDiagnostics:o}:{}}}function Ud(e){const t=xd(e.files?.sandbox),n=b(e.picker?.pickFiles)&&b(e.picker?.pickDirectory),r=b(e.picker?.saveFile),i=t||n||r||b(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getCurrentUserId":b(e.account?.getCurrentUserId),"account.ensureAuthenticated":b(e.account?.ensureAuthenticated),"account.onChange":b(e.account?.onChange),"network.request":b(e.network?.request),"network.stream":b(e.transfer?.network.open)&&b(e.transfer?.network.release),"files.sandbox":t,"files.external":n,"files.save":r,"files.access":i,"files.removeFile":b(o?.remove),"files.removeDirectory":b(e.files?.sandbox.remove),"files.transfer":b(e.transfer?.files.writeResource),"storage.getRaw":b(e.storage?.getRaw),"storage.setRaw":b(e.storage?.setRaw),"presentation.close":b(e.presentation?.close),"presentation.reload":b(e.presentation?.reload),"presentation.openAppPage":b(e.presentation?.openAppPage),"presentation.applyOrientation":b(e.presentation?.applyOrientation),"presentation.openWindow":b(e.presentation?.openWindow),"presentation.getViewportMetrics":b(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":b(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":b(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":b(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":b(e.presentation?.captureAndShare),"presentation.showToast":b(e.presentation?.showToast),"presentation.showLoading":b(e.presentation?.showLoading),"presentation.hideLoading":b(e.presentation?.hideLoading),"presentation.vibrate":b(e.presentation?.vibrate),"presentation.setClipboard":b(e.presentation?.setClipboard),"companion.getInfo":b(e.companion?.getInfo),"companion.getPreparationStatus":b(e.companion?.getPreparationStatus),"companion.prepare":b(e.companion?.prepare),"companion.cancelPreparation":b(e.companion?.cancelPreparation),"companion.getActiveSession":b(e.companion?.getActiveSession),"companion.launch":b(e.companion?.launch),"companion.session.write":b(e.companion?.write),"companion.session.closeStdin":b(e.companion?.closeStdin),"companion.session.terminate":b(e.companion?.terminate),"companion.session.ackOutput":b(e.companion?.ackOutput),"companion.openAttachment":b(e.companion?.openAttachment),"companion.showNotification":b(e.companion?.showNotification)}}function xd(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&b(t.file)&&b(t.directory)&&b(t.create)&&b(t.stat)&&b(t.list)}function go(e,t){return t?.[e]!==!1}function Hd(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("companion.")}function _a(e,t={}){const n={};for(const r of Object.keys(mo)){const o=mo[r].every(a=>e[a]),s=!Hd(r)||!!t.miniProgramDetail?.miniProgramId.trim();n[r]=go(r,t.callerCapabilities)&&go(r,t.hostCapabilities)&&o&&s}return n}function ba(e={},t={}){const n=Ud(e),r=_a(n,t);return{ports:Md(e),primitiveAvailability:n,availablePrimitives:n,effectiveCapabilities:r}}function ji(e,t){if(!t||t===e.signal)return e;const n=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):Fd(e.signal,t);return{...e,signal:n}}function Fd(e,t){const n=new AbortController,r=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",s)},i=a=>{n.signal.aborted||(r(),n.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})),n.signal}function Bd(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 Vd=4,qd=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],zd=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade"]),jd=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Gd=["/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 $d(e,t){const n=Yd(e);return n===null||Eo(n,jd)?!0:t&&Eo(n,Gd)}function Wd(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return qd.some(n=>t===n||t.endsWith(`.${n}`))}function Kd(e){const t=e.trim().toLowerCase();return zd.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Yd(e){let t=e;for(let n=0;n<Vd;n+=1){let r;try{r=decodeURIComponent(t)}catch{return null}if(r===t)return yo(t);t=r}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return yo(t)}function Eo(e,t){return t.some(n=>e===n||e.startsWith(`${n}/`))}function yo(e){const t=[];for(const n of e.replace(/\\/g,"/").split("/"))!n||n==="."||(n===".."?t.pop():t.push(n));return`/${t.join("/")}`}function l(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,data:n}}function M(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qd(e){return typeof e=="object"&&e!==null}function de(e,t){const n=e.data;if(!Qd(n)||typeof n.status!="string")throw new Error(t);return n}const Sa={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Xd={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.public.detail.get",method:"GET",path:"/user_miniprogram/public/detail",query(e){return{mini_program_id:e.mini_program_id,...e.miniprogram_version?{miniprogram_version:e.miniprogram_version}:{},...e.preview_token?{preview_token:e.preview_token}:{},...e.local_dev_launch_token?{local_dev_launch_token:e.local_dev_launch_token}:{},...e.entry?{entry:e.entry}:{},...e.h_src_parent?{h_src_parent:e.h_src_parent}:{},...e.extra!==void 0?{extra:e.extra}:{}}},parse(e,t){return de(e,"工坊小程序详情加载失败")}};function Jt(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Jd(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Zd(e){const t=de(e,"小程序登录授权接口响应异常"),n=t.result,r={};if(n.login_code&&typeof n.login_code=="object"){const i=n.login_code;r.loginCode={code:i.code,expiresIn:i.expires_in,scopes:i.scopes||[]}}return n.consent_challenge&&typeof n.consent_challenge=="object"&&(r.consentChallenge=Jd(n.consent_challenge)),{...t,result:r}}const eu={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=>({...Jt(e.runtimeContext),challenge:e.challenge}),parse:e=>de(e,"小程序授权取消接口响应异常")},tu={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=>Jt(e.runtimeContext),parse:e=>de(e,"小程序授权撤销接口响应异常")},nu={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=>Jt(e.runtimeContext),parse(e){const t=de(e,"小程序隔离身份接口响应异常"),n=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,...n?{steamId:n}:{}}}}},ru={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=>({...Jt(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Zd(e)},iu={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=>({...Jt(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=de(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}};function ou(e){const t=Ne(e);return t.valid&&t.permissions.network?.status==="enabled"}function va(e,t){return t?e?"server":"local":"legacy"}function su(e,t){return va(ou(e),t)}function wo(e,t){if(e==="server")throw l("SERVER_API_REQUIRED",`${t} 在联网模式下必须通过开发者服务端 OpenAPI 获取`)}function au(e,t){if(e==="local")throw l("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const cu=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],du=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),uu=/authorization|cookie|pkey|password|secret|token/i,Oa=/authorization|cookie|pkey|token|password|secret/i;function Ee(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function lu(e){for(const t of Object.keys(e))if(!du.has(t))throw new J(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of cu)if(Object.prototype.hasOwnProperty.call(e,t)&&Ee(e,t)!==void 0)throw new J(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Ee(e,"bodyEncoding")!==void 0&&Ee(e,"bodyEncoding")!=="json"&&Ee(e,"bodyEncoding")!=="form")throw new J("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Ee(e,"failurePresentation")!==void 0&&Ee(e,"failurePresentation")!=="none")throw new J("endpoint failurePresentation 必须为 none");if(Ee(e,"auth")!==void 0&&Ee(e,"auth")!=="none"&&Ee(e,"auth")!=="optional"&&Ee(e,"auth")!=="required")throw new J("endpoint auth 必须为 none、optional 或 required")}function Ct(e){if(Array.isArray(e))return e.map(Ct);if(!e||typeof e!="object")return e;const t=e,n={};for(const[r,i]of Object.entries(t))uu.test(r)||(n[r]=Ct(i));return n}function Io(e){if(!e)return;const t={};for(const[n,r]of Object.entries(e))Oa.test(n)||(t[n]=r);return t}function fu(e){if(!e)return;const t=Object.keys(e).find(n=>Oa.test(n));if(t)throw new J(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Et extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,Object.setPrototypeOf(this,new.target.prototype)}}function Da(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class yt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Da(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Zt extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Da(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function hu(e,t,n,r,i,o,s,a){return{config:{auth:e.auth,body:Ct(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Io(o),method:e.method,metadata:{endpointId:e.id},query:Ct(r),timeout:e.timeout,url:n},data:Ct(a.data),headers:Io(a.headers)||{},status:a.status,statusText:a.statusText}}async function Ar(e,t,n,r){if(!r||!r.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(r.credentials!=="heybox-session"&&r.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(lu(t),typeof t.id!="string"||!t.id)throw new J("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new J("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(n):t.path;if(typeof i!="string"||!i)throw new J("endpoint path 必须为非空字符串");const o=t.query?await t.query(n):void 0,s=t.body?await t.body(n):void 0,a=t.headers?await t.headers(n):void 0;fu(a);let c;try{c=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:r.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:r.signal,...r.miniProgramDetail===void 0?{}:{miniProgramDetail:r.miniProgramDetail}})}catch(u){throw u instanceof J?u:new yt({endpointId:t.id,cause:u})}if(c.status<200||c.status>=300)throw new Et({endpointId:t.id,status:c.status});const d=hu(t,n,i,o,s,a,r,c);if(t.parse)try{return await t.parse(d,n)}catch(u){throw new Zt({endpointId:t.id,cause:u})}return d.data}const mu=new Set(gt),Gi="steam_account",Pa=new Set(gt.filter(e=>e!==Gi)),pu=1e3;function gu(e){const t=new Set,n=new Map,r=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??va(e.networkEnabled===!0,c);async function u(){if(!c)return{};if(!e.authorizationContext)throw l("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let g;try{g=await e.authorizationContext.get(e.operationContext)}catch{throw l("REQUEST_FAILED","读取 Runtime auth context 失败")}if(g.steamAccount!==c||g.userDataMode!==d)throw l("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const R=g.token.trim();if(!R)throw l("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:R}}const m=e.account.onChange(g=>{h(),f("heybox_app_login_change",{isHeyboxAppLoggedIn:!!g})});function h(){i+=1,a?.abort(),n.clear(),r.clear()}function f(g,R){for(const L of t)try{L(g,R)}catch{}}function I(){const g=e.identity.get()?.miniProgramId?.trim();if(!g)throw l("INVALID_STATE","当前能力缺少 canonical 小程序身份");return g}function E(){if(o||e.operationContext.signal.aborted)throw l("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function w(){E();let g;try{g=await e.account.getCurrentUserId(e.operationContext)}catch(R){throw So(R,e.operationContext.signal,"读取小黑盒账号失败")}return typeof g=="string"&&g.trim()?g.trim():void 0}async function p(g,R){const L=await w();if(i!==R||L!==g)throw l("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function _(g){E();try{await e.account.ensureAuthenticated({trustedUserGesture:g,reason:"runtime_auth",signal:e.operationContext.signal})}catch(L){throw So(L,e.operationContext.signal,"小黑盒登录失败")}const R=await w();if(!R)throw l("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return R}async function A(g,R,L=e.operationContext.signal){try{if(L.aborted)throw Ei();return await _u(Ar(e.network,g,R,{...e.operationContext,credentials:"heybox-session",signal:L}),L)}catch(k){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):k instanceof J?l("REQUEST_UNSUPPORTED",k.message):k instanceof Zt?l("INVALID_RESPONSE","授权接口响应不合法"):k instanceof yt?l("REQUEST_FAILED","授权请求失败"):k instanceof Et?l("REQUEST_FAILED",k.message):Ra(k)?k:l("REQUEST_FAILED","授权请求失败")}}async function v(g,R){await A(eu,{runtimeContext:{miniProgramId:g,...await u()},challenge:R}).catch(()=>{})}function x(g){const R=async()=>{const k=_o(e.operationContext.signal);a=k;try{return await g(k.signal)}finally{a===k&&(a=void 0),k.abort()}},L=s.then(R,R);return s=L.then(()=>{},()=>{}),L}async function S(g,R,L,k,U){if(!L)throw await v(g,R.challenge),l("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await v(g,R.challenge),l("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return x(async W=>{await p(k,U);const j=await T(g,R.displayedScopes,W);await p(k,U);let X;try{X=await e.authPresentation.confirmAuthorization({miniProgramId:g,scopes:R.displayedScopes,...j,signal:W})}catch(ne){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await p(k,U),await v(g,R.challenge),Eu("REQUEST_FAILED","授权确认界面执行失败",ne))}if(await p(k,U),X.status!=="granted")throw await v(g,R.challenge),l("AUTHORIZATION_CANCELLED","用户取消授权");const K=Iu(X.grantedScopes,R.displayedScopes,c);if(!K.includes("identity"))throw await v(g,R.challenge),l("AUTHORIZATION_CANCELLED","用户拒绝授权");return K})}async function T(g,R,L){const k=_o(L),U=setTimeout(()=>k.abort(),pu);try{const W=Au(e.miniProgramPresentation),[j,X]=await Promise.all([W?Promise.resolve(W):C(g,k.signal),R.includes("profile")?O(k.signal):Promise.resolve(void 0)]);return{...j?{miniProgram:j}:{},...X?{userProfile:X}:{}}}finally{clearTimeout(U),k.abort()}}async function C(g,R){try{const L=e.identity.get()?.version?.trim(),k=await A(Xd,{mini_program_id:g,...L?{miniprogram_version:L}:{}},R),U=st(k,"小程序公开资料"),W=mt(U.name),j=mt(U.icon_url);return W||j?{...W?{name:W}:{},...j?{avatarUrl:j}:{}}:void 0}catch{return}}async function O(g){try{const R=await A(Sa,void 0,g),L=st(R,"账号基础信息"),k=mt(L.display_username),U=mt(L.display_avatar);return k||U?{...k?{nickname:k}:{},...U?{avatar:U}:{}}:void 0}catch{return}}async function y(g,R){if(au(d,"auth.login"),!c&&g.includes(Gi))throw l("INVALID_PARAMS","auth.login 参数不合法");const L=I(),k=await _(R),U=i,W=await A(ru,{runtimeContext:{miniProgramId:L,...await u()},scopes:g});await p(k,U);const j=st(W,"小程序登录"),X=bo(j,"loginCode"),K=bo(j,"consentChallenge");if(X===K)throw l("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let ne;if(X)ne=Ao(j.loginCode,c);else{const rt=yu(j.consentChallenge,c),it=await S(L,rt,R,k,U);await p(k,U);const on=await A(iu,{runtimeContext:{miniProgramId:L,...await u()},challenge:rt.challenge,selectedScopes:it});if(await p(k,U),ne=Ao(st(on,"小程序登录确认"),c),ne.scopes.some(fe=>!it.includes(fe)))throw l("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}r.clear();for(const rt of ne.scopes)r.add(rt);return f("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),f("user_info_authorization_change",Tr(r,c)),ne}async function D(g,R){const L=i,k=await A(nu,{runtimeContext:{miniProgramId:R,...await u()}});await p(g,L);const U=wu(st(k,"用户本地身份"),c);for(const W of c?gt:Pa)r.add(W);return f("user_info_authorization_change",Tr(r,c)),U}function N(g){E();const R=I(),L=`${g}\0${R}`,k=n.get(L);if(k)return k;const U=D(g,R).finally(()=>{n.get(L)===U&&n.delete(L)});return n.set(L,U),U}async function P(g){if(!g)throw l("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const R=I(),L=i,k=await w();if(!k)throw l("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const U=await A(tu,{runtimeContext:{miniProgramId:R,...await u()}});await p(k,L),st(U,"用户授权撤销"),h(),f("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{login:y,getOrCreateLocalIdentity:N,getAuthorization:()=>Tr(r,c),revoke:P,onEvent(g){return t.add(g),()=>t.delete(g)},dispose(){o||(o=!0,h(),m(),t.clear())}}}function Eu(e,t,n){const r=l(e,t);return Object.defineProperty(r,"cause",{configurable:!0,enumerable:!1,value:n}),r}function st(e,t){if(!M(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const n=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,r=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(r,n)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Ao(e,t){if(!M(e))throw l("INVALID_RESPONSE","login code 必须是对象");const n=nr(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!n.includes("identity"))throw l("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:n}}function yu(e,t){if(!M(e))throw l("INVALID_RESPONSE","授权 challenge 必须是对象");const n=nr(e.requestedScopes,"challenge requestedScopes",t),r=nr(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||!n.length||!n.includes("identity")||!r.length||!r.includes("identity")||n.some(i=>!r.includes(i)))throw l("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:n,displayedScopes:r}}function wu(e,t){if(!M(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw l("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const n=e.appUserId.trim();if(!t)return{appUserId:n};if(e.steamId!==void 0&&typeof e.steamId!="string")throw l("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const r=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return r?{appUserId:n,steamId:r}:{appUserId:n}}function Iu(e,t,n){const r=nr(e,"授权选择 scopes",n);if(r.some(i=>!t.includes(i)))throw l("INVALID_RESPONSE","授权选择包含未展示的 scope");return r}function mt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Au(e){const t=mt(e?.name),n=mt(e?.avatarUrl);return t||n?{...t?{name:t}:{},...n?{avatarUrl:n}:{}}:void 0}function _o(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 _u(e,t){return t.aborted?Promise.reject(Ei()):new Promise((n,r)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>r(Ei()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>n(a)),a=>o(()=>r(a)))})}function Ei(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function nr(e,t,n){const r=n?mu:Pa;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!r.has(i))||new Set(e).size!==e.length)throw l("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Tr(e,t){const n=t?gt:gt.filter(r=>r!==Gi);return Object.fromEntries(n.map(r=>[r,e.has(r)?"granted":"not_requested"]))}function bo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ra(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function So(e,t,n){return t.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Ra(e)?e:l("REQUEST_FAILED",n)}const bu=new Set(gt);function Su(e){return{[Pn]:async(t,n)=>e.authorization.login(vu(t),n.trustedUserGesture)}}function vu(e){if(e===void 0)return["identity"];if(!M(e)||Object.keys(e).some(t=>t!=="scopes"))throw vo();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!bu.has(t))||new Set(e.scopes).size!==e.scopes.length)throw vo();return[...e.scopes]}function vo(){return l("INVALID_PARAMS","auth.login 参数不合法")}const Ou={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.delete.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/current/delete",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return de(e,"排行榜记录删除接口响应异常")}},Du={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/current",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return de(e,"当前排行榜记录接口响应异常")}},Pu={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.info.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/info",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return de(e,"排行榜信息接口响应异常")}},Ru={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.list.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/list",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{},limit:e.limit,...e.cursor?{cursor:e.cursor}:{}}},parse(e,t){return de(e,"排行榜列表接口响应异常")}},Nu={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.submit.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/submit",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{},score:e.score,...e.extra===void 0?{}:{extra:JSON.stringify(e.extra)}}},parse(e,t){return de(e,"排行榜提交接口响应异常")}};function wn(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Oo(e){return e instanceof J?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function $(e){if(e.aborted)throw wn()}function z(e,t,n={}){if(t.aborted&&!n.invokeWhenAborted)return Promise.reject(wn());let r;try{r=e()}catch(i){return Promise.reject(Oo(i))}return t.aborted?(Promise.resolve(r).catch(()=>{}),Promise.reject(wn())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(wn()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(r).then(d=>a(()=>i(d)),d=>a(()=>o(Oo(d))))})}const Cu="default",Tu=/^[A-Za-z0-9_-]{1,64}$/,Lu=300*1e3,ku=250,Mu=3,Uu={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"};class xu{constructor(t){this.options=t,this.unsubscribeAccountChange=Fu(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;disposed=!1;handleTerminalAbort=()=>this.dispose();async submit(t){this.assertUsable();const n=this.accountGeneration,r=this.readMiniProgramId();await this.requireCurrentUser(n);const i=await this.request(Nu,{miniProgramId:r,...t});this.assertAccountGeneration(n);const o=bt(i,Pe);return this.invalidateMutableReads(this.createBucketKey(r,t.key)),Lr(o,Pe)}getList(t){this.assertUsable();const n=this.readMiniProgramId(),r=this.createBucketKey(n,t.key),i=St("list",t.limit,t.cursor??null);return this.read(r,"list",i,async()=>{const o=await this.request(Ru,{miniProgramId:n,...t}),s=bt(o,me);if(!_e(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw G(`${me} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw G(`${me} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>Lr(a,me)),...typeof s.cursor=="string"&&s.cursor?{cursor:s.cursor}:{},hasMore:s.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const n=this.accountGeneration,r=this.readMiniProgramId(),i=await this.requireCurrentUser(n),o=this.createBucketKey(r,t.key),s=St("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(Du,{miniProgramId:r,...t}),c=bt(a,xe);if(!_e(c))throw G(`${xe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Lr(c.entry,xe)})}async deleteCurrentUserEntry(t){this.assertUsable();const n=this.accountGeneration,r=this.readMiniProgramId();await this.requireCurrentUser(n);const i=await this.request(Ou,{miniProgramId:r,...t});this.assertAccountGeneration(n);const o=bt(i,Ze);if(this.invalidateMutableReads(this.createBucketKey(r,t.key)),!_e(o)||typeof o.deleted!="boolean")throw G(`${Ze} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const n=this.readMiniProgramId(),r=this.createBucketKey(n,t.key);return this.read(r,"info",St("info"),async()=>{const i=await this.request(Pu,{miniProgramId:n,...t}),o=bt(i,Ae);if(!_e(o)||typeof o.key!="string"||!Tu.test(o.key))throw G(`${Ae} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw G(`${Ae} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw G(`${Ae} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw G(`${Ae} 返回的 rankLimit 必须是非负整数`);return{key:o.key,order:o.order,rankLimit:o.rank_limit}})}read(t,n,r,i){this.assertUsable();const o=this.getOrCreateBucket(t),s=o?.caches[n],a=s?.get(r);if(a&&a.expiresAt>Date.now())return Promise.resolve(a.value);s?.delete(r);const c=St(t,r),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,m=o?.generation,h=i().then(f=>(this.assertAccountGeneration(u),o&&s&&o.generation===m&&(n==="list"?s.size>=ku&&s.delete(s.keys().next().value):s.clear(),s.set(r,{expiresAt:Date.now()+Lu,value:f})),f)).finally(()=>{this.inflight.get(c)?.promise===h&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:h}),h}getOrCreateBucket(t){const n=this.buckets.get(t);if(n)return n;if(this.pruneExpiredBuckets(),this.buckets.size>=Mu)return;const r={generation:0,caches:{list:new Map,current:new Map,info:new Map}};return this.buckets.set(t,r),r}invalidateMutableReads(t){this.invalidateInflight(t);const n=this.buckets.get(t);n&&(n.generation+=1,n.caches.list.clear(),n.caches.current.clear())}invalidateForAccountChange(){this.accountGeneration+=1,this.buckets.clear(),this.inflight.clear()}invalidateInflight(t){for(const[n,r]of this.inflight)r.bucketKey===t&&this.inflight.delete(n)}pruneExpiredBuckets(){const t=Date.now();for(const[n,r]of this.buckets)Po(r,t),this.isBucketEmpty(n,r)&&this.buckets.delete(n)}removeEmptyBucket(t,n){Po(n,Date.now()),this.buckets.get(t)===n&&this.isBucketEmpty(t,n)&&this.buckets.delete(t)}isBucketEmpty(t,n){return![...this.inflight.values()].some(r=>r.bucketKey===t)&&Object.values(n.caches).every(r=>r.size===0)}async requireCurrentUser(t){this.assertUsable();let n;try{n=await z(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(r){throw No(r)?r:Ro()}if(this.assertAccountGeneration(t),typeof n!="string"||!n.trim())throw he("UNAUTHORIZED","当前用户未登录");return n.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw he("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,n){return St(t,n??Cu)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw he("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,n){this.assertUsable();const r={request:async(i,o)=>(this.assertUsable(),this.options.network.request(i,o))};try{return await z(()=>Ar(r,t,n,{...this.options.operationContext,credentials:"heybox-session"}),this.options.operationContext.signal)}catch(i){throw No(i)||yi(i,"REQUEST_UNSUPPORTED")?i:i instanceof J?he("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求"):i instanceof yt&&yi(i.cause,"INVALID_STATE")?i.cause:i instanceof Et&&(i.status===401||i.status===403)?he("UNAUTHORIZED","当前用户未登录"):i instanceof yt||i instanceof Et?Ro():i instanceof Zt?G(i.cause instanceof Error?i.cause.message:"排行榜响应不合法"):G(i instanceof Error?i.message:"排行榜响应不合法")}}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($(this.options.operationContext.signal),this.disposed)throw he("INVALID_STATE","Cloud capability 已释放")}}function Hu(e){return new xu(e)}function Fu(e,t){try{return e.onChange(t)}catch(n){if(yi(n,Aa))return()=>{};throw n}}function bt(e,t){if(!_e(e)||typeof e.status!="string")throw G(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Bu(e);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw G(`${t} 响应缺少 result`);return e.result}function Lr(e,t){if(!_e(e))throw G(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw G(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw G(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw G(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw G(`${t} 返回的 score 必须是有限数字`);if(!_e(e.extra))throw G(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw G(`${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 Bu(e){if(e.status==="login"||e.status==="relogin")throw he("UNAUTHORIZED",Pt(e.msg)||"当前用户未登录");const t=Do(e.result)??Do(e),n=Pt(t?.user_message)||Pt(e.msg)||Pt(t?.developer_message)||"排行榜请求失败";throw t?he(Vu(t),n,{status:e.status,sbe:t}):he("HEYBOX_API_ERROR",n,{status:e.status})}function Do(e){return _e(e)&&_e(e.sbe)?e.sbe:void 0}function Vu(e){const t=Pt(e.developer_message);if(t&&/^[A-Z][A-Z0-9_]+$/.test(t))return t;const n=e.code;if(typeof n=="number"&&Number.isInteger(n))return Uu[n]||t||"HEYBOX_API_ERROR";if(typeof n=="string"){const r=/^([A-Za-z][A-Za-z0-9_]*)(?:\(\d+\))?$/.exec(n.trim());if(r?.[1])return r[1]}return t||"HEYBOX_API_ERROR"}function Po(e,t){for(const n of Object.values(e.caches))for(const[r,i]of n)i.expiresAt<=t&&n.delete(r)}function St(...e){return JSON.stringify(e)}function _e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function yi(e,t){return _e(e)&&e.code===t}function he(e,t,n){return n===void 0?{code:e,message:t}:{code:e,message:t,data:n}}function G(e){return he("INVALID_RESPONSE",e)}function Ro(){return he("REQUEST_FAILED","排行榜请求失败")}function No(e){return e instanceof Error&&e.name==="AbortError"}const qu=/^[A-Za-z0-9_-]{1,64}$/,Co=20,zu=100,To=2048;function ju(e){const t=Hu(e);return{handlers:{[Pe]:async r=>t.submit(Gu(r)),[me]:async r=>t.getList($u(r)),[xe]:async r=>t.getCurrentUserEntry(kr(r,xe)),[Ze]:async r=>t.deleteCurrentUserEntry(kr(r,Ze)),[Ae]:async r=>t.getInfo(kr(r,Ae))},dispose:()=>t.dispose()}}function Gu(e){const t=$i(e,Pe,!1);if(Wi(t,["key","score","extra"],Pe),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw be("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Ki(t.key,Pe),score:t.score,...t.extra===void 0?{}:{extra:Wu(t.extra)}}}function $u(e){if(e===void 0)return{limit:Co};const t=$i(e,me,!0);Wi(t,["key","limit","cursor"],me);const n=t.limit===void 0?Co:t.limit;if(typeof n!="number"||!Number.isInteger(n)||n<=0||n>zu)throw be("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw be("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Ki(t.key,me),limit:n,...t.cursor===void 0?{}:{cursor:t.cursor}}}function kr(e,t){if(e===void 0)return{};const n=$i(e,t,!0);return Wi(n,["key"],t),Ki(n.key,t)}function $i(e,t,n){if(e===void 0&&n)return{};if(!Na(e))throw be("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Wi(e,t,n){const r=Object.keys(e).find(i=>!t.includes(i));if(r)throw be("INVALID_PARAMS",`${n} 不支持参数 ${r}`)}function Ki(e,t){if(e===void 0)return{};if(typeof e!="string"||!qu.test(e))throw be("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function Wu(e){if(!Na(e))throw be("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw be("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw be("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>To)throw be("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${To} 字节`);return e}function Na(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function be(e,t){return{code:e,message:t}}const Ku=new Set(["stdio","attachments","notifications"]),Ca=new Set(["windows-x64","macos-arm64"]),Yu=new Set(["unsigned","valid","invalid","unknown"]),Qu=/^[a-f0-9]{64}$/,Xu=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Ju=new Set(wa),Zu=new Set([...wa,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Ta=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 el(e){const t=async(r,i,o,s)=>{const a=tl(r);try{Ie(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Ie(i.signal),c}catch(c){throw Ii(c,s)}},n=async(r,i,o)=>{if(!o.trustedUserGesture)throw l("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw l("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>nl(d,i)).catch(d=>{throw Ii(d)});Ie(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:r,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Ie(o.signal),c.status!=="granted")throw l("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[dr]:(r,i)=>t(r,i,async(o,s)=>wi(await e.companion.getInfo(o,s),o)),[ur]:(r,i)=>t(r,i,async(o,s)=>Lo(await e.companion.getPreparationStatus(o,s))),[lr]:(r,i)=>t(r,i,async(o,s)=>{const a=Lo(await e.companion.getPreparationStatus(o,s));return Ie(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await n("prepare",o,i),Ie(i.signal),wi(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(ka(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[fr]:(r,i)=>t(r,i,(o,s)=>e.companion.cancelPreparation(o,s)),[hr]:(r,i)=>t(r,i,async(o,s)=>ko(await e.companion.getActiveSession(o,s),o)),[mr]:(r,i)=>t(r,i,async(o,s)=>{const a=ko(await e.companion.getActiveSession(o,s),o);return Ie(i.signal),a||(await n("launch",o,i),Ie(i.signal),Ma(await e.companion.launch(o,s),o))}),[pr]:(r,i)=>at(r,i,e,"write"),[gr]:(r,i)=>at(r,i,e,"closeStdin"),[Er]:(r,i)=>at(r,i,e,"terminate"),[yr]:(r,i)=>at(r,i,e,"ackOutput"),[wr]:async(r,i)=>{const o=await at(r,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Ir]:(r,i)=>at(r,i,e,"showNotification")}}function tl(e){if(!M(e)||typeof e.alias!="string"||!Ed.test(e.alias))throw l("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Ie(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function at(e,t,n,r){if(!M(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw l("INVALID_PARAMS","Companion Session controller 不合法");try{Ie(t.signal);const i=await n.companion[r](rl(e,r),{...n.operationContext,signal:t.signal});return Ie(t.signal),i}catch(i){throw Ii(i)}}function pe(){throw l("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function La(e){return!Array.isArray(e)||e.some(t=>!Ku.has(t))?pe():Object.freeze([...new Set(e)])}function wi(e,t){return!M(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Ca.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!Yu.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?pe():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:La(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function nl(e,t){const n=wi(e,t);return!M(e)||e.sha256===void 0?n:typeof e.sha256!="string"||!Qu.test(e.sha256)?pe():Object.freeze({...n,sha256:e.sha256})}function ka(e){return M(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):pe():pe()}function Lo(e){return M(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:ka(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&M(e.error)&&typeof e.error.code=="string"&&Ju.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:Ta[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):pe():pe()}function Ma(e,t){return!M(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Ca.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?pe():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:La(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function ko(e,t){return e===void 0?void 0:Ma(e,t)}function rl(e,t){const n=e,r={sessionId:n.sessionId,controllerGeneration:n.controllerGeneration};if(t==="write"){if(!ga(n.data))throw l("INVALID_PARAMS","Companion write data 不合法");return{...r,data:new Uint8Array(n.data)}}if(t==="ackOutput"){if(n.stream!=="stdout"&&n.stream!=="stderr"||!Number.isSafeInteger(n.sequence)||Number(n.sequence)<0)throw l("INVALID_PARAMS","Companion output ack 不合法");return{...r,stream:n.stream,sequence:n.sequence}}if(t==="openAttachment"){if(typeof n.id!="string"||!n.id)throw l("INVALID_PARAMS","Companion Attachment ID 不合法");return{...r,id:n.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(n.category)))throw l("INVALID_PARAMS","Companion notification category 不合法");return{...r,category:n.category}}return r}function il(e){return!M(e)||!Xu.has(String(e.reason))?pe():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):pe():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?pe():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function ol(e){if(!M(e)||!M(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,n=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||!ga(t.data)?void 0:{type:e.type,payload:{sessionId:n,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:n,exit:il(t.exit)}}}catch{return}if(e.type==="companion.session.ownershipLost"&&Number.isSafeInteger(t.controllerGeneration)&&Number(t.controllerGeneration)>=0)return{type:e.type,payload:{sessionId:n,controllerGeneration:t.controllerGeneration}}}function Ii(e,t){return M(e)&&typeof e.code=="string"&&Zu.has(e.code)?l(e.code,Ta[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&M(e)&&e.name==="AbortError"?l(t,"Companion 准备已取消"):l("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Mo=5e3,Uo=1e4;function Qe(e){throw{code:"INVALID_PARAMS",message:e}}function Ua(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xa(e,t,n){const r=Object.keys(e).filter(i=>!t.includes(i));r.length&&Qe(`${n} 不支持字段: ${r.join(", ")}`)}function sl(e){if(e===void 0)return{intensity:"light",delay:0};if(!Ua(e))return Qe("device.vibrate 参数必须是对象");xa(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return Qe("device.vibrate intensity 必须是 light、medium 或 heavy");const n=t,r=e.delay??0;return typeof r!="number"||!Number.isInteger(r)||r<0||r>Mo?Qe(`device.vibrate delay 必须是 0-${Mo} 的整数毫秒`):{intensity:n,delay:r}}function al(e){return Ua(e)?(xa(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?Qe("device.setClipboard text 必须是非空字符串"):e.text.length>Uo?Qe(`device.setClipboard text 不能超过 ${Uo} 字符`):{text:e.text}):Qe("device.setClipboard 参数必须是对象")}function cl(e){return{[Xn]:async t=>{$(e.operationContext.signal),await z(()=>e.presentation.vibrate(sl(t),e.operationContext),e.operationContext.signal)},[Jn]:async t=>{$(e.operationContext.signal),await z(()=>e.presentation.setClipboard(al(t),e.operationContext),e.operationContext.signal)}}}const dl=new Set(["METHOD_FORBIDDEN","FILE_PICKER_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_ENCODING_INVALID","DIRECTORY_LIST_LIMIT_EXCEEDED","DIRECTORY_NOT_EMPTY","FILE_IO_FAILED"]),ul={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 Yi(e){const t=Ha(e),n=t&&dl.has(t)?l(t,ul[t]??"文件操作失败"):l("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(n,"cause",{value:e,enumerable:!1}),n}function De(e){try{return e()}catch(t){throw Yi(t)}}function Ha(e){try{if(!M(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function Fa(e,t,n={}){const r=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=r==="readwrite",o=n.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:r,create:i?(s,a)=>e.create(s,a):Ai,remove:o?s=>e.remove(s):Va,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Ai,stat:s=>e.stat(s)})}function Ba(e,t,n={}){const r=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=r==="readwrite",o=n.allowRemove!==!1,s=o&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:r,file:a=>Fa(e.file(a),r,{allowRemove:o}),directory:a=>Ba(e.directory(a),r,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Ai,remove:s?(a,c)=>e.remove(a,c):Va,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Ai(){return Promise.reject(l("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Va(){return Promise.reject(l("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const xo=1024;class ll{constructor(t,n){this.files=t,this.miniProgramDetail=n}handles=new Map;disposed=!1;dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,n="external",r){this.assertCanonicalDetail();const i=this.prepareFile(t,n,r),[o]=this.registerMany([i]);return dn(i.handle,{kind:"file",handleId:o})}registerFiles(t,n="external",r,i){this.assertCanonicalDetail();const o=De(()=>{if(!Array.isArray(t))throw l("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw l("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>xo)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw l("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],n,r))}return c}),s=this.registerMany(o);return o.map((a,c)=>dn(a.handle,{kind:"file",handleId:s[c]}))}registerDirectory(t,n="external",r){this.assertCanonicalDetail();const i=this.prepareDirectory(t,n,r),[o]=this.registerMany([i]);return Fo(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Vi(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const n=hl(t);if("handleId"in n){const s=this.readDirect(n.handleId,"file");return{ref:n,...s}}const r=this.resolveRoot(n.root),i=$t(n.relativePath),o=this.prepareFile(De(()=>r.hostHandle.file(i)),r.origin,r.handle.mode);return{ref:n,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const n=ml(t);if("handleId"in n){const s=this.readDirect(n.handleId,"directory");return{ref:n,...s}}const r=this.resolveRoot(n.root),i=n.relativePath==="."?".":$t(n.relativePath),o=this.prepareDirectory(i==="."?r.hostHandle:De(()=>r.hostHandle.directory(i)),r.origin,r.handle.mode,!0);return{ref:n,...o}}describeFile(t,n){return Vo(t),dn(t,n)}describeListedEntries(t,n,r){return this.assertCanonicalDetail(),De(()=>{if(!Array.isArray(n))throw l("FILE_IO_FAILED","Host 返回了无效目录列表");const i=n.length;if(i>r)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(n,s))throw l("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,n[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,n){return De(()=>{if(M(n)&&n.kind==="file"){const r=this.prepareFile(n,t.origin,t.handle.mode);return dn(r.handle,Ho(t.ref,r.handle.name))}if(M(n)&&n.kind==="directory"){const r=this.prepareDirectory(n,t.origin,t.handle.mode);return Fo(r.handle,fl(t.ref,r.handle.name))}throw l("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,n){this.assertCanonicalDetail();const r=en(n),i=this.prepareFile(De(()=>t.hostHandle.file(r)),t.origin,t.handle.mode);return{ref:Ho(t.ref,r),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw l("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,n,r){return De(()=>{Vo(t);const i=r??t.mode;return Bo(t.mode,i),{handle:Fa(t,i,{allowRemove:n==="sandbox"}),hostHandle:t,origin:n}})}prepareDirectory(t,n,r,i=!1){return De(()=>{El(t,i);const o=r??t.mode;return Bo(t.mode,o),{handle:Ba(t,o,{allowRemove:n==="sandbox"}),hostHandle:t,origin:n}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>xo)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const n=new Set,r=t.map(()=>{for(let i=0;i<8;i+=1){const o=pl();if(!this.handles.has(o)&&!n.has(o))return n.add(o),o}throw l("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(r[o],i)),r}readDirect(t,n){if(!gl(t))throw l("FILE_ACCESS_REVOKED","文件授权句柄无效");const r=this.handles.get(t);if(!r)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(r.handle.kind!==n||r.hostHandle.kind!==n)throw l("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return r}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Se("files.sandbox");return this.prepareDirectory(De(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Se("files")}}function $t(e){if(!Bi(e))throw l("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function en(e,t="文件名"){const n=$t(e);if(n.includes("/"))throw l("INVALID_PARAMS",`${t} 只能是 basename`);return n}function Ho(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:$t(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function fl(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:$t(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function dn(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function Fo(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Bo(e,t){if(t==="readwrite"&&e!=="readwrite")throw l("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function hl(e){return Vi(e)||qa(),e}function ml(e){return pa(e)||qa(),e}function qa(){throw l("INVALID_PARAMS","文件引用不合法")}function pl(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw l("FILE_IO_FAILED","当前环境缺少安全随机数能力");const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function gl(e){return/^[0-9a-f]{32}$/.test(e)}function Vo(e){if(!M(e)||e.kind!=="file"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.create!="function"||typeof e.read!="function"||typeof e.write!="function"||typeof e.stat!="function")throw l("FILE_IO_FAILED","Host 返回了无效 File handle");en(e.name,"Host File name")}function El(e,t=!1){if(!M(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 l("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw l("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&en(e.name,"Host Directory name")}const qo=1e3,yl=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function wl(e){const t=n=>ji(e.operationContext,n.signal);return{files:{[Fn]:async(n,r)=>{Mr(r);const i=Ur(e.picker),o=Il(n),s=await se(()=>i.pickFiles(o,t(r)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Bn]:async(n,r)=>{Mr(r);const i=Ur(e.picker),o=Al(n),s=await se(()=>i.pickDirectory(o,t(r)));return e.registry.registerDirectory(s,"external",o.mode)},[Vn]:async(n,r)=>{Mr(r);const i=Ur(e.picker),o=_l(n).suggestedName,s=t(r);if(!i.saveFile)throw Se("files.saveFile");const a=await se(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[Ft]:async(n,r)=>{const i=ue(n,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);ct(o.mode),await se(()=>o.create(zo(i),t(r)))},[Bt]:async(n,r)=>{const i=ue(n),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),ct(o.handle.mode),!o.handle.remove)throw Se(Bt);await se(()=>o.handle.remove(t(r)))},[qn]:async(n,r)=>{const i=ue(n);return jo(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(r));if(!M(o)||o.kind!=="file")throw $o()})},[Vt]:async(n,r)=>{const i=ue(n),o=Go(await se(()=>e.registry.resolveFile(i.target).read(t(r))));try{const s=new TextDecoder("utf-8",{fatal:!0}).decode(o);return s.charCodeAt(0)===65279?s.slice(1):s}catch{throw l("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[zn]:async(n,r)=>{const i=ue(n,["content"]);typeof i.content!="string"&&le("content 必须是字符串");const o=e.registry.resolveFile(i.target);ct(o.mode),await se(()=>o.write(new TextEncoder().encode(i.content),t(r)))},[qt]:async(n,r)=>{const i=ue(n),o=await se(()=>e.registry.resolveFile(i.target).read(t(r)));return Go(o)},[jn]:async(n,r)=>{const i=ue(n,["content"]),o=e.registry.resolveFile(i.target);ct(o.mode),await se(()=>o.write(Sl(i.content),t(r)))},[zt]:async(n,r)=>{const i=ue(n),o=await se(()=>e.registry.resolveFile(i.target).stat(t(r)));return vl(o)}},directory:{[Gn]:async(n,r)=>{const i=ue(n,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);ct(o.mode),await se(()=>o.create(zo(i),t(r)))},[jt]:async(n,r)=>{const i=ue(n,["recursive"]);if(M(i.target)&&i.target.relativePath===".")throw l("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),ct(o.handle.mode),!o.handle.remove)throw Se(jt);await se(()=>o.handle.remove({recursive:i.recursive===void 0?!1:rr(i.recursive,"recursive")},t(r)))},[$n]:async(n,r)=>{const i=ue(n);return jo(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(r));if(!M(o)||o.kind!=="directory")throw $o()})},[Wn]:async(n,r)=>{const i=ue(n,["limit"]),o=bl(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await se(()=>s.handle.list({limit:o},t(r)));return e.registry.describeListedEntries(s,a,o)}}}}function Il(e){if(e===void 0)return{mode:"read",multiple:!1};M(e)||le("pickFiles 参数必须是对象"),_r(e,["mode","accept","multiple"]);const t=za(e.mode,"read"),n=e.multiple===void 0?!1:rr(e.multiple,"multiple");let r;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)))&&le("accept 必须是规范扩展名数组"),r=[...new Set(e.accept)]),{mode:t,multiple:n,...r===void 0?{}:{accept:r}}}function Al(e){return e===void 0?{mode:"read"}:(M(e)||le("pickDirectory 参数必须是对象"),_r(e,["mode"]),{mode:za(e.mode,"read")})}function _l(e){return M(e)||le("saveFile 参数必须是对象"),_r(e,["suggestedName"]),{suggestedName:en(e.suggestedName,"suggestedName")}}function ue(e,t=[]){return(!M(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&le("文件操作参数必须包含 target"),_r(e,["target",...t]),e}function zo(e){return{recursive:e.recursive===void 0?!1:rr(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:rr(e.exclusive,"exclusive")}}function za(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&le("mode 必须是 read 或 readwrite"),e)}function rr(e,t){return typeof e!="boolean"&&le(`${t} 必须是布尔值`),e}function bl(e){if(e===void 0)return qo;if((!Number.isSafeInteger(e)||e<=0)&&le("limit 必须是正整数"),e>qo)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function _r(e,t){const n=Object.keys(e).filter(r=>!t.includes(r));n.length&&le(`不支持字段: ${n.join(", ")}`)}function ct(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Mr(e){if(!e.trustedUserGesture)throw l("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Ur(e){if(!e)throw Se("files.external");return e}async function jo(e){try{return await e(),!0}catch(t){if(yl.has(Ha(t)??""))return!1;throw Yi(t)}}async function se(e){try{return await e()}catch(t){throw Yi(t)}}function Sl(e){return e instanceof Uint8Array||le("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&le("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Go(e){if(!(e instanceof Uint8Array))throw l("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function $o(){return l("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function vl(e){if(!M(e)||e.kind!=="file"||!Ol(e.size))throw l("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Dl(e[t]))throw l("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 Ol(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Dl(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function le(e){throw l("INVALID_PARAMS",e)}const un=4294967296;function Pl(e){const t=new Rl;return t.write(e),t.finish()}class Rl{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<un?(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 n=Nl(t),r=n.byteLength;if(r<32)this.writeUint8(160+r);else if(r<256)this.writeUint8(217),this.writeUint8(r);else if(r<65536)this.writeUint8(218),this.writeUint16(r);else if(r<un)this.writeUint8(219),this.writeUint32(r);else throw new Error("share extra string is too long");this.writeBytes(n)}writeArray(t){const n=t.length;n<16?this.writeUint8(144+n):n<65536?(this.writeUint8(220),this.writeUint16(n)):(this.writeUint8(221),this.writeUint32(n));for(const r of t)this.write(r)}writeMap(t){const n=Object.keys(t),r=n.length;r<16?this.writeUint8(128+r):r<65536?(this.writeUint8(222),this.writeUint16(r)):(this.writeUint8(223),this.writeUint32(r));for(const i of n)this.writeString(i),this.write(t[i])}ensureCapacity(t){const n=this.offset+t;if(n<=this.bytes.byteLength)return;const r=new Uint8Array(Math.max(n,this.bytes.byteLength*2));r.set(this.bytes),this.bytes=r,this.view=new DataView(r.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/un),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/un)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Nl(e){const t=new Uint8Array(Cl(e));let n=0,r=0;for(;n<e.length;){let i=e.charCodeAt(n++);if(i>=55296&&i<=56319&&n<e.length){const o=e.charCodeAt(n);o>=56320&&o<=57343&&(n+=1,i=((i&1023)<<10)+(o&1023)+65536)}i<128?t[r++]=i:i<2048?(t[r++]=i>>6&31|192,t[r++]=i&63|128):i<65536?(t[r++]=i>>12&15|224,t[r++]=i>>6&63|128,t[r++]=i&63|128):(t[r++]=i>>18&7|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=i&63|128)}return t}function Cl(e){let t=0,n=0;for(;n<e.length;){let r=e.charCodeAt(n++);if(r<128)t+=1;else if(r<2048)t+=2;else{if(r>=55296&&r<=56319&&n<e.length){const i=e.charCodeAt(n);i>=56320&&i<=57343&&(n+=1,r=((r&1023)<<10)+(i&1023)+65536)}t+=r<65536?3:4}}return t}function ja(e){_i(e);const t=Pl(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 _i(e,t=0,n=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(n.has(e))throw new Error("extra value must not contain cycles");if(n.add(e),Array.isArray(e)){if(e.length>64)throw new Error("extra array is too large");for(const o of e)_i(o,t+1,n);n.delete(e);return}const r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==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");_i(s,t+1,n)}n.delete(e)}const Tl=["pc","console","mobile"],Ll=["game","wiki"];function ir(e){throw{code:"INVALID_PARAMS",message:e}}function kl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fe(e,t){return typeof e!="string"||!e.trim()?ir(t):e.trim()}function Wo(e,t,n){return typeof e!="string"||!t.includes(e)?ir(n):e}function Ml(e){const t={target:"game_detail",appId:Fe(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Wo(e.gameType,Tl,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Wo(e.page,Ll,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Fe(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Fe(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Ul(e){return{target:"user_detail",userId:Fe(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function xl(e){const t={target:"post_detail",linkId:Fe(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Fe(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Fe(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Hl(e){const t={target:"mini_program",miniProgramId:Fe(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Fl(e){return kl(e)?e.target==="game_detail"?Ml(e):e.target==="user_detail"?Ul(e):e.target==="post_detail"?xl(e):e.target==="mini_program"?Hl(e):ir("navigation.openAppPage target 不支持"):ir("navigation.openAppPage options 必须是对象")}function Bl(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 Vl(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function ql(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 zl(e){const t=e;return t.target==="game_detail"?Bl(t):t.target==="user_detail"?Vl(t):ql(t)}function Ga(e){throw{code:"INVALID_PARAMS",message:e}}function Ko(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Ga(`${t} 不支持参数`)}function jl(e){return{[Zn]:async t=>{$(e.operationContext.signal),Ko(t,"navigation.close"),await z(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[er]:async t=>{$(e.operationContext.signal),Ko(t,"navigation.reload"),await z(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[tr]:async t=>{$(e.operationContext.signal);const n=Fl(t);if(n.target==="mini_program"){let r;if(n.extra!==void 0)try{r=ja(n.extra)}catch{Ga("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}await z(()=>e.presentation.openWindow({miniProgramId:n.miniProgramId,...r===void 0?{}:{extra:r}},e.operationContext),e.operationContext.signal);return}await z(()=>e.presentation.openAppPage(zl(n),e.operationContext),e.operationContext.signal)}}}const Gl=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),$l=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Wl=new Set(["range","if-range","a-im"]),Kl=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"]),Yl=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,ln={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Ql{constructor(t){this.signal=t}phase="initial";transition(t){if(ln[t]<=ln[this.phase])throw l("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(ln[this.phase]<ln.committed&&this.signal.aborted)throw Ka()}normalizeHostError(t,n){return this.throwIfCancelled(),Qi(t,n,this.signal)}}async function Xl(e,t,n){const r=n.transfer,i=n.fileRegistry;if(!r||!i)throw Se("network.download");const o=ji(n.operationContext,t.signal),s=new Ql(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await tf(e,i,o)}catch(u){throw s.normalizeHostError(u,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await r.network.open(e.request,o)}catch(u){throw s.normalizeHostError(u,"network")}let d=!1;try{s.throwIfCancelled(),s.transition("validate");const u=rf(c);of(c,u);const m=sf(c.status,u);if(e.maxBytes!==void 0&&m.expectedBytes!==void 0&&m.expectedBytes>e.maxBytes)throw l("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const h=nf(e,a,u,i);let f=0;const I=Zl(m.expectedBytes,e.maxBytes);Hr(t,xr(0,m));const E={...o,onProgress(_){!Number.isSafeInteger(_)||_<f||I!==void 0&&_>I||(f=_,Hr(t,xr(f,m)))}};s.transition("transfer"),d=!0;let w;try{w=await r.files.writeResource(h.hostHandle,c.body,{mode:h.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...m.expectedBytes===void 0?{}:{expectedBytes:m.expectedBytes}},E)}catch(_){throw s.normalizeHostError(_,"transfer")}s.transition("committed"),f=Jl(w,m,f,e.maxBytes),Hr(t,xr(f,m));const p=i.describeFile(h.handle,h.ref);return s.transition("completed"),p}finally{d||ef(r.network,c.body)}}function Jl(e,t,n,r){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=r===void 0?n:Math.min(n,r);try{const o=e?.committedBytes;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=i&&(r===void 0||o<=r))return o}catch{}return i}function Zl(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function ef(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function tf(e,t,n){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return bi(i.handle.mode),await hf(i.handle,n),{kind:"file",...i}}const r=t.resolveDirectoryEntry(e.to);return bi(r.handle.mode),await mf(r.handle,n),{kind:"directory",...r}}function nf(e,t,n,r){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=cf(e,n),o=r.deriveFile(t,i);return bi(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function rf(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 l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!M(e.headers))throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[n,r]of Object.entries(e.headers)){if(n!==n.toLowerCase()||!Gl.has(n)||!Array.isArray(r)||r.length===0)throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(r.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[n]=[...r]}return t}function of(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw l("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:ff(t,$l)});if((t["content-range"]?.length??0)>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function sf(e,t){const n=t["content-length"]??[],r=t["transfer-encoding"]??[];if(n.length>0&&r.length>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&n.some(d=>d!=="0"))throw l("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&r.length>0)throw l("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=n.length===1&&/^(?:0|[1-9]\d*)$/.test(n[0])?Number(n[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=af(t["content-encoding"]),a=e===204||e===205?0:r.length===0&&s?o:void 0,c=a!==void 0;return{...a===void 0?{}:{expectedBytes:a},...c?{total:a}:{},lengthComputable:c}}function af(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function xr(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Hr(e,t){try{e.postProgress(t)}catch{}}function cf(e,t){const n=t["content-disposition"]??[];for(const i of n){const o=df(i);if(o&&In(o))return o}for(const i of n){const o=uf(i);if(o&&In(o))return o}if(e.suggestedName!==void 0)return $a(e.suggestedName);const r=lf(e.url);return r&&In(r)?r:"download.bin"}function df(e){const t=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(e);if(!t)return;const n=t[1].trim().replace(/^"|"$/g,""),r=/^utf-8'[^']*'(.*)$/i.exec(n);if(r)try{return decodeURIComponent(r[1])}catch{return}}function uf(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 lf(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function $a(e){try{en(e,"suggestedName")}catch{throw l("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!In(e))throw l("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function In(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Yl.test(e))}function ff(e,t){return Object.fromEntries(Object.entries(e).filter(([n])=>t.has(n)).map(([n,r])=>[n,r.join(", ")]))}async function hf(e,t){try{const n=await e.stat(t);if(!n||n.kind!=="file")throw Wa()}catch(n){throw Qi(n,"file",t.signal)}}async function mf(e,t){try{const n=await e.stat(t);if(!n||n.kind!=="directory")throw Wa()}catch(n){throw Qi(n,"file",t.signal)}}function bi(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","下载目标只允许读取")}const pf={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 Qi(e,t,n){if(n.aborted)return Ka();const r=gf(e);if(r&&Kl.has(r)){const o=l(r,pf[r]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?l("DOWNLOAD_TIMEOUT","下载网络请求超时"):l("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?l("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):l("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function gf(e){return M(e)&&typeof e.code=="string"?e.code:void 0}function Wa(){return l("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Ka(){return l("DOWNLOAD_CANCELLED","下载已取消")}function Ef(e){if(!e)return;const t=Object.keys(e).find(n=>Wl.has(n.trim().toLowerCase()));if(t)throw l("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Xi="withCredentials",yf=new Set(["url","method","params","data","headers","timeout",Xi]),wf=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Xi]),If=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Yo=3e4,Qo=2*1024*1024,Af=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,_f=/[\u0000-\u0008\u000A-\u001F\u007F]/,bf=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Sf="network.request 不支持 multipart/form-data,请使用专用上传能力";function vf(e){const t=Of(e.runtimePermissions),n=Ff(e.allowedHttpOrigins);return{[Hn]:async(r,i)=>{const o=Pf(r,{permission:t,allowedHttpOrigins:n});return Xl(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[xn]:async(r,i)=>{const o=ji(e.operationContext,i?.signal);$(o.signal);const s=Df(r,{permission:t,allowedHttpOrigins:n});let a;try{a=await z(()=>e.network.request(s,o),o.signal)}catch(c){throw qf(c)?c:zf(c,"REQUEST_UNSUPPORTED")?H("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):H("REQUEST_FAILED","网络请求失败")}return Vf(a)}}}function Of(e){const t=Ne(e),n=t.permissions.network;return{enabled:t.valid&&n?.status==="enabled",useOfficialDomain:t.valid&&n?.status==="enabled"&&n.config.useOfficialDomain===!0}}function Df(e,t){const n=br(e,"network.request 参数必须是对象"),r=Object.keys(n).filter(c=>!yf.has(c));if(r.length>0)throw H("INVALID_PARAMS",`network.request 不支持字段: ${r.join(", ")}`);Qa(n,"network.request");const i=Ya(n,t,"network.request"),o=Nf(n.method),s=n.data;s!==void 0&&Lf(s),Mf(i.headers,s);const a=Uf(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 Pf(e,t){const n=br(e,"network.download 参数必须是对象"),r=Object.keys(n).filter(c=>!wf.has(c));if(r.length>0)throw H("INVALID_PARAMS",`network.download 不支持字段: ${r.join(", ")}`);Qa(n,"network.download");const i=Ya(n,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw H("INVALID_PARAMS","network.download timeout 必须是有限正数");Ef(i.headers);const o=Vi(n.to),s=pa(n.to);if(!o&&!s)throw H("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(n.suggestedName!==void 0||n.overwrite!==void 0))throw H("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(n.suggestedName!==void 0){if(typeof n.suggestedName!="string")throw H("INVALID_PARAMS","suggestedName 必须是字符串");a=$a(n.suggestedName)}if(n.overwrite!==void 0&&typeof n.overwrite!="boolean")throw H("INVALID_PARAMS","overwrite 必须是布尔值");if(n.maxBytes!==void 0&&(!Number.isSafeInteger(n.maxBytes)||n.maxBytes<=0))throw H("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:n.to,targetKind:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...n.overwrite===void 0?{}:{overwrite:n.overwrite},...n.maxBytes===void 0?{}:{maxBytes:n.maxBytes}}}function Ya(e,t,n){const r=Rf(e.url,t.allowedHttpOrigins,n),i=Wd(r);if(i&&!t.permission.useOfficialDomain)throw H("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if($d(r.pathname,i))throw H("PERMISSION_DENIED",`${n} 不允许访问 Runtime 或账号敏感接口`);return{url:r,official:i,params:e.params===void 0?void 0:{...br(e.params,`${n} params 必须是对象`)},headers:e.headers===void 0?void 0:Cf(e.headers,n),timeout:Tf(e.timeout,n)}}function Rf(e,t,n="network.request"){if(typeof e!="string"||!e.trim())throw H("INVALID_PARAMS",`${n} url 必须是 HTTP(S) URL`);let r;try{r=new URL(e)}catch{throw H("INVALID_PARAMS",`${n} url 必须是 HTTP(S) URL`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw H("INVALID_PARAMS",`${n} url 必须是 HTTP(S) URL`);if(r.username||r.password)throw H("INVALID_PARAMS",`${n} url 不允许包含用户信息`);if(r.protocol==="http:"&&!t.has(r.origin))throw H("PERMISSION_DENIED",`${n} 生产环境只允许 HTTPS`);return r}function Nf(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw H("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!If.has(t))throw H("INVALID_PARAMS","network.request method 不合法");return t}function Cf(e,t="network.request"){const n=br(e,`${t} headers 必须是 Record<string, string>`),r={};for(const[i,o]of Object.entries(n)){const s=i.trim();if(!s||s!==i||!Af.test(s)||typeof o!="string"||_f.test(o))throw H("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Kd(s))throw H("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);r[s]=o}return r}function Qa(e,t){const n=e[Xi];if(n!==void 0&&typeof n!="boolean")throw H("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Tf(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw H("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Yo)throw H("INVALID_PARAMS",`${t} timeout 不能超过 ${Yo}ms`);return e}}function Lf(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw H("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(kf(e)>Qo)throw H("INVALID_PARAMS",`network.request data 不能超过 ${Qo} 字节`)}function kf(e){if(typeof e=="string")return Fr(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return Fr(e.toString());try{const t=JSON.stringify(e);return t?Fr(t):0}catch{throw H("INVALID_PARAMS","network.request data 必须可序列化")}}function Mf(e,t){const n=Xa(e),r=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(n?.includes("multipart/form-data")||r)throw H("INVALID_PARAMS",Sf)}function Uf(e,t,n){if(t===void 0)return;const r=Xa(e);return r?.includes("application/x-www-form-urlencoded")?"form":r?.includes("application/json")?"json":typeof URLSearchParams<"u"&&t instanceof URLSearchParams||n&&(Array.isArray(t)||Hf(t))?"form":xf(t)?"json":void 0}function Xa(e){return e?Object.entries(e).find(([n])=>n.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function xf(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function Hf(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ff(e){const t=new Set;for(const n of e??[])try{const r=new URL(n);r.protocol==="http:"&&!r.username&&!r.password&&r.pathname==="/"&&!r.search&&!r.hash&&Bf(r.hostname)&&t.add(r.origin)}catch{}return t}function Bf(e){const t=e.toLowerCase();if(t==="[::1]")return!0;const n=t.split(".").map(Number);return n.length!==4||n.some((r,i)=>!/^\d+$/.test(t.split(".")[i])||r<0||r>255)?!1:n[0]===127||n[0]===10||n[0]===172&&n[1]>=16&&n[1]<=31||n[0]===192&&n[1]===168}function Vf(e){return Object.keys(e.headers).some(Xo)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Xo(t)))}:e}function Xo(e){const t=e.trim().toLowerCase();return bf.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function qf(e){return e instanceof Error&&e.name==="AbortError"}function zf(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function br(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw H("INVALID_PARAMS",t);return e}function Fr(e){return new TextEncoder().encode(e).length}function H(e,t){return{code:e,message:t}}function jf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gf(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 $f(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topicIds 必须是数组"],values:[]};const t=[],n=new Set,r=[];for(const i of e){const o=Gf(i);o?n.has(o)||(n.add(o),r.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:r}}function Wf(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topics 必须是数组"],values:[]};const t=[],n=new Set,r=[];for(const i of e){const o=typeof i=="string"?i.trim():"";!o||o.startsWith("#")||o.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):n.has(o)||(n.add(o),r.push(o))}return{invalidMessages:t,values:r}}function Ja(e,t){if(e==null)return{};if(!jf(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const n=$f(e.topicIds),r=Wf(e.topics),i=[...n.invalidMessages,...r.invalidMessages];let o=n.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||r.values.length?{...o.length?{topicIds:o}:{},...r.values.length?{topics:r.values}:{}}:void 0;return s||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:s}}function Kf(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function Yf(e){try{if(Kf(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function te(e){throw{code:"INVALID_PARAMS",message:e}}function tn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Si(e,t){return typeof e!="string"||!e.trim()?te(t):e}function Qf(e,t){const n=Si(e,t);try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?te(t):n}catch{return te(t)}}function Xf(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Za(e,t,n){const r=e.identity.get(),i=r?.miniProgramId.trim();if(!i)return te(`${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=r?.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),n!==void 0&&s.searchParams.set("extra",n),s.href}catch{return te(`${t} 缺少有效的小程序分享地址`)}}function Jf(e,t){if(!tn(e))return te("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return te("share.showShareMenu 不支持自定义 url");const n=e.channel;if(n!==void 0&&!Xf(n))return te("share.showShareMenu channel 不合法");const r=ec(e.extra,"share.showShareMenu");return{title:Si(e.title,"share.showShareMenu title 必须是非空字符串"),description:Si(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Za(t,"share.showShareMenu",r),...e.imageUrl===void 0?{}:{imageUrl:Qf(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...n===void 0?{}:{channel:n}}}function ec(e,t){if(e!==void 0)try{return ja(e)}catch{return te(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function tc(e,t){return e.invalidMessage&&await z(()=>Yf(t.environment),t.operationContext.signal)?te(e.invalidMessage):e.post}function Jo(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?n:t}function Zf(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Jo(t.windowWidth,0),height:Jo(t.windowHeight,0)}}function vi(e,t){const n=Number(e);return!Number.isFinite(n)||n<0?te(t):n}function Zo(e,t){const n=Number(e);return!Number.isFinite(n)||n<=0?te(t):n}function eh(e){return tn(e)?{left:vi(e.left,"share.screenshot rect.left 必须是非负数字"),top:vi(e.top,"share.screenshot rect.top 必须是非负数字"),width:Zo(e.width,"share.screenshot rect.width 必须是正数"),height:Zo(e.height,"share.screenshot rect.height 必须是正数")}:te("share.screenshot rect 必须是对象")}function th(e,t){if(e!=null&&!tn(e))return te("share.screenshot 参数必须是对象");const n=e??{};return n.saveToAlbum!==void 0&&typeof n.saveToAlbum!="boolean"?te("share.screenshot saveToAlbum 必须是布尔值"):{rect:n.rect===void 0?Zf(t):eh(n.rect),...n.delay===void 0?{}:{delay:vi(n.delay,"share.screenshot delay 必须是非负数字")},...n.saveToAlbum===void 0?{}:{saveToAlbum:n.saveToAlbum}}}async function nh(e,t){$(t.operationContext.signal);const n=Jf(e,t);let r=Ja(e.post,{maxTopicIds:1,method:"share.showShareMenu"});n.channel&&r.post&&(r={invalidMessage:r.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await tc(r,t);return z(()=>t.presentation.showShareMenu({...n,post:i},t.operationContext),t.operationContext.signal)}async function rh(e,t){if($(t.operationContext.signal),e!==void 0&&!tn(e))return te("share.copyLink 参数必须是对象");const n=ec(e?.extra,"share.copyLink"),r=Za(t,"share.copyLink",n);return await z(()=>t.presentation.setClipboard({text:r},t.operationContext),t.operationContext.signal),r}async function ih(e,t){$(t.operationContext.signal);const n=th(e,t.presentation),r=Ja(tn(e)?e.post:void 0,{method:"share.screenshot"}),i=await tc(r,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=oh();let a=!1,c;try{a=!0,await z(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),c={status:"fulfilled",value:await z(()=>t.presentation.captureAndShare({...n,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(u){c={status:"rejected",error:u}}const d=a?await sh(t.presentation,s,t.operationContext.signal):void 0;if(c.status==="rejected")throw c.error;if(d)throw d;return c.value}function oh(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function sh(e,t,n){let r;try{r=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await z(()=>r,n,{invokeWhenAborted:!0})}catch(i){if(n.aborted)return i}}function ah(e){return{[Tn]:(t,n)=>rh(t,e),[Ln]:(t,n)=>nh(t,e),[kn]:(t,n)=>ih(t,e)}}const ch=128,dh=/^[A-Za-z0-9_-]+$/;function uh(e){const t=lh(e),n={[xt]:async r=>{$(e.operationContext.signal);const i=es(r,xt,e.storageLimits?.maxKeyLength),o=await z(()=>e.storage.getRaw(Br(t(),i),e.operationContext),e.operationContext.signal);return{data:ts(o)}},[Ht]:async r=>{$(e.operationContext.signal);const i=nc(r,"storage.setStorage 参数必须是对象"),o=es(i,Ht,e.storageLimits?.maxKeyLength),s=fh(i.data,e.storageLimits?.maxValueBytes);await z(()=>e.storage.setRaw(Br(t(),o),s,e.operationContext),e.operationContext.signal)}};return e.storageDiagnostics?{handlers:n,diagnostics:{getSnapshot:async()=>{$(e.operationContext.signal);let r;try{r=t()}catch{throw Be("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const i=Br(r,"");return(await z(()=>e.storageDiagnostics.listRaw(e.operationContext),e.operationContext.signal)).filter(s=>s.key.startsWith(i)).map(s=>{const a=s.value;return{area:s.area,key:s.key.slice(i.length),value:ts(a),serializedValue:a,bytes:rc(a)}}).sort((s,a)=>s.key.localeCompare(a.key))}}}:{handlers:n}}function lh(e){let t=!1,n;return()=>{if(!t){const r=e.identity.get()?.miniProgramId.trim();if(r)n=`id_${ns(r)}`;else{const i=e.anonymousStorageScope?.trim();i&&(n=`anon_${ns(i)}`)}t=n!==void 0}if(!n)throw Be("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return n}}function Br(e,t){return`hb_miniprogram_${e}_${t}`}function es(e,t,n=ch){const i=nc(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Be("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>n||!dh.test(i))throw Be("INVALID_PARAMS",`storage key 仅支持 1-${n} 位字母、数字、下划线和连字符`);return i}function fh(e,t){let n;try{n=JSON.stringify(e)}catch{throw Be("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof n!="string")throw Be("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&rc(n)>t)throw Be("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return n}function ts(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function nc(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Be("INVALID_PARAMS",t);return e}function ns(e){return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:hh(e)}function hh(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function rc(e){return new TextEncoder().encode(e).length}function Be(e,t){return{code:e,message:t}}const rs=120;function Me(e){throw{code:"INVALID_PARAMS",message:e}}function Ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ic(e,t,n){const r=Object.keys(e).filter(i=>!t.includes(i));r.length&&Me(`${n} 不支持字段: ${r.join(", ")}`)}function mh(e){if(!Ji(e))return Me("ui.showToast 参数必须是对象");if(ic(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Me("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>rs)return Me(`ui.showToast message 不能超过 ${rs} 字符`);const n=e.status;if(n!==void 0&&n!=="success"&&n!=="error")return Me("ui.showToast status 必须是 success 或 error");const r=n;return{message:t,...r===void 0?{}:{status:r}}}function ph(e){return e===void 0?{dismissible:!1}:Ji(e)?(ic(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Me("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Me("ui.showLoading 参数必须是对象")}function gh(e){e!==void 0&&(!Ji(e)||Object.keys(e).length)&&Me("ui.hideLoading 不支持参数")}function Eh(e){return{[Kn]:async t=>{$(e.operationContext.signal),await z(()=>e.presentation.showToast(mh(t),e.operationContext),e.operationContext.signal)},[Yn]:async t=>{$(e.operationContext.signal),await z(()=>e.presentation.showLoading(ph(t),e.operationContext),e.operationContext.signal)},[Qn]:async t=>{$(e.operationContext.signal),gh(t),await z(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const yh={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return de(e,"当前用户首页资料接口响应异常")}},wh=3e4;function Ih(e,t,n={}){const r=n.ttlMs??wh;let i=0,o,s;async function a(){let d;try{d=await Ar(e,yh,void 0,{...t,credentials:"heybox-session"})}catch(u){throw t.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):u instanceof J?l("REQUEST_UNSUPPORTED",u.message):u instanceof Zt?l("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof yt?l("REQUEST_FAILED","user home_v2 请求失败"):u instanceof Et?l("REQUEST_FAILED",u.message):_h(u)?u:l("REQUEST_FAILED","user home_v2 请求失败")}return Ah(d,"user home_v2")}function c(d){const u=Date.now();if(o?.userId===d&&o.expiresAt>u)return Promise.resolve(o.value);if(s?.userId===d&&s.generation===i)return s.promise;const m=i,h=a().then(f=>(i===m&&(o={userId:d,value:f,expiresAt:Date.now()+r}),f)).finally(()=>{s?.promise===h&&(s=void 0)});return s={userId:d,generation:m,promise:h},h}return{get:c,clear(){i+=1,o=void 0,s=void 0}}}function Ah(e,t){if(!M(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const n=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,r=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(r,n)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function _h(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}const bh={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.game.steam.get_game_list.get",method:"GET",path:"/game/steam/get_game_list",query(e){return{userid:e.userId,...e.steamId?{steam_id:e.steamId}:{},limit:e.limit,offset:e.offset,sort:e.sort,need_hidden:e.includeHidden,...e.personalInformationOpen===void 0?{}:{personal_infomation_open:e.personalInformationOpen},...e.q?{q:e.q}:{}}},parse(e,t){return de(e,"Steam 游戏库接口响应异常")}},oc=20,Sh=100,sc=0,ac="weeks",vh=100,Oh=new Set(["weeks","all","achieved"]);function Dh(e){const t=Ih(e.network,e.operationContext),n=new Map;let r=0,i=!1;const o=e.account.onChange(()=>{r+=1,t.clear(),n.clear()}),s=e.authorization.onEvent((E,w)=>{E==="user_info_authorization_change"&&"identity"in w&&w.identity==="denied"&&(r+=1,t.clear(),n.clear())});function a(){if(i||e.operationContext.signal.aborted)throw l("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function c(){const E=e.identity.get()?.miniProgramId?.trim();if(!E)throw l("INVALID_STATE","用户能力缺少 canonical 小程序身份");return E}async function d(){a();let E;try{E=await e.account.getCurrentUserId(e.operationContext)}catch(w){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):os(w)?w:l("REQUEST_FAILED","读取小黑盒账号失败")}return typeof E=="string"&&E.trim()?E.trim():void 0}async function u(E,w){const p=await d();if(r!==w||p!==E)throw l("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function m(E,w){try{return await Ar(e.network,E,w,{...e.operationContext,credentials:"heybox-session"})}catch(p){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):p instanceof J?l("REQUEST_UNSUPPORTED",p.message):p instanceof Zt?l("INVALID_RESPONSE","用户接口响应不合法"):p instanceof yt?l("REQUEST_FAILED","用户请求失败"):p instanceof Et?l("REQUEST_FAILED",p.message):os(p)?p:l("REQUEST_FAILED","用户请求失败")}}async function h(){c();const E=r,w=await d();if(!w)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[p,_]=await Promise.all([e.authorization.getOrCreateLocalIdentity(w),f(w)]);return await u(w,E),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:p.appUserId,profile:_,...p.steamId?{steam_id:p.steamId}:{}}}}function f(E){const w=n.get(E);if(w)return w;const p=m(Sa,void 0).then(_=>{const A=is(_,"账号基础信息");if(A.display_username!==void 0&&typeof A.display_username!="string")throw l("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(A.display_avatar!==void 0&&typeof A.display_avatar!="string")throw l("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:A.display_username??"",avatar:A.display_avatar??""}}).catch(()=>({nickname:"",avatar:""})).finally(()=>{n.get(E)===p&&n.delete(E)});return n.set(E,p),p}async function I(E){const w=Ph(E);c();const p=r,_=await d();if(!_)return{isLogin:!1,isBound:!1,data:null};const A=await t.get(_);await u(_,p);const v=Zi(A.steam_id_info);if(Object.keys(v).length===0)return{isLogin:!0,isBound:!1,data:null};const x=await m(bh,{userId:_,...w,personalInformationOpen:cc(v.personal_infomation_open??v.personal_information_open)});await u(_,p);const S=is(x,"Steam 游戏库");return{isLogin:!0,isBound:!0,data:Lh(S,w)}}return{getInfo:h,getSteamGameList:I,dispose(){i||(i=!0,r+=1,o(),s(),t.clear(),n.clear())}}}function Ph(e){if(e==null)return{limit:oc,offset:sc,sort:ac,includeHidden:!1};if(!M(e))throw Ue("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(r=>!["steamId","limit","offset","sort","q","includeHidden"].includes(r));if(t)throw Ue(`user.getSteamGameList 不支持字段: ${t}`);const n={limit:Rh(e.limit),offset:Nh(e.offset),sort:Ch(e.sort),includeHidden:Th(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim())throw Ue("user.getSteamGameList steamId 必须是非空字符串");n.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ue("user.getSteamGameList q 必须是字符串");const r=e.q.trim();r&&(n.q=r.slice(0,vh))}return n}function Rh(e){if(e===void 0)return oc;if(!Number.isInteger(e)||Number(e)<1)throw Ue("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Sh)}function Nh(e){if(e===void 0)return sc;if(!Number.isInteger(e)||Number(e)<0)throw Ue("user.getSteamGameList offset 必须是非负整数");return Number(e)}function Ch(e){if(e===void 0)return ac;if(typeof e!="string"||!Oh.has(e))throw Ue("user.getSteamGameList sort 不支持");return e}function Th(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ue("user.getSteamGameList includeHidden 必须是 boolean");return e}function Lh(e,t){if(!Array.isArray(e.game_list))throw l("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const n=e.game_list.map(kh).filter(a=>a!==void 0),r=or(e.total),i=t.offset+n.length,o={gameList:n,hasMore:n.length>=t.limit,nextOffset:i};r!==void 0&&(o.total=r,o.hasMore=i<r);const s=cc(e.is_me);return s!==void 0&&(o.isMe=s),o}function kh(e){const t=Zi(e),n=or(t.appid),r=or(t.steam_appid)??n,i=eo(t.name);if(n===void 0||r===void 0||!i)return;const o={appid:n,steamAppid:r,name:i};Tt(o,"image",t.image),Tt(o,"icon",t.appicon??t.icon),Lt(o,"playtimeForever",t.playtime_forever),Lt(o,"playtime2Weeks",t.playtime_2weeks);const s=Uh(t.external_tags??t.tags);s.length&&(o.tags=s);const a=Mh(t.price);return a&&(o.price=a),o}function Mh(e){const t=Zi(e),n={};return Tt(n,"current",t.current),Tt(n,"initial",t.initial),Lt(n,"discount",t.discount),Lt(n,"lowestPrice",t.lowest_price),Tt(n,"deadlineDate",t.deadline_date),Lt(n,"deadlineTimestamp",t.deadline_timestamp),Object.keys(n).length?n:void 0}function is(e,t){if(!M(e))throw l("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const n=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,r=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw l(r,n)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Zi(e){return M(e)?e:{}}function eo(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Uh(e){return Array.isArray(e)?e.map(eo).filter(Boolean):[]}function or(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function cc(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function Tt(e,t,n){const r=eo(n);r&&Object.assign(e,{[t]:r})}function Lt(e,t,n){const r=or(n);r!==void 0&&Object.assign(e,{[t]:r})}function Ue(e){return l("INVALID_PARAMS",e)}function os(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function xh(e){const t=e.userDataMode??su(e.runtimePermissions,e.steamAccount===!0);return{[Rn]:async n=>(ss(n,"user.getInfo"),wo(t,"user.getInfo"),e.user.getInfo()),[Nn]:async(n,r)=>{ss(n,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Cn]:async n=>(wo(t,"user.getSteamGameList"),e.user.getSteamGameList(n))}}function ss(e,t){if(e!==void 0)throw l("INVALID_PARAMS",`${t} 不接收入参`)}const Hh="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K";function Fh(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute("aria-label","退出全屏"),t.style.cssText=["position:fixed","right:0","top:50%","z-index:2147483647","box-sizing:border-box","width:48px","height:44px","padding:5px 4px","border:0","border-radius:5px","display:flex","flex-direction:column","align-items:center","justify-content:center","gap:3px","background:rgba(57,61,64,.9)","color:#fff",'font:400 9px/12px "PingFang SC",sans-serif',"cursor:pointer","touch-action:manipulation","opacity:1","transform:translateY(-50%)","transition:opacity .2s,transform .2s"].join(";");const n=document.createElement("img");n.src=Hh,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const r=document.createElement("span");r.textContent="退出全屏",r.style.whiteSpace="nowrap",t.append(n,r);let i=!0,o=!1,s=!1,a;function c(){clearTimeout(a),a=setTimeout(()=>{i=!1,t.style.opacity="0.18",t.style.transform="translate(38px, -50%)",t.setAttribute("aria-label","展开退出全屏按钮")},1e3)}function d(){i=!0,t.style.opacity="1",t.style.transform="translateY(-50%)",t.setAttribute("aria-label","退出全屏"),c()}async function u(){if(!(o||s)){if(!i){d();return}s=!0,clearTimeout(a);try{await e()}catch{}finally{s=!1,o||d()}}}return t.addEventListener("click",u),document.body.append(t),c(),{dispose(){o=!0,clearTimeout(a),t.removeEventListener("click",u),t.remove()}}}const dc=1e4;function Bh(e){const t=new AbortController;let n;const r=()=>{n??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},t.abort()};e.addEventListener("abort",r,{once:!0}),e.aborted&&r();const i=setTimeout(()=>{n??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},t.abort()},dc);return{signal:t.signal,async run(o){try{return await z(o,t.signal)}catch(s){throw n??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",r)}}}function uc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 参数必须是对象"};const{orientation:t,fullscreen:n}=e;if(t!==void 0&&t!=="portrait"&&t!=="landscape")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay orientation 必须是 portrait 或 landscape"};if(n!==void 0&&typeof n!="boolean")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay fullscreen 必须是布尔值"};if(t===void 0&&n===void 0)throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 至少设置 orientation 或 fullscreen"};return{orientation:t,fullscreen:n}}function Vr(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function fn(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function Vh(e){let t,n,r={mode:"portrait",hideCapsule:!1},i={mode:"portrait",hideCapsule:!1},o;function s(){o?.dispose(),o=void 0}function a(h){if(!h.hideCapsule){s();return}o??=Fh(()=>m.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(h,f){if(t===h){if(t=void 0,clearTimeout(h.timer),e.operationContext.signal.removeEventListener("abort",d),"error"in f)h.controller.abort();else if(n={options:h.options,result:f.result},r=h.options,a(h.options),e.onApplied?.(h.options),f.result.supported&&!Vr(i,h.options)){i={...h.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:h.source})}catch{}}for(const I of h.subscribers)I.dispose(),"error"in f?I.reject(f.error):I.resolve(f.result);h.subscribers.clear()}}function d(){t&&c(t,{error:fn()})}function u(h,f){return new Promise((I,E)=>{const w=()=>{h.subscribers.delete(p),p.dispose(),E(fn()),h.subscribers.size===0&&c(h,{error:fn()})},p={resolve:I,reject:E,dispose:()=>f?.removeEventListener("abort",w)};h.subscribers.add(p),f?.addEventListener("abort",w,{once:!0}),f?.aborted&&w()})}const m={async apply(h,f,I="api"){if($(e.operationContext.signal),f?.aborted)throw fn();const E=uc(h),w=t?.options??r,p={mode:E.orientation??w.mode,hideCapsule:E.fullscreen??w.hideCapsule};p.mode==="landscape"&&(p.hideCapsule=!0);const _=e.presentation.applyOrientation;if(!_)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&Vr(t.options,p))return u(t,f);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),n&&Vr(n.options,p))return n.result;n=void 0;const A={options:p,source:I,controller:new AbortController,subscribers:new Set};t=A;const v=u(A,f);return e.operationContext.signal.addEventListener("abort",d,{once:!0}),f||(A.timer=setTimeout(()=>{c(A,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},dc)),z(()=>_.call(e.presentation,p,{...e.operationContext,signal:A.controller.signal}),A.controller.signal).then(x=>c(A,{result:x??{supported:!0}}),x=>c(A,{error:x})),v},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return m}function as(e){throw{code:"INVALID_PARAMS",message:e}}function vt(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?n:t}function lc(e,t){const n=Number(e);return Number.isFinite(n)&&n>=0?n:t}function hn(e,t,n){return Math.min(lc(e,t),n)}async function qh(e){try{return lc(await e.getNavigationBarHeight(),0)}catch{return 0}}function zh(e,t,n,r){const i=hn(e.safeArea?.left,0,t),o=Math.max(i,hn(e.safeArea?.right,t,t)),s=hn(e.safeArea?.top,r,n),a=Math.max(s,hn(e.safeArea?.bottom,n,n));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function cs(e){const t=e.getViewportMetrics(),n=vt(t.windowWidth,0),r=vt(t.windowHeight,0),i=await qh(e);return{pixelRatio:vt(t.pixelRatio,1),screenWidth:vt(t.screenWidth,n),screenHeight:vt(t.screenHeight,r),windowWidth:n,windowHeight:r,statusBarHeight:i,safeArea:zh(t,n,r,i),screenTop:i}}function jh(e){const t=new AbortController,n={...e,operationContext:{...e.operationContext,signal:t.signal}};let r=!1,i=0,o,s;const a=()=>{if(r||n.operationContext.signal.aborted||!n.onViewportChange)return;const m=++i;cs(n.presentation).then(h=>{if(r||n.operationContext.signal.aborted||m!==i)return;const f=JSON.stringify(h);f!==o&&(o=f,n.onViewportChange?.(h))}).catch(()=>{})},c=Vh({...n,onApplied:a}),d=()=>{r||(r=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?d():(s=n.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[Je]:async(m,h)=>c.apply(m,h?.signal),[Mn]:async()=>($(n.operationContext.signal),cs(n.presentation)),[Un]:async m=>{if($(n.operationContext.signal),typeof m!="object"||m===null||Array.isArray(m))return as("viewport.setNavigationBarStyle 参数必须是对象");const h=m.foregroundStyle;if(h!=="light"&&h!=="dark")return as("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await z(()=>n.presentation.setNavigationBarStyle(h,e.operationContext),n.operationContext.signal)}},applyOrientation:(m,h)=>c.apply({orientation:m.mode,fullscreen:m.hideCapsule},h),notifyChange:()=>{o=void 0,a()},dispose:d}}const Gh=new Map(He.map(e=>[e.method,e]));function mn(e,t,n){return{code:e,message:t,...n===void 0?{}:{data:n}}}function $h(e){const t=Ne(e);return n=>{if(n.requirement.kind==="none")return{allowed:!0};for(const r of n.requirement.permissions){const i=t.valid?t.permissions[r]:void 0;if(!i)return{allowed:!1,code:"PERMISSION_NOT_DECLARED",message:`小程序未声明权限: ${r}`,data:{permission:r,method:n.method}};if(i.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${r}`,data:{permission:r,method:n.method}}}return{allowed:!0}}}function Wh(e,t,n,r){let i;try{i=Promise.resolve(e(t,n))}catch(o){return r.aborted?Promise.resolve({status:"dropped"}):Promise.reject(o)}return r.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((o,s)=>{let a=!1;const c=u=>{a||(a=!0,r.removeEventListener("abort",d),u())},d=()=>c(()=>o({status:"dropped"}));r.addEventListener("abort",d,{once:!0}),i.then(u=>c(()=>o({status:"handled",value:u})),u=>c(()=>s(u)))})}function Kh(e){const t=$h(e.runtimePermissions),n=Ne(e.runtimePermissions);let r=0,i=0,o=0;return{async dispatch(s,a,c){const d=e.now??Yh,u=e.onTrace?d():0,m=e.onTrace?`cap_${++r}`:"",h=s===Je?++i:void 0;let f;try{if(e.terminalSignal.aborted)throw mn("RUNTIME_DESTROYED","小程序 Runtime 已终止");vd(s,e.effectiveCapabilities);const I=Gh.get(s);if(!I)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const E=t(I),w=!E.allowed&&n.valid&&n.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!E.allowed&&!w)throw mn(E.code,E.message,E.data);const p=e.handlers[s];if(!p)throw new Error(`Capability method ${s} 缺少 handler`);h!==void 0&&(f=Bh(c.signal));const _=f?{...c,signal:f.signal}:c,A=async()=>{for(const x of e.policies??[]){const S=await x.evaluate({method:s,payload:a,capability:I});if(e.terminalSignal.aborted||f?.signal.aborted)throw ls();if(!S.allowed)throw mn(S.code,S.message,S.data)}if(e.terminalSignal.aborted||f?.signal.aborted)throw ls();if(h!==void 0){if(uc(a),h<o)throw mn("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=h}return p(a,_)},v=await Wh(()=>f?f.run(A):A(),void 0,c,e.terminalSignal);return ds(e.onTrace,us(m,s,a,u,v),d),v}catch(I){throw ds(e.onTrace,us(m,s,a,u,{status:"error",error:I}),d),I}finally{f?.dispose()}}}}function Yh(){return typeof performance>"u"?Date.now():performance.now()}function ds(e,t,n){if(!e)return;const r=n();try{e({...t,timestamp:r,durationMs:Math.max(0,Number.isFinite(r-t.startedAt)?r-t.startedAt:0)})}catch{}}function us(e,t,n,r,i){const o=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:r,outcome:o,...i.status==="error"?{errorCode:Qh(i.error)}:{},...Xh(t,n,i)}}function Qh(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function Xh(e,t,n){if(e!=="network.request"||typeof t!="object"||t===null||!("url"in t)||typeof t.url!="string")return{};try{const r=new URL(t.url);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.username||r.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=n.status==="handled"&&fc(n.value)&&typeof n.value.status=="number"?n.value.status:void 0;return{network:{method:o,origin:r.origin,pathname:r.pathname,...s===void 0?{}:{responseStatus:s}}}}catch{return{}}}function fc(e){return typeof e=="object"&&e!==null}function ls(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Jh(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},n=new ll(e.files,e.miniProgramDetail),r=wl({registry:n,picker:e.picker,operationContext:t}),i=gu({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});let o,s,a,c=()=>{},d=()=>{};try{o=jh({operationContext:t,presentation:e.hostPresentation,onDisplayChange:p=>e.eventSink.postEvent("display_change",p),onViewportChange:p=>e.eventSink.postEvent("viewport_change",p)}),s=Dh({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:i}),c=i.onEvent((p,_)=>e.eventSink.postEvent(p,_)),d=e.hostCompanion?.onSessionEvent?.(p=>{const _=ol(p);!e.terminalSignal.aborted&&_&&e.eventSink.postEvent(_.type,_.payload)})??(()=>{}),a=ju({account:e.account,identity:e.identity,network:e.network,operationContext:t});const u=uh({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),m=[{name:"auth",handlers:Su({authorization:i})},{name:"user",handlers:xh({user:s,authorization:i,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:ah({environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:o.handlers},{name:"storage",handlers:u.handlers},{name:"network",handlers:vf({network:e.network,transfer:e.transfer,fileRegistry:n,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"files",handlers:r.files},{name:"file",handlers:r.file},{name:"directory",handlers:r.directory},{name:"ui",handlers:Eh({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:cl({operationContext:t,presentation:e.hostPresentation})},{name:"navigation",handlers:jl({operationContext:t,presentation:e.hostPresentation})},{name:"cloud",handlers:a.handlers},{name:"companion",handlers:el({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:n})}],h=Zh(m);let f=!1;const I=()=>{f||(f=!0,e.terminalSignal.removeEventListener("abort",I),o?.dispose(),a?.dispose(),c(),d(),s?.dispose(),i.dispose(),n.dispose())};e.terminalSignal.aborted?I():e.terminalSignal.addEventListener("abort",I,{once:!0});const E=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:m,handlers:h,allowsCompanionAttachmentAccess:(p,_)=>E.has(p)&&fc(_)&&n.isCompanionAttachmentRef(_.target),applyOrientation:o.applyOrientation,notifyViewportChange:o.notifyChange,...u.diagnostics?{storageDiagnostics:u.diagnostics}:{},dispose:I}}catch(u){throw o?.dispose(),a?.dispose(),c(),d(),s?.dispose(),i.dispose(),n.dispose(),u}}function Zh(e){const t=new Map(He.map(i=>[i.method,i.module])),n=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(n.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);n.set(a,s)}const r=He.map(i=>i.method).filter(i=>!n.has(i));if(r.length>0)throw new Error(`Capability registry 缺少 method: ${r.join(", ")}`);if(n.size!==He.length)throw new Error(`Capability registry method 数量不合法: ${n.size}`);return Object.freeze(Object.fromEntries(n))}const em="heybox-mini-dev:";function fs(e){try{return tm(new URL(e))}catch{return!1}}function tm(e){return e.protocol===em}function nm(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||rm(e)}function rm(e){const t=e.split(".");if(t.length!==4)return!1;const n=t.map(r=>/^\d+$/.test(r)?Number(r):Number.NaN);return n.some(r=>!Number.isInteger(r)||r<0||r>255)?!1:n[0]===10||n[0]===172&&n[1]>=16&&n[1]<=31||n[0]===192&&n[1]===168}const im=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function om(e,t){const n=[],r=sm(e.environmentInfo,n),i=An(r?.appVersion,"host.appVersion",n),o=cm(r?.operatingSystem,n);return{info:Object.freeze({runtime:Object.freeze({mode:am(e.sdkVersionPolicy?.releaseChannel,n)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:An(t.miniProgramId),version:An(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(n)}}function sm(e,t){if(e!=null){if(hc(e))return e;t.push("environmentInfo")}}function am(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function cm(e,t){if(e==null)return{name:"unknown",version:null};if(!hc(e))return t.push("operatingSystem"),{name:"unknown",version:null};const n=im.has(e.name)?e.name:"unknown";return n==="unknown"&&e.name!==void 0&&e.name!==null&&e.name!=="unknown"&&t.push("operatingSystem.name"),{name:n,version:An(e.version,"operatingSystem.version",t)}}function An(e,t,n){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&n&&n.push(t),null)}function hc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const dm=1,mc="allow-scripts allow-same-origin",um="",lm="no-referrer";function fm(e=mc){return!e.split(/\s+/).includes("allow-same-origin")}function hs(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const hm=new Set(["javascript:","data:","blob:","file:"]),ms="xiaoheihe.cn";function mm(e,t=window.location.href,n={}){const r=e.trim();if(!r)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(r)}catch{throw new Error("小程序链接必须是绝对 URL")}if(hm.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!wm(i,t,n))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function pm(e,t){const n=new URL(e);return n.searchParams.set(nd,t),n.toString()}function gm(e,t,n){try{const r=new URL(e),i=new URL(t);if(r.origin!==i.origin)return!1;const o=Em(n)??ym(r.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Em(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function ym(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const n=e.lastIndexOf("/");return n>=0?e.slice(0,n+1):"/"}function ps(e){const t=new URL(e);return to(t)?"loopback":no(t)?"lan":"production"}function wm(e,t,n){return Im(e)||to(e)||no(e)&&_m(t,n)}function Im(e){return e.protocol==="https:"&&vm(e.hostname)}function to(e){return e.protocol==="http:"&&Am(e.hostname)}function Am(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function no(e){return e.protocol==="http:"&&bm(e.hostname)}function _m(e,t){if(t.allowPrivateNetwork)return!0;try{const n=new URL(e);return to(n)||no(n)}catch{return!1}}function bm(e){const t=Sm(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Sm(e){const t=e.split(".");if(t.length!==4)return;const n=t.map(r=>{if(!/^\d+$/.test(r))return;const i=Number(r);return Number.isInteger(i)&&i>=0&&i<=255?i:void 0});return n.every(r=>r!==void 0)?n:void 0}function vm(e){return e===ms||e.endsWith(`.${ms}`)}const Om=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"]),Dm=new Set(["url","inline","eval","unknown"]),Pm=/^\/(?:\:segment(?:\/\:segment)*)?$/,Rm=/^[a-f0-9]{64}$/,Nm=255,Cm=160,Tm=256;function Lm(e,t){const n=e;if(!n||typeof n.sdkVersion!="string"||n.sdkVersion!==t||typeof n.effectiveDirective!="string"||!Om.has(n.effectiveDirective)||typeof n.violatedDirective!="string"||n.violatedDirective.length>Tm||n.violatedDirective.split(/\s/,1)[0]!==n.effectiveDirective||!["enforce","report"].includes(n.disposition??"")||typeof n.blockedResourceType!="string"||!Dm.has(n.blockedResourceType)||typeof n.timestamp!="number"||!Number.isFinite(n.timestamp)||n.timestamp<0)return;const r=km(n.blockedOrigin);if(n.blockedOrigin!==void 0&&!r)return;const i=n.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>Cm||!Pm.test(i)))return;const o=n.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Rm.test(o)||i===void 0)))return{effectiveDirective:n.effectiveDirective,violatedDirective:n.effectiveDirective,blockedResourceType:n.blockedResourceType,origin:r,sanitizedPathname:i,sanitizedPathnameHash:o,sdkVersion:n.sdkVersion,timestamp:n.timestamp}}function km(e){if(e!==void 0&&!(typeof e!="string"||e.length>Nm))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Mm=/^(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 Um(e){if(!e?.minimumSdkVersion)throw F("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=We(e.minimumSdkVersion),n=e.sdkVersion?We(e.sdkVersion):void 0;if(!t)throw F("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!n)throw F("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const r=We("0.6.0");if(!n){if(_n(t,r)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw F("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&n.prerelease.length>0)throw F("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(_n(n,t)<0)throw F("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:_n(n,We("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function xm(e,t){if(typeof t!="string"||!We(t))throw F("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw F("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function Hm(e,t){const n=We(e),r=We(t);if(!(!n||!r))return _n(n,r)}function We(e){const t=Mm.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(n=>/^\d+$/.test(n)?Number(n):n)??[]}}function _n(e,t){for(const r of["major","minor","patch"])if(e[r]!==t[r])return e[r]<t[r]?-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 n=Math.max(e.prerelease.length,t.prerelease.length);for(let r=0;r<n;r+=1){const i=e.prerelease[r],o=t.prerelease[r];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const Sr=["android","ios","ohos","windows","macos","linux"],Fm="0.9.0",Bm=Object.freeze(["android","ios","ohos","windows","macos"]),pc="该小程序暂不支持当前平台",Vm="PLATFORM_UNSUPPORTED";function qm(e){return typeof e=="string"&&Sr.includes(e)}function zm(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 jm(e){const t=e.manifest;if(!Ym(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const r=Es(e.sdkVersion)??Es(t.sdkVersion);return Wm(r)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:$m()}const n=gc(t.platforms);return"reason"in n?{status:"invalid",reason:n.reason}:{status:"resolved",declaredPlatforms:n.platforms,effectivePlatforms:n.platforms,platformsDeclared:!0,policy:"explicit"}}function Gm(e){const t=zm(e.operatingSystemName);if(!t)return lt("host_operating_system_unknown");const n=e.platformAccess;if(!n)return lt("platform_access_missing",{platform:t});if(n.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Sr,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:n.reason};if(n.source==="manifest"){const s=jm({manifest:n.manifest,...n.sdkVersion===void 0?{}:{sdkVersion:n.sdkVersion}});return s.status==="invalid"?lt("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):gs(t,s)}if(n.effectivePlatforms===void 0)return lt("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const r=gc(n.effectivePlatforms);if("reason"in r)return lt("platform_declaration_invalid",{invalidReason:r.reason,platform:t});const i=typeof n.platformsDeclared=="boolean"?n.platformsDeclared:!0,o=Km(n.platformPolicy)?n.platformPolicy:i?"explicit":"legacy_mobile_default";return gs(t,{declaredPlatforms:i?r.platforms:[],effectivePlatforms:r.platforms,platformsDeclared:i,policy:o})}function gs(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:lt("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function lt(e,t={}){return{status:"denied",reason:e,message:pc,...t}}function $m(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:Bm,platformsDeclared:!1,policy:"legacy_mobile_default"}}function gc(e){if(!Array.isArray(e))return{reason:"platforms_not_array"};if(e.length===0)return{reason:"platforms_empty"};const t=new Set;for(const n of e){if(!qm(n))return{reason:"platform_unknown_value"};if(t.has(n))return{reason:"platform_duplicate_value"};t.add(n)}return{platforms:Object.freeze(Sr.filter(n=>t.has(n)))}}function Wm(e){if(typeof e!="string"||!e.trim())return!1;const t=Hm(e.trim(),Fm);return t!==void 0&&t>=0}function Es(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Km(e){return e==="explicit"||e==="legacy_mobile_default"}function Ym(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Qm=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Xm(e,t,n){const r=Date.now();try{const i=new URL(t);return{type:"security_violation",errorCode:e,timestamp:r,sdkVersion:n,origin:i.origin,sanitizedPathname:Jm(i.pathname),sanitizedPathnameHash:Zm(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:r,sdkVersion:n}}}function Jm(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(n=>n?":segment":"").join("/")}function Zm(e){const t=new TextEncoder().encode(e),n=Math.ceil((t.length+9)/64)*64,r=new Uint8Array(n);r.set(t),r[t.length]=128,new DataView(r.buffer).setUint32(n-4,t.length*8,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64),s=new DataView(r.buffer);for(let a=0;a<n;a+=64){for(let w=0;w<16;w+=1)o[w]=s.getUint32(a+w*4,!1);for(let w=16;w<64;w+=1){const p=o[w-15],_=o[w-2],A=ye(p,7)^ye(p,18)^p>>>3,v=ye(_,17)^ye(_,19)^_>>>10;o[w]=o[w-16]+A+o[w-7]+v>>>0}let[c,d,u,m,h,f,I,E]=i;for(let w=0;w<64;w+=1){const p=E+(ye(h,6)^ye(h,11)^ye(h,25))+(h&f^~h&I)+Qm[w]+o[w]>>>0,_=(ye(c,2)^ye(c,13)^ye(c,22))+(c&d^c&u^d&u);E=I,I=f,f=h,h=m+p>>>0,m=u,u=d,d=c,c=p+_>>>0}[c,d,u,m,h,f,I,E].forEach((w,p)=>{i[p]=i[p]+w>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ye(e,t){return e>>>t|e<<32-t}const ep=1e4,qr=2e3,tp=2,np="open-with-native-credential-policy",Ec="安全提示",yc="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class rp{nonce=hs();runtimeId=hs();terminalController=new AbortController;options;handshakeTimeout;ports;primitiveAvailability;effectiveCapabilities;identity;identityRef;iframe;iframeErrorListener;iframeLoadListener;bridgeServer=null;miniProgramSrc="";launchUrl="";startPromise=null;readyContext=null;resolveReady;rejectReady;terminalError;status="idle";stateValue="idle";handshakeTimeoutTimer;lifecycleDisposer;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;sdkVersionDecision;platformGateDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;unexpectedDocumentLoadTimer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const n=ba(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities});this.ports=n.ports,this.primitiveAvailability=n.primitiveAvailability,this.effectiveCapabilities=n.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const r=this.identity.miniProgramId?.trim();if(r)return{miniProgramId:r,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??ep,this.iframeErrorListener=r=>{this.onIframeError(r)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics;return t?{storage:t}:{}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??F("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??F("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(fp(),this.startPromise=this.createReadyPromise(),this.setState("starting"),this.setStatus("starting"),this.launch().catch(t=>{this.failRuntime(t)}),this.startPromise)}destroy(){if(this.stateValue==="destroyed")return;const t=F("RUNTIME_DESTROYED","小程序运行时已销毁");this.terminalError=t,this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.teardownIframe(),this.rejectReady?.(t)}show(){const t=this.hostVisible;this.hostVisible=!0,this.emitLifecycleEvent("show"),this.capabilityGraph?.notifyViewportChange(),!t&&this.stateValue==="ready"&&this.sdkVersionDecision?.heartbeatEnabled&&(this.documentRevalidationPending?(this.armDocumentRevalidationTimer(this.documentRevalidationGeneration),this.resendDocumentRevalidationProbe()):this.sendLocationProbe())}hide(){this.hostVisible=!1,this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.emitLifecycleEvent("hide")}prepareForHistoryTraversal(){if(this.stateValue!=="ready"||this.bridgeServer?.protocolVersion!==2||!this.sdkVersionDecision?.heartbeatEnabled)return()=>{};const t=this.beginDocumentRevalidation({deferProbe:!0});return this.preparedHistoryTraversalGeneration=t,()=>{this.preparedHistoryTraversalGeneration===t&&this.cancelPreparedHistoryTraversal()}}createReadyPromise(){return new Promise((t,n)=>{this.resolveReady=t,this.rejectReady=n})}async launch(){const t=await this.resolveRuntimeLaunchConfiguration();if(this.isInactive())return;this.runtimePermissions=t.runtimePermissions,this.runtimeFeatures=t.runtimeFeatures,this.miniProgramPresentation=t.miniProgramPresentation,this.locationBasePath=t.locationBasePath,this.anonymousStorageScope=t.anonymousStorageScope??this.options.anonymousStorageScope,this.allowedHttpOrigins=t.allowedHttpOrigins??this.options.allowedHttpOrigins,this.bindCanonicalIdentity(t.canonicalIdentity),this.sdkVersionDecision=Um(t.sdkVersionPolicy);const n=om(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=Gm({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw pp(this.platformGateDecision);if(this.miniProgramDetail=gp(t),this.effectiveCapabilities=_a(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),ap(this.options.onLaunchConfigurationResolved,t,this.sdkVersionDecision),this.isInactive())return;this.applyIframeDefaults(),this.startBridgeServer(),this.installSubscriptions();const r=await this.normalizeLaunchUrl(t.launchUrl);if(this.isInactive())return;const i=await this.confirmDevMiniProgramLaunch(r);if(!this.isInactive()){if(!i){await this.closeAfterDevLaunchCancellation();return}if(this.bridgeServer?.setTargetOrigin(dp(r)),this.launchUrl=r,this.miniProgramSrc=pm(r,this.nonce),this.traceSecurityPolicy(r),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(o){if(this.isInactive())return;const s=zi(o);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:Je,errorCode:s.code,message:`默认展示设置失败,沿用宿主当前布局:${s.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ce(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(r,i)=>{this.stateValue==="ready"&&(r!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(r!=="display_change"||this.effectiveCapabilities[Je])&&this.bridgeServer?.postEvent(r,i)}};this.capabilityGraph=Jh({account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,transfer:this.ports.transfer,storage:this.ports.storage,storageDiagnostics:this.ports.storageDiagnostics,hostPresentation:this.ports.presentation,hostCompanion:this.ports.companion,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins});const n=Kh({handlers:this.capabilityGraph.handlers,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:r,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:u})=>{const m={type:"capability",runtimeId:this.runtimeId,callId:r,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...u?{network:u}:{}};Ce(this.options.onCapabilityTrace,m)}}:{}});this.bridgeServer=new bd({iframe:this.iframe,nonce:this.nonce,dispatcher:n,environmentInfo:this.environmentInfo,onHandshake:r=>this.handleBridgeHandshake(r),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:r=>{this.handleInternalBridgeEvent(r)},onResponsePosted:({method:r,outcome:i,errorCode:o})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:r,outcome:i,...o?{errorCode:o}:{}})}}),this.bridgeServer.start(),this.setStatus("bridge_started"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge_started"})}onIframeError(t=new Error("小程序 iframe 加载失败")){if(this.isInactive())return;const n=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(F("IFRAME_LOAD_ERROR",n,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 sp(t)?t:wc(F("STARTUP_ERROR",t instanceof Error?t.message:"获取小程序启动配置失败"),t)}}bindCanonicalIdentity(t){const n=t?.miniProgramId?.trim();n&&(this.identity.miniProgramId=n);const r=t?.miniProgramVersion?.trim();r&&(this.identity.miniProgramVersion=r)}async normalizeLaunchUrl(t){try{const n=this.options.environment.getCurrentHref();return mm(t,n,{allowPrivateNetwork:fs(n)||ys(n)||await this.isDevRuntime()})}catch(n){throw F("INVALID_LAUNCH_URL",n instanceof Error?n.message:"小程序链接不合法",n)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??lp)({message:yc,title:Ec,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(ps(t)==="production")return!1;const n=this.options.environment.getCurrentHref();return!fs(n)&&!ys(n)}async closeAfterDevLaunchCancellation(){const t=F("LAUNCH_CANCELLED","小程序启动已取消");this.terminalError=t,this.destroyBridgeServer();const n=new AbortController;let r;try{r=Promise.resolve(this.ports.presentation.close({signal:n.signal}))}catch{ws(),r=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 r.catch(()=>ws())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",um),this.iframe.setAttribute("referrerpolicy",lm),this.iframe.setAttribute("sandbox",mc)}removeIframeListeners(){this.iframe.removeEventListener("error",this.iframeErrorListener),this.iframe.removeEventListener("load",this.iframeLoadListener)}installSubscriptions(){if(this.options.lifecycle&&!this.lifecycleDisposer){const t=this.options.lifecycle.subscribe({show:this.show.bind(this),hide:this.hide.bind(this)});this.lifecycleDisposer=typeof t=="function"?t:null}}clearLifecycleDisposer(){const t=[this.lifecycleDisposer];this.lifecycleDisposer=null;for(const n of t)try{n?.()}catch{}}handleBridgeReady(){if(this.isInactive())return;if(this.readyContext){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"});return}this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge",method:"ready"}),this.setState("ready"),this.sdkVersionDecision?.heartbeatEnabled&&this.hostVisible&&this.sendLocationProbe(),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),Ce(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(),Ce(this.options.onReady,t)}handleBridgeHandshake(t){const n=this.sdkVersionDecision?.sdkVersion;if(n)try{xm(n,t?.sdkVersion)}catch(r){return this.failRuntime(r),!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(F("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>=tp)){this.failRuntime(F("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(sn,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},qr),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:sn})}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 n=++this.documentRevalidationGeneration;return this.iframeHiddenForRevalidation||(this.iframeVisibilityBeforeRevalidation=this.iframe.style.visibility,this.iframe.style.visibility="hidden",this.iframeHiddenForRevalidation=!0),this.armDocumentRevalidationTimer(n),t.deferProbe||this.sendDocumentRevalidationProbe(),n}sendDocumentRevalidationProbe(){if(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)return;const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(sn,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:sn})}armDocumentRevalidationTimer(t){this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&(this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(F("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 文档再验证超时")))},qr))}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()},qr))}clearDocumentRevalidation(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1}cancelPreparedHistoryTraversal(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.iframeHiddenForRevalidation&&this.iframe.style.visibility==="hidden"&&(this.iframe.style.visibility=this.iframeVisibilityBeforeRevalidation??""),this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1,this.hostVisible&&this.sdkVersionDecision?.heartbeatEnabled&&this.sendLocationProbe()}handleDuplicateBridgeHandshake(){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"}),this.documentRevalidationPending&&this.resendDocumentRevalidationProbe()}handleInternalBridgeEvent(t){if(t.method===id){this.handleCspViolation(t.payload);return}if(t.method!==rd)return;const n=this.sdkVersionDecision?.sdkVersion;if(!n)return;const r=t.payload;if(!r||r.sdkVersion!==n){this.failRuntime(F("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(r.probeId!==void 0&&r.probeId!==this.pendingProbeId)){if(typeof r.href!="string"||!gm(this.launchUrl,r.href,this.locationBasePath)){typeof r.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",r.href),this.failRuntime(F("URL_OUT_OF_SCOPE","小程序页面地址超出允许范围"));return}r.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 n=Lm(t,this.sdkVersionDecision?.sdkVersion);n&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:n.timestamp,sdkVersion:n.sdkVersion,origin:n.origin,sanitizedPathname:n.sanitizedPathname,sanitizedPathnameHash:n.sanitizedPathnameHash,effectiveDirective:n.effectiveDirective,violatedDirective:n.violatedDirective,blockedResourceType:n.blockedResourceType})}emitSecurityViolation(t){Ce(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,n){const r=Xm(t,n,this.sdkVersionDecision?.sdkVersion);this.emitSecurityViolation(r)}scheduleUnexpectedDocumentLoadFailure(){this.clearUnexpectedDocumentLoadFailure(),this.unexpectedDocumentLoadTimer=setTimeout(()=>{this.unexpectedDocumentLoadTimer=void 0,this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(F("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:dm,launchUrlType:ps(t),networkPolicy:np})}failRuntime(t){const n=ip(t);return this.isInactive()||(this.terminalError=n,this.terminalController.abort(n),this.postBridgeError(n),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:n.code,message:n.message}),this.setState("failed"),this.teardownIframe(n),Ce(this.options.onError,op(n)),this.rejectReady?.(n)),n}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0,this.clearHandshakeTimeout(),this.clearHeartbeat(),this.clearUnexpectedDocumentLoadFailure(),this.clearDocumentRevalidation(),this.destroyBridgeServer(),this.capabilityGraph?.dispose(),this.capabilityGraph=void 0,this.clearLifecycleDisposer(),this.removeIframeListeners();try{this.options.dispose?.()}catch{}}}teardownIframe(t){if(!this.iframeTornDown){this.iframeTornDown=!0;try{this.options.teardownIframe?this.options.teardownIframe(this.iframe,t):this.iframe.remove()}catch{}}}setStatus(t){this.status!==t&&(this.status=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:t}))}setState(t){this.stateValue!==t&&(this.stateValue=t,Ce(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ce(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 ip(e){const t=zi(e);return sr(e)&&"cause"in e&&wc(t,e.cause),t}function wc(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function op(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function sp(e){return sr(e)&&typeof e.code=="string"&&typeof e.message=="string"}function sr(e){return!!e&&typeof e=="object"}function Ce(e,t){try{e?.(t)}catch{}}function ap(e,t,n){try{e?.(t,n)}catch{}}function ys(e){try{const t=new URL(e);return t.protocol==="http:"&&nm(t.hostname)}catch{return!1}}function cp(e){try{return new URL(e).origin}catch{return}}function dp(e){return fm()?"*":cp(e)}function up(e){return`${Ec}
|
|
2
2
|
|
|
3
3
|
${yc}
|
|
4
4
|
|