@heybox/hb-sdk 0.9.1-alpha.8 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +123 -17
- package/README.md +18 -17
- package/dist/cli-chunks/_commonjs-dynamic-modules-DUamuDzp.cjs +7 -0
- package/dist/cli-chunks/browser-RAy8e8cV.cjs +635 -0
- package/dist/cli-chunks/{build-CQkpLf81.cjs → build-DCp9C9V4.cjs} +10 -14
- package/dist/cli-chunks/{context-CqJDNtEi.cjs → context-Bg6C5ow7.cjs} +10 -5
- package/dist/cli-chunks/{create-BRuR2M7y.cjs → create-D5bX2Xvw.cjs} +7 -12
- package/dist/cli-chunks/{dev-KJAFHEg_.cjs → dev-CFjwhG3q.cjs} +195 -82
- package/dist/cli-chunks/{doctor-DhiUViwk.cjs → doctor-CMz_Kf7-.cjs} +9 -13
- package/dist/cli-chunks/{index-9trmrUtW.cjs → index-B_KKGIBN.cjs} +13591 -10542
- package/dist/cli-chunks/{index-rxAV5dza.cjs → index-YnVa6S_p.cjs} +9 -10
- package/dist/cli-chunks/{index.esm-Cv9FlhXy.cjs → index.esm-CgZPnqEA.cjs} +43 -43
- package/dist/cli-chunks/{login-5DEcU9eL.cjs → login-Df_v6jNs.cjs} +13 -12
- package/dist/cli-chunks/{project-vite-CXWFwbEz.cjs → project-vite-By8cnIwP.cjs} +1 -1
- package/dist/cli-chunks/{remote-laUZaGpI.cjs → remote-ClIJz-e2.cjs} +42 -71
- package/dist/cli-chunks/{runtime-gate-DmJhPcNQ.cjs → runtime-gate-DKiyNwX2.cjs} +9 -13
- package/dist/cli-chunks/{runtime-permission-env-Gy2dH17F.cjs → runtime-permission-env-BNQ2fx4w.cjs} +82 -2794
- package/dist/cli-chunks/{skill--mZIZkyn.cjs → skill-Bk-EBSbJ.cjs} +10 -14
- package/dist/cli-chunks/{version-BMp9qmtC.cjs → version-CG_VNZGM.cjs} +1 -1
- package/dist/cli.cjs +11 -16
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-C1g2tadT.js +102 -0
- package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-BU-vzcs0.js → desktop-app-launch-sH2a_jbj.js} +1 -1
- package/dist/devtools/browser-dev-host/assets/{index-BRxbUJVN.css → index-7Cq8iNcD.css} +1 -1
- package/dist/devtools/browser-dev-host/assets/{index-BZBZfB4t.js → index-Bpxbe1lP.js} +4 -4
- package/dist/devtools/browser-dev-host/index.html +3 -3
- package/dist/index.cjs.js +16 -8
- package/dist/index.esm.js +16 -8
- package/dist/miniapp-publish.cjs.js +27 -0
- package/dist/miniapp-publish.esm.js +27 -0
- package/dist/protocol.cjs.js +1 -1
- package/dist/protocol.esm.js +1 -1
- package/dist/vite.cjs.js +36 -1
- package/dist/vite.esm.js +36 -1
- package/docs/runtime-host-migration.md +4 -2
- package/package.json +6 -5
- package/skill/SKILL.md +10 -0
- package/skill/skill.json +5 -5
- package/types/index.d.ts +124 -94
- package/types/miniapp-publish/index.d.ts +3 -0
- package/types/protocol.d.ts +47 -39
- package/types/vite/index.d.ts +1 -0
- package/dist/cli-chunks/browser-YVckob3g.cjs +0 -15
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-COdk-39n.js +0 -102
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import{H as jo,ax as qd,aY as zd,M as Gd,aH as jd,aI as $d,aj as mr,b6 as j,aa as Wd,ak as Ya,aq as Kd,b0 as Yd,am as Qd,d as Jd,aE as Qa,a8 as Xd,at as Ja,r as Zd,az as Xa,o as el,aD as tl,a5 as rl,a_ as nl,aZ as il,c as ol}from"./desktop-app-launch-BU-vzcs0.js";const $r="workspaceCards.requestRefresh",Wr="auth.login",Kr="user.getInfo",Yr="user.revokeAuthorization",Qr="user.getSteamGameList",Jr="share.copyLink",Xr="share.showShareMenu",Zr="share.screenshot",ot="viewport.setDisplay",en="viewport.getWindowInfo",tn="viewport.setNavigationBarStyle",Zt="storage.getStorage",er="storage.setStorage",rn="network.request",nn="network.download",on="network.upload",sn="files.pickFiles",an="files.pickDirectory",cn="files.saveFile",tr="file.create",rr="file.remove",dn="file.exists",nr="file.readText",ln="file.writeText",ir="file.readBytes",un="file.writeBytes",or="file.stat",fn="directory.create",sr="directory.remove",hn="directory.exists",mn="directory.list",pn="ui.showToast",gn="ui.showLoading",yn="ui.hideLoading",En="device.vibrate",wn="device.setClipboard",An="device.executeProtocol",bn="navigation.close",In="navigation.reload",_n="navigation.openAppPage",ke="cloud.leaderboard.submit",Ie="cloud.leaderboard.getList",ze="cloud.leaderboard.getCurrentUserEntry",st="cloud.leaderboard.deleteCurrentUserEntry",De="cloud.leaderboard.getInfo",Tn="companion.getInfo",Cn="companion.getPreparationStatus",Ln="companion.prepare",Mn="companion.cancelPreparation",kn="companion.getActiveSession",Un="companion.launch",xn="companion.session.write",Hn="companion.session.closeStdin",Fn="companion.session.terminate",Bn="companion.session.ackOutput",Vn="companion.openAttachment",qn="companion.showNotification",Ge=[{method:$r,module:"workspaceCards",capability:$r,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:Wr,module:"auth",capability:Wr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Kr,module:"user",capability:Kr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Yr,module:"user",capability:Yr,requirement:{kind:"none"},risk:"high"},{method:Qr,module:"user",capability:Qr,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:Jr,module:"share",capability:Jr,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Xr,module:"share",capability:Xr,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Zr,module:"share",capability:Zr,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:en,module:"viewport",capability:en,requirement:{kind:"none"},risk:"low"},{method:tn,module:"viewport",capability:tn,requirement:{kind:"none"},risk:"low"},{method:ot,module:"viewport",capability:ot,requirement:{kind:"none"},risk:"low"},{method:Zt,module:"storage",capability:Zt,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:er,module:"storage",capability:er,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:rn,module:"network",capability:rn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:nn,module:"network",capability:nn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:on,module:"network",capability:on,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:sn,module:"files",capability:sn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:an,module:"files",capability:an,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:cn,module:"files",capability:cn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:tr,module:"file",capability:tr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:rr,module:"file",capability:rr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:dn,module:"file",capability:dn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:nr,module:"file",capability:nr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ln,module:"file",capability:ln,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ir,module:"file",capability:ir,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:un,module:"file",capability:un,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:or,module:"file",capability:or,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:fn,module:"directory",capability:fn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:sr,module:"directory",capability:sr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:hn,module:"directory",capability:hn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:mn,module:"directory",capability:mn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:pn,module:"ui",capability:pn,requirement:{kind:"none"},risk:"low"},{method:gn,module:"ui",capability:gn,requirement:{kind:"none"},risk:"low"},{method:yn,module:"ui",capability:yn,requirement:{kind:"none"},risk:"low"},{method:En,module:"device",capability:En,requirement:{kind:"none"},risk:"low"},{method:wn,module:"device",capability:wn,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:An,module:"device",capability:An,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:bn,module:"navigation",capability:bn,requirement:{kind:"none"},risk:"medium"},{method:In,module:"navigation",capability:In,requirement:{kind:"none"},risk:"medium"},{method:_n,module:"navigation",capability:_n,requirement:{kind:"none"},risk:"medium"},{method:ke,module:"cloud",capability:ke,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ie,module:"cloud",capability:Ie,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:ze,module:"cloud",capability:ze,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:st,module:"cloud",capability:st,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:De,module:"cloud",capability:De,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},...[Tn,Cn,Ln,Mn,kn,Un,xn,Hn,Fn,Bn,Vn,qn].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],Xe="heybox:miniprogram",Za=2,sl="hb_mini_bridge_nonce",ec="sdk.handshake",br="runtime.location.probe",al="sdk.location.report",cl="sdk.csp.violation",tc="operation.progress",dl="companion.session.output",ll="companion.session.exit",ul="companion.session.ownershipLost";function fl(e){return!Qe(e)||e.namespace!==Xe||e.version!==1&&e.version!==2||!ce(e.nonce)?!1:e.type==="handshake"?ce(e.id)&&e.method===ec&&e.error===void 0&&gl(e.payload):e.type==="request"?ce(e.id)&&ce(e.method)&&e.error===void 0:e.type==="response"?ce(e.id)&&(e.method===void 0||ce(e.method))&&(e.error===void 0||yl(e.error)):e.type==="event"?!ce(e.method)||e.error!==void 0?!1:e.method===tc?e.version===2&&ce(e.id)&&pl(e.payload):e.id===void 0||ce(e.id):e.type==="cancel"?e.version===2&&ce(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function yo(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function rc(e){return Qe(e)?e.kind==="sandbox"?Ue(e,["kind"]):e.kind==="directory"&&ce(e.handleId)&&Ue(e,["kind","handleId"]):!1}function zn(e){return!Qe(e)||e.kind!=="file"?!1:ce(e.handleId)?Ue(e,["kind","handleId"]):rc(e.root)&&yo(e.relativePath)&&Ue(e,["kind","root","relativePath"])}function nc(e){return!Qe(e)||e.kind!=="directory"?!1:ce(e.handleId)?Ue(e,["kind","handleId"]):rc(e.root)&&(e.relativePath==="."||yo(e.relativePath))&&Ue(e,["kind","root","relativePath"])}function ic(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function hl(e){return!Qe(e)||!At(e.loaded)||typeof e.lengthComputable!="boolean"||!Ue(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?At(e.total)&&e.loaded<=e.total:e.total===void 0}function ml(e){return Qe(e)?e.phase==="downloading"?At(e.loaded)&&(e.total===void 0||At(e.total)&&e.loaded<=e.total)&&Ue(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:At(e.processed)&&At(e.total)&&e.processed<=e.total&&Ue(e,["phase","processed","total"]):!1}function pl(e){return hl(e)||ml(e)}function gl(e){return Qe(e)&&ce(e.href)&&typeof e.userAgent=="string"&&ce(e.sdkVersion)}function yl(e){return Qe(e)&&ce(e.code)&&typeof e.message=="string"}function At(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ce(e){return typeof e=="string"&&e.length>0}function Ue(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const ar=["userInfo","steamLibrary","share","storage","cloud_storage","filesystem","clipboard","leaderboard","network","companion","appProtocol","workspaceCards"];new Set(ar);const El=new Set(ar);function wl(e){return El.has(e)}function Je(e){if(!Ir(e)||e.schema_version!==1||!Array.isArray(e.entries))return{valid:!1,permissions:{}};if(e.revision!==void 0&&(typeof e.revision!="number"||!Number.isInteger(e.revision)||e.revision<0))return{valid:!1,permissions:{}};const t=new Set,r={};for(const n of e.entries){if(!Ir(n)||typeof n.key!="string"||!n.key.trim())return{valid:!1,permissions:{}};const i=n.key.trim(),o=i==="network.request"?"network":i;if(t.has(o)||n.status!=="enabled"&&n.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(o),!!wl(o)){if(o==="network"){const s=n.config;if(!Ir(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(n.config!==null&&n.config!==void 0&&(!Ir(n.config)||Object.keys(n.config).length>0))return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{}}}}return{valid:!0,permissions:r}}function Ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Lr=["network","companion","appProtocol"];function oc(e){if(!Ct(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>Lr.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Ct(n,["key","status","config"])||n.status!=="enabled")return{valid:!1};if(typeof n.key!="string"||r.has(n.key))return{valid:!1};if(r.add(n.key),n.key==="network"){if(!Ct(n.config,["useOfficialDomain"])||n.config.useOfficialDomain!==!1)return{valid:!1};t.push({key:"network",status:"enabled",config:{useOfficialDomain:!1}})}else if(n.key==="companion"){if(!Ct(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Ct(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>Lr.indexOf(n.key)-Lr.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Al(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=Je(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of Lr)!r.has(i)||e.declaredPermissions[i]?.enabled!==!0||t.valid&&t.permissions[i]?.status==="enabled"||n.push(i==="network"?{key:i,status:"enabled",config:{useOfficialDomain:!1}}:{key:i,status:"enabled",config:{}});return{schema_version:1,revision:e.revision,entries:n}}function Eo(e){const t=Je(e.runtimePermissions),r=oc(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of ar)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:s==="network"&&n.network&&(n.network.config.useOfficialDomain=n.network.status==="enabled"&&n.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(r.valid)for(const s of r.grant.entries)e.declaredPermissions[s.key]?.enabled!==!0||n[s.key]?.status==="enabled"||(n[s.key]=s,i.push(s.key));const o=sc(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:ar.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function sc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ct(e,t){return sc(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const _t=["identity","profile","steam_account"],bl=/^[a-z][a-z0-9-]{0,31}$/,ac=["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"];Ge.map(e=>e.method);function K(e,t,r){return{code:e,message:t,data:r}}function wo(e){return Il(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?K("RUNTIME_ERROR",e.message):K("UNKNOWN_ERROR","小程序运行时异常",e)}function Il(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function _l(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Sl=1e3;function vl(e,t=_l()){if(t.userActivation)return t.userActivation.isActive===!0;const r=t.lastUserInteractionAt,n=t.now??Date.now();return t.activeElement===e&&r!==void 0&&n>=r&&n-r<=Sl}const Ol="runtime.gate.probe",cc=new Set(Ge.map(e=>e.method));class Rl{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=Za;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:Xe,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:"unload",payload:{timestamp:Date.now()}})}catch{}finally{window.removeEventListener("message",this.handleMessage);for(const r of["pointerdown","touchend","mousedown","keydown"])window.removeEventListener(r,this.handleUserInteraction,!0);this.lastUserInteractionAt=void 0;for(const r of this.operations.values())r.abort("bridge destroyed");this.operations.clear()}}postEvent(t,r){this.destroyed||this.postMessage({namespace:Xe,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Xe,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Xe,version:2,nonce:this.nonce,type:"event",id:t,method:tc,payload:r})}onMessage(t){if(!this.started||!this.isTrustedMiniProgramMessage(t))return;const r=t.data;if(r.type==="handshake"){this.handleHandshake(r,t.origin);return}if(r.type==="request"){let n=!1;try{n=vl(this.iframe,{activeElement:document.activeElement,userActivation:navigator.userActivation,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{n=!1}this.handleRequest(r,n);return}if(r.type==="cancel"&&this.handshaken&&r.id){this.operations.get(r.id)?.abort();return}r.type==="event"&&this.handshaken&&this.onInternalEvent?.(r)}onUserInteraction(t){const r=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||r.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&fl(t.data)&&(!this.handshaken||t.data.version===this.bridgeVersion)&&((this.handshaken?this.bridgeVersion:t.data.version)===1||this.targetOrigin==="*"||t.origin===this.targetOrigin)&&t.data.nonce===this.nonce}handleHandshake(t,r){const n=t.payload,i=t.version,o=!this.handshaken;if(o){if(this.onHandshake?.(n)===!1)return;this.bridgeVersion=i,i===1&&this.targetOrigin!=="*"&&r&&r!=="null"&&(this.targetOrigin=r),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.environmentInfo&&t.id&&this.postMessage({namespace:Xe,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:ec,payload:{environment:this.environmentInfo}}),this.postEvent("ready",{timestamp:Date.now()}),o?this.onReady?.(n):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===Ol){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,K("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!cc.has(t.method)){this.postResponse(t,void 0,K("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,K("INVALID_PARAMS","bridge request id 重复"));return}const n=new AbortController;this.operations.set(t.id,n);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{postEvent:this.postEvent.bind(this),postProgress:o=>{this.operations.get(t.id)===n&&this.postProgress(t.id,o)},signal:n.signal,trustedUserGesture:r});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==n)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==n)return;const o=wo(i);this.postResponse(t,void 0,o),this.postEvent("error",o)}finally{this.operations.get(t.id)===n&&(this.operations.delete(t.id),n.signal.aborted||n.abort("operation terminal"))}}postResponse(t,r,n){if(!(!this.postMessage({namespace:Xe,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!Pl(t.method)))try{this.onResponsePosted?.({method:t.method,outcome:n?"error":"success",...n?{errorCode:n.code}:{}})}catch{}}postMessage(t){const r=this.iframe.contentWindow;return r?(r.postMessage(t,this.targetOrigin),!0):!1}}function Pl(e){return typeof e=="string"&&cc.has(e)}const dc="METHOD_FORBIDDEN";function _e(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=dc,t}class se extends Error{code="HOST_REQUEST_UNSUPPORTED";constructor(t="当前 Host 不支持该请求形状",r){super(t),this.name="HostRequestUnsupportedError",r&&"cause"in r&&Object.defineProperty(this,"cause",{configurable:!0,enumerable:!1,value:r.cause}),Object.setPrototypeOf(this,new.target.prototype)}}const $o={[$r]:["workspaceCards.requestRefresh"],[Wr]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Kr]:["account.getCurrentUserId","account.onChange","network.request"],[Yr]:["account.getCurrentUserId","account.onChange","network.request"],[Qr]:["account.getCurrentUserId","account.onChange","network.request"],[Jr]:["presentation.setClipboard"],[Xr]:["presentation.showShareMenu"],[Zr]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ot]:["presentation.applyOrientation"],[en]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[tn]:["presentation.setNavigationBarStyle"],[Zt]:["storage.getRaw"],[er]:["storage.setRaw"],[rn]:["network.request"],[nn]:["network.stream","files.transfer","files.access"],[on]:["network.upload","files.access"],[sn]:["files.external"],[an]:["files.external"],[cn]:["files.save"],[tr]:["files.access"],[rr]:["files.removeFile"],[dn]:["files.access"],[nr]:["files.access"],[ln]:["files.access"],[ir]:["files.access"],[un]:["files.access"],[or]:["files.access"],[fn]:["files.access"],[sr]:["files.removeDirectory"],[hn]:["files.access"],[mn]:["files.access"],[pn]:["presentation.showToast"],[gn]:["presentation.showLoading"],[yn]:["presentation.hideLoading"],[En]:["presentation.vibrate"],[wn]:["presentation.setClipboard"],[An]:["protocol.invoke"],[bn]:["presentation.close"],[In]:["presentation.reload"],[_n]:["presentation.openAppPage"],[ke]:["account.getCurrentUserId","account.onChange","network.request"],[Ie]:["account.onChange","network.request"],[ze]:["account.getCurrentUserId","account.onChange","network.request"],[st]:["account.getCurrentUserId","account.onChange","network.request"],[De]:["account.onChange","network.request"],[Tn]:["companion.getInfo"],[Cn]:["companion.getPreparationStatus"],[Ln]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[Mn]:["companion.cancelPreparation"],[kn]:["companion.getActiveSession"],[Un]:["companion.getInfo","companion.launch"],[xn]:["companion.session.write"],[Hn]:["companion.session.closeStdin"],[Fn]:["companion.session.terminate"],[Bn]:["companion.session.ackOutput"],[Vn]:["companion.openAttachment"],[qn]:["companion.showNotification"]};function Nl(e,t){if(t[e]!==!0)throw _e(e)}const Dl=32*1024*1024,Tl=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Cl(e){if(e.mode==="request-only")return{network:{request:(n,i)=>e.request(n,i)}};if(e.mode==="override-request")return{network:{request:(n,i)=>e.request(n,i)},...e.stream===void 0?{}:{stream:e.stream}};const{consume:t,stream:r}=e;return{stream:r,network:{async request(n,i){const o=await r.open(n,i);let s;try{const a=await t(o.body,{maxBytes:Dl},i);return Ll(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Ll(e,t){const r=Object.fromEntries(Object.entries(e.headers).map(([n,i])=>[n,i.join(", ")]));return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:r,data:Ml(t,Ul(e,"content-type"))}}function Ml(e,t){kl(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new se("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!Tl.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function kl(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new se(`Host network response 不支持 charset=${t}`)}function Ul(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function k(e){return typeof e=="function"}function Wo(e){return(...t)=>{throw _e(e)}}function re(e){return async(...t)=>{throw _e(e)}}const xl=(e,t)=>{},Hl=()=>()=>{};function Fl(e){const t={request:k(e.network?.request)?e.network.request.bind(e.network):re("network.request")},r={getCurrentUserId:k(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):re("account.getCurrentUserId"),ensureAuthenticated:k(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):re("account.ensureAuthenticated"),onChange:k(e.account?.onChange)?e.account.onChange.bind(e.account):Hl},n={getRaw:k(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):re("storage.getRaw"),setRaw:k(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):re("storage.setRaw")},i={...k(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...k(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:k(e.presentation?.close)?e.presentation.close.bind(e.presentation):re("presentation.close"),reload:k(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):re("presentation.reload"),openAppPage:k(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):re("presentation.openAppPage"),openWindow:k(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):re("presentation.openWindow"),getViewportMetrics:k(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Wo("presentation.getViewportMetrics"),getNavigationBarHeight:k(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Wo("presentation.getNavigationBarHeight"),setNavigationBarStyle:k(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):re("presentation.setNavigationBarStyle"),showShareMenu:k(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):re("presentation.showShareMenu"),setScreenshotChromeHidden:k(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):xl,captureAndShare:k(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):re("presentation.captureAndShare"),showToast:k(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):re("presentation.showToast"),showLoading:k(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):re("presentation.showLoading"),hideLoading:k(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):re("presentation.hideLoading"),vibrate:k(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):re("presentation.vibrate"),setClipboard:k(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):re("presentation.setClipboard")},o=k(e.storageDiagnostics?.listRaw)?{listRaw:e.storageDiagnostics.listRaw.bind(e.storageDiagnostics)}:void 0,s=Object.fromEntries(["getInfo","getPreparationStatus","prepare","cancelPreparation","getActiveSession","launch","write","closeStdin","terminate","ackOutput","openAttachment","showNotification"].map(c=>[c,k(e.companion?.[c])?e.companion[c].bind(e.companion):re(`companion.${c}`)]));k(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const a={invoke:k(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):re("protocol.invoke")};return{network:t,account:r,storage:n,presentation:i,companion:s,protocol:a,...e.files===void 0?{}:{files:e.files},...e.picker===void 0?{}:{picker:e.picker},...e.transfer===void 0?{}:{transfer:e.transfer},...o?{storageDiagnostics:o}:{}}}function Bl(e){const t=Vl(e.files?.sandbox),r=k(e.picker?.pickFiles)&&k(e.picker?.pickDirectory),n=k(e.picker?.saveFile),i=t||r||n||k(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getCurrentUserId":k(e.account?.getCurrentUserId),"account.ensureAuthenticated":k(e.account?.ensureAuthenticated),"account.onChange":k(e.account?.onChange),"network.request":k(e.network?.request),"network.stream":k(e.transfer?.network.open)&&k(e.transfer?.network.release),"network.upload":k(e.transfer?.upload?.upload),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":k(o?.remove),"files.removeDirectory":k(e.files?.sandbox.remove),"files.transfer":k(e.transfer?.files.writeResource),"storage.getRaw":k(e.storage?.getRaw),"storage.setRaw":k(e.storage?.setRaw),"presentation.close":k(e.presentation?.close),"presentation.reload":k(e.presentation?.reload),"presentation.openAppPage":k(e.presentation?.openAppPage),"presentation.applyOrientation":k(e.presentation?.applyOrientation),"presentation.openWindow":k(e.presentation?.openWindow),"presentation.getViewportMetrics":k(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":k(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":k(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":k(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":k(e.presentation?.captureAndShare),"presentation.showToast":k(e.presentation?.showToast),"presentation.showLoading":k(e.presentation?.showLoading),"presentation.hideLoading":k(e.presentation?.hideLoading),"presentation.vibrate":k(e.presentation?.vibrate),"presentation.setClipboard":k(e.presentation?.setClipboard),"workspaceCards.requestRefresh":!1,"companion.getInfo":k(e.companion?.getInfo),"companion.getPreparationStatus":k(e.companion?.getPreparationStatus),"companion.prepare":k(e.companion?.prepare),"companion.cancelPreparation":k(e.companion?.cancelPreparation),"companion.getActiveSession":k(e.companion?.getActiveSession),"companion.launch":k(e.companion?.launch),"companion.session.write":k(e.companion?.write),"companion.session.closeStdin":k(e.companion?.closeStdin),"companion.session.terminate":k(e.companion?.terminate),"companion.session.ackOutput":k(e.companion?.ackOutput),"companion.openAttachment":k(e.companion?.openAttachment),"companion.showNotification":k(e.companion?.showNotification),"protocol.invoke":k(e.protocol?.invoke)}}function Vl(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&k(t.file)&&k(t.directory)&&k(t.create)&&k(t.stat)&&k(t.list)}function Ko(e,t){return t?.[e]!==!1}function ql(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("companion.")}function lc(e,t={}){const r={};for(const n of Object.keys($o)){const o=$o[n].every(a=>e[a]),s=!ql(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=Ko(n,t.callerCapabilities)&&Ko(n,t.hostCapabilities)&&o&&s}return r}function uc(e={},t={}){const r=Bl(e),n=lc(r,t);return{ports:Fl(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function Tt(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):zl(e.signal,t);return{...e,signal:r}}function zl(e,t){const r=new AbortController,n=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",s)},i=a=>{r.signal.aborted||(n(),r.abort(a.reason))},o=()=>i(e),s=()=>i(t);return e.aborted?i(e):t.aborted?i(t):(e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",s,{once:!0})),r.signal}function Gl(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 jl=4,$l=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Wl=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade"]),Kl=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Yl=["/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 Ql(e,t){const r=Zl(e);return r===null||Yo(r,Kl)?!0:t&&Yo(r,Yl)}function Jl(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return $l.some(r=>t===r||t.endsWith(`.${r}`))}function Xl(e){const t=e.trim().toLowerCase();return Wl.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Zl(e){let t=e;for(let r=0;r<jl;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Qo(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Qo(t)}function Yo(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Qo(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function lt(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Jo(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function fc(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,o=new Map,s=new Set,a=new Set;let c=!1;function l(A,O){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:A,type:O})).catch(()=>{})}catch{}}function h(A){const O=r.get(A);if(!O)throw new Error("Unknown runtime cache scope");return O}function g(A,O){return A.flatMap((b,D)=>{const _=JSON.stringify(A.slice(0,D+1));return[JSON.stringify([_]),JSON.stringify([_,O])]})}function u(A,O){return JSON.stringify(g(A,O).map(b=>n.get(b)??0))}async function p(A,O){const b=h(A),D=JSON.stringify([JSON.stringify(b),...O?[O]:[]]),_=(n.get(D)??0)+1;n.set(D,_),i.add(D);for(const L of a)L(b,O);if(!e.store){i.delete(D),l(O??"*","invalidation");return}try{await e.store.invalidate(b,O)}catch(L){throw l(O??"*","storage_error"),L}n.get(D)===_&&i.delete(D),l(O??"*","invalidation")}function v(A){if(c)throw new Error("Runtime cache manager disposed");const O=o.get(A.namespace);if(O){if(O.sourceCodec!==A.codec||O.definition.codec.version!==A.codec.version||JSON.stringify(O.definition.policy)!==JSON.stringify(A.policy))throw new Error("Conflicting runtime cache namespace");return O.cache}if(!A.namespace||!A.codec.version)throw new Error("Invalid runtime cache definition");const b=Object.freeze({...A.policy}),D=Object.freeze({version:A.codec.version,encode:A.codec.encode.bind(A.codec),decode:A.codec.decode.bind(A.codec),validate:A.codec.validate.bind(A.codec),clone:A.codec.clone.bind(A.codec)}),_=A.namespace;for(const P of[b.ttlMs,b.memoryMaxEntries,b.diskMaxEntries,b.diskMaxBytes,b.maxEntryBytes])if(!Number.isFinite(P)||P<0)throw new Error("Invalid runtime cache policy");const L=new Map,F=new Map,N=new Map;let I=!1;function d(P,M,R){if(c||I||P.aborted||u(M,_)!==R)throw lt()}function m(P){return b.ttlMs>0&&b.persistence==="memory-and-disk"&&!!e.store&&!g(P,_).some(M=>i.has(M))}function f(P,M,R){const U=t();return P.envelopeVersion===1&&JSON.stringify(P.address)===JSON.stringify(M)&&Jo(P.revisions,R)&&P.payload.byteLength<=b.maxEntryBytes&&Number.isFinite(P.cachedAt)&&Number.isFinite(P.expiresAt)&&P.cachedAt<=U&&P.cachedAt>=0&&P.expiresAt>P.cachedAt&&Math.min(P.expiresAt,P.cachedAt+b.ttlMs)>U}function E(P,M,R,U,x){if(!(b.ttlMs<=0||b.memoryMaxEntries<1)){for(const[H,z]of L)Math.min(z.entry.expiresAt,z.entry.cachedAt+b.ttlMs)<=t()&&L.delete(H);for(L.delete(P);L.size>=Math.floor(b.memoryMaxEntries);){const H=L.keys().next();if(H.done)break;L.delete(H.value)}L.set(P,{entry:M,value:R,epoch:U,persistent:x})}}async function w(P,M,R,U){const x={namespace:_,codecVersion:D.version,scopeIds:M,key:P.key},H=JSON.stringify(x);let z=[],G=m(M);if(G)try{z=await e.store.readRevisions(M,_)}catch{G=!1,l(_,"storage_error")}d(U.signal,M,R);async function $(){if(!G)return!0;try{return Jo(z,await e.store.readRevisions(M,_))}catch{return G=!1,l(_,"storage_error"),!1}}const ee=L.get(H);if(b.ttlMs>0&&ee&&ee.epoch===R&&f(ee.entry,x,z)&&ee.persistent===G&&await $())return d(U.signal,M,R),l(_,"memory_hit"),ee.value;if(L.delete(H),G){let W,he;try{W=await e.store.read(x,b.maxEntryBytes),W&&f(W,x,z)?he=D.decode(W.payload):W=void 0}catch{W=void 0,l(_,"storage_error")}if(d(U.signal,M,R),W&&await $())return d(U.signal,M,R),E(H,W,he,R,!0),l(_,"disk_hit"),he}l(_,"miss");const Z=D.validate(await P.load(U.signal));d(U.signal,M,R);const J=D.clone(Z);if(!await $()&&G)throw lt();if(d(U.signal,M,R),b.ttlMs>0){const W=t();let he;try{he=D.encode(J)}catch{return J}const zo={envelopeVersion:1,address:x,revisions:G?z:[],cachedAt:W,expiresAt:W+b.ttlMs,payload:he};if(G&&he.byteLength<=b.maxEntryBytes){let ei=!0,Go=!1;try{ei=await e.store.publish(zo,b),Go=ei}catch{l(_,"storage_error")}if(d(U.signal,M,R),!ei)throw lt();Go&&l(_,"published")}d(U.signal,M,R),E(H,zo,J,R,G)}return J}async function S(P){if(c||I||P.signal?.aborted)return Promise.reject(lt());const M=h(P.scope),R=u(M,_);let U;if(m(M)){const G=new AbortController;N.set(G,M);const $=()=>G.abort();P.signal?.addEventListener("abort",$,{once:!0});let ee=()=>{};try{U=await Promise.race([e.store.readRevisions(M,_),new Promise((Z,J)=>{const W=()=>J(lt());G.signal.addEventListener("abort",W,{once:!0}),ee=()=>G.signal.removeEventListener("abort",W)})])}catch{G.signal.aborted||l(_,"storage_error")}finally{ee(),N.delete(G),P.signal?.removeEventListener("abort",$)}}d(P.signal??new AbortController().signal,M,R);const x=JSON.stringify([M,P.key,R,U]);let H=F.get(x);if(H?.controller.signal.aborted&&(H=void 0),!H){const G=new AbortController;H={ids:M,controller:G,waiters:0,promise:Promise.resolve(void 0)};const $=H;$.promise=w(P,M,R,G).finally(()=>{F.get(x)===$&&F.delete(x)}),F.set(x,$)}const z=H;return z.waiters+=1,new Promise((G,$)=>{let ee=!1;function Z(W){ee||(ee=!0,P.signal?.removeEventListener("abort",J),z.controller.signal.removeEventListener("abort",J),z.waiters-=1,z.waiters===0&&z.controller.abort(),W())}function J(){Z(()=>$(lt()))}P.signal?.addEventListener("abort",J,{once:!0}),z.controller.signal.addEventListener("abort",J,{once:!0}),z.promise.then(W=>Z(()=>{try{d(P.signal??new AbortController().signal,M,R),G(D.clone(W))}catch(he){$(he)}}),W=>Z(()=>$(W)))})}function T(P,M){if(M&&M!==_)return;const R=U=>P.every((x,H)=>U[H]===x);for(const[U,x]of L)R(x.entry.address.scopeIds)&&L.delete(U);for(const[U,x]of F)R(x.ids)&&(x.controller.abort(),F.delete(U));for(const[U,x]of N)R(x)&&U.abort()}function V(){if(!I){I=!0,L.clear();for(const P of N.keys())P.abort();N.clear();for(const P of F.values())P.controller.abort();F.clear(),s.delete(V),a.delete(T),o.get(_)?.cache===C&&o.delete(_)}}const C={read:S,invalidateScope:P=>p(P,_),dispose:V};return s.add(V),a.add(T),o.set(_,{definition:{namespace:_,codec:D,policy:b},sourceCodec:A.codec,cache:C}),C}return{createScope(A,O){if(c||!A)throw new Error("Invalid runtime cache scope");const b=Object.freeze({});return r.set(b,[...O?h(O):[],A]),b},register:v,invalidateScope:A=>p(A),dispose(){if(!c){c=!0;for(const A of[...s])A();o.clear(),n.clear(),i.clear()}}}}function eu(e){const t=new TextEncoder,r=new TextDecoder("utf-8",{fatal:!0});return{version:e.version,validate:e.validate,encode:n=>t.encode(JSON.stringify(n)),decode:n=>e.validate(JSON.parse(r.decode(n))),clone:n=>e.validate(JSON.parse(JSON.stringify(n)))}}const tu=".hb-runtime-cache-v1",ti=64*1024,ut=1e3,ru=2048,Lt=32*1024*1024,nu=1024,Mr=new TextEncoder,Xo=new TextDecoder("utf-8",{fatal:!0});function Mt(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function _r(e){const t=await globalThis.crypto.subtle.digest("SHA-256",Mr.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function ve(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Zo(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function iu(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function es(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function ou(e,t){const r=e.sandbox.directory(tu),n=r.directory("revisions"),i=r.directory("entries");for(const d of[r,n,i,i.directory("capability-check")])es(d,["directory","file","create","stat","list","remove"]),es(d.file("capability-check"),["create","stat","read","write","remove"]);let o=Promise.resolve(),s=!1;function a(d){if(iu(d))throw s=!0,d}function c(){if(t.signal.aborted)throw Mt();if(s)throw Object.assign(new Error("Host 不支持完整文件能力,磁盘缓存已关闭"),{code:"METHOD_FORBIDDEN"})}function l(d,m=t.signal){const f=o.then(()=>{if(m.aborted)throw Mt();return c(),d()},()=>{if(m.aborted)throw Mt();return c(),d()}).catch(S=>{throw a(S),S});if(o=f.catch(()=>{}),m.aborted)return Promise.reject(Mt());let E=()=>{};const w=new Promise((S,T)=>{const V=()=>T(Mt());m.addEventListener("abort",V,{once:!0}),E=()=>m.removeEventListener("abort",V)});return Promise.race([f,w]).finally(E)}async function h(){c(),await n.create({recursive:!0,exclusive:!1},t),await i.create({recursive:!0,exclusive:!1},t),c()}async function g(d,m){const f=n.file(`${await _r([d,m??null])}.revision`);await p(f);let E=!1;try{await f.create({recursive:!1,exclusive:!0},t),E=!0}catch(T){a(T),c()}if(E){const T=Zo();return await f.write(Mr.encode(T),t),c(),T}const w=await f.stat(t);if(w.size<1||w.size>128)throw new Error("缓存 revision 文件损坏");const S=Xo.decode(await f.read(t));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(S))throw new Error("缓存 revision 文件损坏");return c(),S}async function u(d){const m=await d.list({limit:ut},t);if(m.length>=ut)throw new Error("缓存目录超过治理上限");return m}async function p(d){try{await d.stat(t);return}catch(f){if(!Sr(f))throw f}if((await u(n)).length>=ut-1)throw new Error("缓存 metadata 超过治理上限")}async function v(d,m){await h();const f=[];for(let E=0;E<d.length;E+=1){const w=d.slice(0,E+1);f.push(await g(w),await g(w,m))}return f}async function A(d){return r.directory(`entries/${await _r([d.namespace,d.codecVersion,d.scopeIds])}`)}async function O(d){return(await A(d)).file(`${await _r(d.key)}.cache`)}async function b(d,m){const f=await d.stat(t);if(f.size<5||f.size>m+ti+4)throw new Error("缓存条目超过大小限制");const E=await d.read(t);if(c(),E.length!==f.size)throw new Error("缓存条目读取不完整");const w=new DataView(E.buffer,E.byteOffset,E.byteLength).getUint32(0);if(w<1||w>ti||w+4>E.length)throw new Error("缓存信封损坏");const S=JSON.parse(Xo.decode(E.subarray(4,w+4))),T=E.slice(w+4);if(S.envelopeVersion!==1||!S.address||!Array.isArray(S.address.scopeIds)||!S.address.scopeIds.every(V=>typeof V=="string")||typeof S.address.namespace!="string"||typeof S.address.codecVersion!="string"||typeof S.address.key!="string"||!Array.isArray(S.revisions)||S.revisions.length!==S.address.scopeIds.length*2||!S.revisions.every(V=>typeof V=="string"&&V.length>0)||!Number.isSafeInteger(S.cachedAt)||!Number.isSafeInteger(S.expiresAt)||S.cachedAt<0||S.expiresAt<=S.cachedAt||S.payloadBytes!==T.length||T.length>m)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:S.address,revisions:S.revisions,cachedAt:S.cachedAt,expiresAt:S.expiresAt,payload:T}}async function D(d){if(!d.remove)throw new Error("Host 不支持缓存文件删除");await d.remove(t)}async function _(d){try{if((await d.file.stat(t)).size!==d.size)return!1;const m=await b(d.file,Lt);return!ve(m.address,d.entry.address)||!ve(m.revisions,d.entry.revisions)||m.cachedAt!==d.entry.cachedAt||m.expiresAt!==d.entry.expiresAt||!ve(await L(m.payload),await L(d.entry.payload))?!1:(await D(d.file),!0)}catch(m){if(Sr(m))return!0;throw m}}async function L(d){const m=await globalThis.crypto.subtle.digest("SHA-256",d);return Array.from(new Uint8Array(m),f=>f.toString(16).padStart(2,"0")).join("")}async function F(){const d=await u(n);let m=0;for(const S of d)if(S.kind==="file"&&(m+=(await S.stat(t)).size,m>Lt))throw new Error("缓存扫描超过字节上限");const f=[];let E=0,w=m;for(const S of await u(i)){if(S.kind!=="directory")throw new Error("缓存目录结构损坏");for(const T of await u(S)){if(T.kind!=="file"||++E>ru)throw new Error("缓存文件超过治理上限");const V=(await T.stat(t)).size;if(w+=V,w>Lt)throw new Error("缓存扫描超过字节上限");try{const C=await b(T,Lt);f.push({file:T,entry:C,size:(await T.stat(t)).size,bucketName:S.name})}catch(C){a(C),c(),Sr(C)||await D(T)}}}return{entries:f,metadataBytes:m}}async function N(){for(const d of await u(i))if(d.kind==="directory"&&d.remove&&(await u(d)).length===0)try{await d.remove({recursive:!1},t)}catch(m){a(m),c()}}function I(d){const{payload:m,...f}=d,E=Mr.encode(JSON.stringify({...f,payloadBytes:m.length}));if(E.length>ti)throw new Error("缓存信封过大");const w=new Uint8Array(4+E.length+m.length);return new DataView(w.buffer).setUint32(0,E.length),w.set(E,4),w.set(m,E.length+4),w}return{readRevisions:(d,m)=>l(()=>v(d,m)),read:(d,m)=>l(async()=>{c();const f=await O(d);let E;try{E=await b(f,m)}catch(w){if(c(),Sr(w))return;throw w}if(!(!ve(E.address,d)||E.expiresAt<=Date.now())&&ve(E.revisions,await v(d.scopeIds,d.namespace)))return E}),publish:(d,m)=>l(async()=>{c();const{address:f}=d;if(!ve(d.revisions,await v(f.scopeIds,f.namespace)))return!1;const E=I(d);if(d.payload.length>m.maxEntryBytes||E.length>m.diskMaxBytes||m.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await h();const w=await A(f),S=await O(f),T=await F(),V=[],C=new Map;for(const R of T.entries){if(R.bucketName===w.name&&R.file.name===S.name)continue;const U=JSON.stringify([R.entry.address.scopeIds,R.entry.address.namespace]);let x=C.get(U);if(x||(x=await v(R.entry.address.scopeIds,R.entry.address.namespace),C.set(U,x)),R.entry.expiresAt<=Date.now()||!ve(R.entry.revisions,x)){if(!await _(R))throw new Error("缓存治理期间条目已变化")}else V.push(R)}V.sort((R,U)=>R.entry.cachedAt-U.entry.cachedAt);function P(){const R=V.filter(U=>U.bucketName===w.name);return V.length+1>nu||E.length+T.metadataBytes+V.reduce((U,x)=>U+x.size,0)>Lt||R.length+1>Math.min(m.diskMaxEntries,ut-1)||E.length+R.reduce((U,x)=>U+x.size,0)>m.diskMaxBytes}for(;P();){const R=V.filter(H=>H.bucketName===w.name),x=R.length+1>Math.min(m.diskMaxEntries,ut-1)||E.length+R.reduce((H,z)=>H+z.size,0)>m.diskMaxBytes?R[0]:V[0];if(!x||!await _(x))throw new Error("缓存容量不足或条目已变化");V.splice(V.indexOf(x),1)}await N();const M=await u(i);if(!M.some(R=>R.name===w.name)&&M.length>=ut-1)throw new Error("缓存目录超过治理上限");if(await w.create({recursive:!0,exclusive:!1},t),!ve(d.revisions,await v(f.scopeIds,f.namespace)))return!1;try{await S.create({recursive:!1,exclusive:!0},t)}catch(R){a(R),await S.stat(t)}return await S.write(E,t),c(),ve(d.revisions,await v(f.scopeIds,f.namespace))}),invalidate:(d,m)=>l(async()=>{await h();const f=n.file(`${await _r([d,m??null])}.revision`);await p(f);try{await f.create({recursive:!1,exclusive:!0},t)}catch(E){a(E),await f.stat(t)}await f.write(Mr.encode(Zo()),t),c();try{const{entries:E}=await F();for(const w of E){if(m!==void 0&&w.entry.address.namespace!==m||!d.every((T,V)=>w.entry.address.scopeIds[V]===T))continue;const S=await v(w.entry.address.scopeIds,w.entry.address.namespace);ve(w.entry.revisions,S)||await _(w)}await N()}catch(E){a(E),c()}})}}function Sr(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const su="RATE_LIMITED_BY_RUNTIME",au="RATE_LIMITED",hc=20,mc=40,pc=150,gc=20,yc=1e4,Ec=45e3,wc=1,cu=300*1e3,du=64;function ft(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function lu(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function uu(e={}){const t=e.now??Date.now,r=lu(e.coalesceWindowMs,pc),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,ft(e.budget?.ratePerSecond,hc)),burst:Math.max(1,Math.floor(ft(e.budget?.burst,mc)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(ft(e.loopDetection?.maxCalls,gc))),windowMs:Math.max(1,Math.floor(ft(e.loopDetection?.windowMs,yc)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(ft(e.circuitBreaker?.failureThreshold,wc))),openMs:Math.max(1,Math.floor(ft(e.circuitBreaker?.openMs,Ec)))},s=new Map,a=new Map,c=new Set,l=new Map,h=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},g={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let u=!1;function p(I){try{e.onReport?.(I)}catch{}}function v(I,d){if(!i)return{exceeded:!1,count:0};const m=a.get(I)??[],f=d-i.windowMs;let E=0;for(;E<m.length&&m[E]<=f;)E+=1;E>0&&m.splice(0,E);const w=m.length>=i.maxCalls;return w||(m.push(d),m.length>i.maxCalls+1&&m.splice(0,m.length-(i.maxCalls+1))),a.set(I,m),{exceeded:w,count:m.length}}function A(I){if(!n)return!0;const d=Math.max(0,I-h.updatedAt)/1e3;return h.tokens=Math.min(n.burst,h.tokens+d*n.ratePerSecond),h.updatedAt=I,h.tokens<1?!1:(h.tokens-=1,!0)}function O(I){if(!n)return 0;const d=Math.max(0,I-h.updatedAt)/1e3,m=Math.min(n.burst,h.tokens+d*n.ratePerSecond);return Math.max(0,Math.ceil((1-m)/n.ratePerSecond*1e3))}function b(I,d,m,f,E){if(!o)return;const w=l.get(d),S=(w?.open?0:w?.failures??0)+1;if(S<o.failureThreshold){l.set(d,{open:!1,openedAt:0,openMs:0,failures:S});return}const T=Math.min(Math.max(o.openMs,f),cu);l.set(d,{open:!0,openedAt:E,openMs:T,failures:S}),g.circuitOpened+=1,p({type:"circuit_opened",capability:I,endpointId:d,status:m,openMs:T,timestamp:E})}function D(I){const d=l.get(I);d&&!d.open&&l.delete(I)}function _(I){for(const[d,m]of s)!m.pending&&m.expiresAt<=I&&s.delete(d);for(;s.size>=du;){const d=[...s].find(([,m])=>!m.pending);if(!d)break;s.delete(d[0])}}function L(I,d){if(I===void 0)return;const m=s.get(I);m?.promise===d&&(m.pending=!1)}function F(I,d){if(I===void 0)return;s.get(I)?.promise===d&&s.delete(I)}async function N(I){if(u)return I.load();const d=t();if(o){const w=l.get(I.endpointId);if(w?.open){const S=w.openedAt+w.openMs-d;if(S>0)throw g.circuitRejected+=1,p({type:"circuit_rejected",capability:I.capability,endpointId:I.endpointId,retryAfterMs:S,timestamp:d}),mu("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:I.endpointId,retryAfterMs:S});l.delete(I.endpointId)}}const m=v(I.endpointId,d);m.exceeded&&i?c.has(I.endpointId)||(c.add(I.endpointId),p({type:"loop_detected",capability:I.capability,endpointId:I.endpointId,count:m.count,windowMs:i.windowMs,timestamp:d})):c.delete(I.endpointId);const f=r>0?I.coalesceKey:void 0;if(f!==void 0){const w=s.get(f);if(w&&(w.pending||w.expiresAt>d))return g.coalesced+=1,p({type:"coalesced",capability:I.capability,endpointId:I.endpointId,timestamp:d}),w.promise;w&&s.delete(f)}if(m.exceeded&&i)throw g.loopRejected+=1,ts("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:I.capability,endpointId:I.endpointId,count:m.count,windowMs:i.windowMs});if(!A(d)){g.budgetRejected+=1;const w=O(d);throw p({type:"budget_exhausted",capability:I.capability,endpointId:I.endpointId,retryAfterMs:w,timestamp:d}),ts("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:I.capability,endpointId:I.endpointId,retryAfterMs:w})}f!==void 0&&_(d);const E=I.load().then(w=>(L(f,E),D(I.endpointId),w),w=>{F(f,E);const S=fu(w);throw S!==void 0&&b(I.capability,I.endpointId,S,hu(w),d),w});return f!==void 0&&s.set(f,{promise:E,expiresAt:d+r,pending:!0}),E}return{execute:N,invalidateCoalescing(){s.clear()},snapshot(){return{...g,openCircuits:[...l.entries()].filter(([,I])=>I.open).map(([I])=>I)}},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear(),l.clear())}}}function fu(e){if(typeof e!="object"||e===null)return;const t=e.status;if(!(typeof t!="number"||!Number.isInteger(t)))return t===403||t===429?t:void 0}function hu(e){if(typeof e!="object"||e===null)return 0;const t=e.retryAfterMs;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function ts(e,t){return{code:su,message:e,data:t}}function mu(e,t){return{code:au,message:e,data:t}}const Ac=3e4,bc=6e4,qi=1440*60*1e3;function pu(e){const t=e!==!1&&(e?.enabled??!0),r=e===!1?void 0:e;return{enabled:t,debugReport:t&&r?.debugReport===!0,identityTtlMs:t?Math.max(0,Math.floor(r?.identityTtlMs??Ac)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??bc)):0,steamGameListTtlMs:t?gu(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:hc,burst:mc},coalesceWindowMs:r?.coalesceWindowMs??pc,loopDetection:r?.loopDetection??{maxCalls:gc,windowMs:yc},circuitBreaker:r?.circuitBreaker??{failureThreshold:wc,openMs:Ec}}}}function gu(e){return e===void 0||!Number.isFinite(e)?qi:Math.max(0,Math.floor(e))}function y(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function B(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yu(e){return typeof e=="object"&&e!==null}function ye(e,t){const r=e.data;if(!yu(r)||typeof r.status!="string")throw new Error(t);return r}const Ic={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Eu={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 ye(e,"工坊小程序详情加载失败")}};function pr(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function wu(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Au(e){const t=ye(e,"小程序登录授权接口响应异常"),r=t.result,n={};if(r.login_code&&typeof r.login_code=="object"){const i=r.login_code;n.loginCode={code:i.code,expiresIn:i.expires_in,scopes:i.scopes||[]}}return r.consent_challenge&&typeof r.consent_challenge=="object"&&(n.consentChallenge=wu(r.consent_challenge)),{...t,result:n}}const bu={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.authorization.cancel.post",method:"POST",path:"/user_miniprogram/runtime/auth/authorization/cancel",body:e=>({...pr(e.runtimeContext),challenge:e.challenge}),parse:e=>ye(e,"小程序授权取消接口响应异常")},Iu={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.authorization.revoke.post",method:"POST",path:"/user_miniprogram/runtime/auth/authorization/revoke",body:e=>pr(e.runtimeContext),parse:e=>ye(e,"小程序授权撤销接口响应异常")},_u={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.local_identity.post",method:"POST",path:"/user_miniprogram/runtime/local_identity",body:e=>pr(e.runtimeContext),parse(e){const t=ye(e,"小程序隔离身份接口响应异常"),r=typeof t.result.steam_id=="string"&&t.result.steam_id.trim()?t.result.steam_id.trim():void 0;return{...t,result:{appUserId:t.result.app_user_id,...r?{steamId:r}:{}}}}},Su={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.login.begin.post",method:"POST",path:"/user_miniprogram/runtime/auth/login/begin",body:e=>({...pr(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Au(e)},vu={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.login.confirm.post",method:"POST",path:"/user_miniprogram/runtime/auth/login/confirm",body:e=>({...pr(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=ye(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},Ou=64;function _c(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??Ou)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(g){for(const[u,p]of i)p.expiresAt<=g&&i.delete(u)}function l(g,u,p){if(a||t<=0||p!==s)return;const v=n();for(c(v),i.delete(g);i.size>=r;){const A=i.keys().next();if(A.done)break;i.delete(A.value)}i.set(g,{expiresAt:v+t,value:u})}function h(g,u){if(a)return u();if(t>0){const O=i.get(g);if(O&&O.expiresAt>n())return Promise.resolve(O.value);O&&i.delete(g)}const p=o.get(g);if(p)return p;const v=s,A=u().then(O=>(l(g,O,v),O)).finally(()=>{o.get(g)===A&&o.delete(g)});return o.set(g,A),A}return{read:h,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function Ru(e,t){return t?e?"server":"local":"legacy"}function Pu(e,t){if(e==="local")throw y("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const Nu=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],Du=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Tu=/authorization|cookie|pkey|password|secret|token/i,Sc=/authorization|cookie|pkey|token|password|secret/i;function Oe(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Cu(e){for(const t of Object.keys(e))if(!Du.has(t))throw new se(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of Nu)if(Object.prototype.hasOwnProperty.call(e,t)&&Oe(e,t)!==void 0)throw new se(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Oe(e,"bodyEncoding")!==void 0&&Oe(e,"bodyEncoding")!=="json"&&Oe(e,"bodyEncoding")!=="form")throw new se("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Oe(e,"failurePresentation")!==void 0&&Oe(e,"failurePresentation")!=="none")throw new se("endpoint failurePresentation 必须为 none");if(Oe(e,"auth")!==void 0&&Oe(e,"auth")!=="none"&&Oe(e,"auth")!=="optional"&&Oe(e,"auth")!=="required")throw new se("endpoint auth 必须为 none、optional 或 required")}function $t(e){if(Array.isArray(e))return e.map($t);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Tu.test(n)||(r[n]=$t(i));return r}function rs(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Sc.test(r)||(t[r]=n);return t}function Lu(e){if(!e)return;const t=Object.keys(e).find(r=>Sc.test(r));if(t)throw new se(`endpoint 禁止声明 credential-bearing header: ${t}`)}class St extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;retryAfterMs;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,t.retryAfterMs!==void 0&&(this.retryAfterMs=t.retryAfterMs),Object.setPrototypeOf(this,new.target.prototype)}}const ns=1440*60*1e3,Mu=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function ku(e,t=Date.now){if(!e)return;const r=Object.entries(e).find(([s])=>s.trim().toLowerCase()==="retry-after")?.[1];if(typeof r!="string"||!r.trim())return;const n=r.trim();if(/^\d+$/.test(n)){const s=Number(n)*1e3;return s>0?Math.min(s,ns):void 0}if(!Mu.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,ns):void 0}function Uu(e,t,r,n){if(e.method!=="GET")return;let i;try{i=JSON.stringify([t??null,r??null])??"undefined"}catch{return}return`${e.id}\0${n}\0${i}`}function vc(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class vt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,vc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class gr extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,vc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function xu(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:$t(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:rs(o),method:e.method,metadata:{endpointId:e.id},query:$t(n),timeout:e.timeout,url:r},data:$t(a.data),headers:rs(a.headers)||{},status:a.status,statusText:a.statusText}}async function Gn(e,t,r,n){if(!n||!n.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(n.credentials!=="heybox-session"&&n.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(Cu(t),typeof t.id!="string"||!t.id)throw new se("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new se("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new se("endpoint path 必须为非空字符串");const o=t.query?await t.query(r):void 0,s=t.body?await t.body(r):void 0,a=t.headers?await t.headers(r):void 0;Lu(a);const c=async()=>{let g;try{g=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...o===void 0?{}:{params:o},...s===void 0?{}:{data:s},...a===void 0?{}:{headers:a},credentials:n.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:n.signal,...n.miniProgramDetail===void 0?{}:{miniProgramDetail:n.miniProgramDetail}})}catch(p){throw p instanceof se?p:new vt({endpointId:t.id,cause:p})}if(g.status<200||g.status>=300)throw new St({endpointId:t.id,status:g.status,retryAfterMs:ku(g.headers)});const u=xu(t,r,i,o,s,a,n,g);if(t.parse)try{return await t.parse(u,r)}catch(p){throw new gr({endpointId:t.id,cause:p})}return u.data},l=n.gate;if(!l)return c();const h=Uu(t,o,s,n.credentials);return l.gate.execute({capability:l.capability,endpointId:t.id,...h===void 0?{}:{coalesceKey:h},load:c})}const Hu=new Set(_t),Ao="steam_account",Oc=new Set(_t.filter(e=>e!==Ao)),Fu=1e3;function Bu(e){const t=new Set,r=_c({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??Ac))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,l=e.userDataMode??Ru(e.networkEnabled===!0,c),h=e.requestPolicyEnabled!==!1,g=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function u(){if(!c)return{};if(!e.authorizationContext)throw y("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let C;try{C=await e.authorizationContext.get(e.operationContext)}catch{throw y("REQUEST_FAILED","读取 Runtime auth context 失败")}if(C.steamAccount!==c||C.userDataMode!==l)throw y("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const P=C.token.trim();if(!P)throw y("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:P}}const p=e.account.onChange(C=>{v(),A("heybox_app_login_change",{isHeyboxAppLoggedIn:!!C})});function v(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function A(C,P){C==="user_info_authorization_change"&&Wu(P)&&r.invalidate();for(const M of t)try{M(C,P)}catch{}}function O(){const C=e.identity.get()?.miniProgramId?.trim();if(!C)throw y("INVALID_STATE","当前能力缺少 canonical 小程序身份");return C}function b(){if(o||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function D(){b();let C;try{C=await e.account.getCurrentUserId(e.operationContext)}catch(P){throw as(P,e.operationContext.signal,"读取小黑盒账号失败")}return typeof C=="string"&&C.trim()?C.trim():void 0}async function _(C,P){const M=await D();if(i!==P||M!==C)throw y("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function L(C){b();try{await e.account.ensureAuthenticated({trustedUserGesture:C,reason:"runtime_auth",signal:e.operationContext.signal})}catch(M){throw as(M,e.operationContext.signal,"小黑盒登录失败")}const P=await D();if(!P)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return P}async function F(C,P,M=e.operationContext.signal){try{if(M.aborted)throw zi();return await $u(Gn(e.network,C,P,{...e.operationContext,credentials:"heybox-session",signal:M,...g?{gate:g}:{}}),M)}catch(R){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):R instanceof se?y("REQUEST_UNSUPPORTED",R.message):R instanceof gr?y("INVALID_RESPONSE","授权接口响应不合法"):R instanceof vt?y("REQUEST_FAILED","授权请求失败"):R instanceof St?h&&(R.status===403||R.status===429)?y("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:R.status,...R.retryAfterMs===void 0?{}:{retryAfterMs:R.retryAfterMs}}):y("REQUEST_FAILED",R.message):Rc(R)?R:y("REQUEST_FAILED","授权请求失败")}}async function N(C,P){await F(bu,{runtimeContext:{miniProgramId:C,...await u()},challenge:P}).catch(()=>{})}function I(C){const P=async()=>{const R=os(e.operationContext.signal);a=R;try{return await C(R.signal)}finally{a===R&&(a=void 0),R.abort()}},M=s.then(P,P);return s=M.then(()=>{},()=>{}),M}async function d(C,P,M,R,U){if(!M)throw await N(C,P.challenge),y("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await N(C,P.challenge),y("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return I(async x=>{await _(R,U);const H=await m(C,P.displayedScopes,x);await _(R,U);let z;try{z=await e.authPresentation.confirmAuthorization({miniProgramId:C,scopes:P.displayedScopes,...H,signal:x})}catch($){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await _(R,U),await N(C,P.challenge),Vu("REQUEST_FAILED","授权确认界面执行失败",$))}if(await _(R,U),z.status!=="granted")throw await N(C,P.challenge),y("AUTHORIZATION_CANCELLED","用户取消授权");const G=Gu(z.grantedScopes,P.displayedScopes,c);if(!G.includes("identity"))throw await N(C,P.challenge),y("AUTHORIZATION_CANCELLED","用户拒绝授权");return G})}async function m(C,P,M){const R=os(M),U=setTimeout(()=>R.abort(),Fu);try{const x=ju(e.miniProgramPresentation),[H,z]=await Promise.all([x?Promise.resolve(x):f(C,R.signal),P.includes("profile")?E(R.signal):Promise.resolve(void 0)]);return{...H?{miniProgram:H}:{},...z?{userProfile:z}:{}}}finally{clearTimeout(U),R.abort()}}async function f(C,P){try{const M=e.identity.get()?.version?.trim(),R=await F(Eu,{mini_program_id:C,...M?{miniprogram_version:M}:{}},P),U=ht(R,"小程序公开资料"),x=bt(U.name),H=bt(U.icon_url);return x||H?{...x?{name:x}:{},...H?{avatarUrl:H}:{}}:void 0}catch{return}}async function E(C){try{const P=await F(Ic,void 0,C),M=ht(P,"账号基础信息"),R=bt(M.display_username),U=bt(M.display_avatar);return R||U?{...R?{nickname:R}:{},...U?{avatar:U}:{}}:void 0}catch{return}}async function w(C,P){if(Pu(l,"auth.login"),!c&&C.includes(Ao))throw y("INVALID_PARAMS","auth.login 参数不合法");const M=O(),R=await L(P),U=i,x=await F(Su,{runtimeContext:{miniProgramId:M,...await u()},scopes:C});await _(R,U);const H=ht(x,"小程序登录"),z=ss(H,"loginCode"),G=ss(H,"consentChallenge");if(z===G)throw y("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let $;if(z)$=is(H.loginCode,c);else{const ee=qu(H.consentChallenge,c),Z=await d(M,ee,P,R,U);await _(R,U);const J=await F(vu,{runtimeContext:{miniProgramId:M,...await u()},challenge:ee.challenge,selectedScopes:Z});if(await _(R,U),$=is(ht(J,"小程序登录确认"),c),$.scopes.some(W=>!Z.includes(W)))throw y("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ee of $.scopes)n.add(ee);return r.invalidate(),A("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),A("user_info_authorization_change",ri(n,c)),$}async function S(C,P){const M=i,R=await F(_u,{runtimeContext:{miniProgramId:P,...await u()}});await _(C,M);const U=zu(ht(R,"用户本地身份"),c);for(const x of c?_t:Oc)n.add(x);return A("user_info_authorization_change",ri(n,c)),U}function T(C){b();const P=O(),M=`${C}\0${P}\0${i}\0${c}`;return r.read(M,()=>S(C,P))}async function V(C){if(!C)throw y("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const P=O(),M=i,R=await D();if(!R)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const U=await F(Iu,{runtimeContext:{miniProgramId:P,...await u()}});await _(R,M),ht(U,"用户授权撤销"),v(),A("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{login:w,getOrCreateLocalIdentity:T,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>ri(n,c),revoke:V,onEvent(C){return t.add(C),()=>t.delete(C)},dispose(){o||(o=!0,v(),r.dispose(),p(),t.clear())}}}function Vu(e,t,r){const n=y(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function ht(e,t){if(!B(e))throw y("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw y(n,r)}if(!B(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function is(e,t){if(!B(e))throw y("INVALID_RESPONSE","login code 必须是对象");const r=Sn(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!r.includes("identity"))throw y("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function qu(e,t){if(!B(e))throw y("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Sn(e.requestedScopes,"challenge requestedScopes",t),n=Sn(e.displayedScopes,"challenge displayedScopes",t);if(typeof e.challenge!="string"||!e.challenge.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!Number.isInteger(e.consentUiVersion)||Number(e.consentUiVersion)<0||!r.length||!r.includes("identity")||!n.length||!n.includes("identity")||r.some(i=>!n.includes(i)))throw y("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function zu(e,t){if(!B(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw y("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw y("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const n=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return n?{appUserId:r,steamId:n}:{appUserId:r}}function Gu(e,t,r){const n=Sn(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw y("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function bt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function ju(e){const t=bt(e?.name),r=bt(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function os(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(zi()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(zi()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function zi(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Sn(e,t,r){const n=r?Hu:Oc;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw y("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function ri(e,t){const r=t?_t:_t.filter(n=>n!==Ao);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function ss(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Wu(e){return B(e)?Object.values(e).some(t=>t==="denied"):!1}function Rc(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}function as(e,t,r){return t.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Rc(e)?e:y("REQUEST_FAILED",r)}const Ku=new Set(_t);function Yu(e){return{[Wr]:async(t,r)=>e.authorization.login(Qu(t),r.trustedUserGesture)}}function Qu(e){if(e===void 0)return["identity"];if(!B(e)||Object.keys(e).some(t=>t!=="scopes"))throw cs();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Ku.has(t))||new Set(e.scopes).size!==e.scopes.length)throw cs();return[...e.scopes]}function cs(){return y("INVALID_PARAMS","auth.login 参数不合法")}const Ju={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 ye(e,"排行榜记录删除接口响应异常")}},Xu={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 ye(e,"当前排行榜记录接口响应异常")}},Zu={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 ye(e,"排行榜信息接口响应异常")}},ef={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 ye(e,"排行榜列表接口响应异常")}},tf={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 ye(e,"排行榜提交接口响应异常")}};function kr(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function ds(e){return e instanceof se?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function te(e){if(e.aborted)throw kr()}function X(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(kr());let n;try{n=e()}catch(i){return Promise.reject(ds(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(kr())):new Promise((i,o)=>{let s=!1;const a=l=>{s||(s=!0,t.removeEventListener("abort",c),l())},c=()=>a(()=>o(kr()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(l=>a(()=>i(l)),l=>a(()=>o(ds(l))))})}const rf="default",nf=/^[A-Za-z0-9_-]{1,64}$/,of=300*1e3,sf=250,af=3,cf={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 df{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=uf(t.account,()=>this.invalidateForAccountChange()),t.operationContext.signal.aborted?this.dispose():t.operationContext.signal.addEventListener("abort",this.handleTerminalAbort,{once:!0})}accountGeneration=0;buckets=new Map;inflight=new Map;unsubscribeAccountChange;requestGateContext;disposed=!1;handleTerminalAbort=()=>this.dispose();async submit(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(tf,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=kt(i,ke);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),ni(o,ke)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Ut("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(ef,{miniProgramId:r,...t}),s=kt(o,Ie);if(!Te(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw ne(`${Ie} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw ne(`${Ie} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>ni(a,Ie)),...typeof s.cursor=="string"&&s.cursor?{cursor:s.cursor}:{},hasMore:s.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId(),i=await this.requireCurrentUser(r),o=this.createBucketKey(n,t.key),s=Ut("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(Xu,{miniProgramId:n,...t}),c=kt(a,ze);if(!Te(c))throw ne(`${ze} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:ni(c.entry,ze)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Ju,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=kt(i,st);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Te(o)||typeof o.deleted!="boolean")throw ne(`${st} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Ut("info"),async()=>{const i=await this.request(Zu,{miniProgramId:r,...t}),o=kt(i,De);if(!Te(o)||typeof o.key!="string"||!nf.test(o.key))throw ne(`${De} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw ne(`${De} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw ne(`${De} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw ne(`${De} 返回的 rankLimit 必须是非负整数`);return{key:o.key,order:o.order,rankLimit:o.rank_limit}})}read(t,r,n,i){this.assertUsable();const o=this.getOrCreateBucket(t),s=o?.caches[r],a=s?.get(n);if(a&&a.expiresAt>Date.now())return Promise.resolve(a.value);s?.delete(n);const c=Ut(t,n),l=this.inflight.get(c);if(l)return l.promise;const h=this.accountGeneration,g=o?.generation,u=i().then(p=>(this.assertAccountGeneration(h),o&&s&&o.generation===g&&(r==="list"?s.size>=sf&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+of,value:p})),p)).finally(()=>{this.inflight.get(c)?.promise===u&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:u}),u}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=af)return;const n={generation:0,caches:{list:new Map,current:new Map,info:new Map}};return this.buckets.set(t,n),n}invalidateMutableReads(t){this.invalidateInflight(t);const r=this.buckets.get(t);r&&(r.generation+=1,r.caches.list.clear(),r.caches.current.clear())}invalidateForAccountChange(){this.accountGeneration+=1,this.buckets.clear(),this.inflight.clear()}invalidateInflight(t){for(const[r,n]of this.inflight)n.bucketKey===t&&this.inflight.delete(r)}pruneExpiredBuckets(){const t=Date.now();for(const[r,n]of this.buckets)us(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){us(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await X(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw hs(n)?n:fs()}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw we("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw we("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Ut(t,r??rf)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw we("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){this.assertUsable();const n={request:async(i,o)=>(this.assertUsable(),this.options.network.request(i,o))};try{return await X(()=>Gn(n,t,r,{...this.options.operationContext,credentials:"heybox-session",...this.requestGateContext?{gate:this.requestGateContext}:{}}),this.options.operationContext.signal)}catch(i){if(hs(i)||Vt(i,"REQUEST_UNSUPPORTED")||Vt(i,"RATE_LIMITED")||Vt(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof se)throw we("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求");if(i instanceof vt&&Vt(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof St){if(this.options.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw we("RATE_LIMITED","排行榜请求已被网关限流,请稍后重试",{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw we("UNAUTHORIZED","当前用户未登录")}throw i instanceof vt||i instanceof St?fs():i instanceof gr?ne(i.cause instanceof Error?i.cause.message:"排行榜响应不合法"):ne(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(te(this.options.operationContext.signal),this.disposed)throw we("INVALID_STATE","Cloud capability 已释放")}}function lf(e){return new df(e)}function uf(e,t){try{return e.onChange(t)}catch(r){if(Vt(r,dc))return()=>{};throw r}}function kt(e,t){if(!Te(e)||typeof e.status!="string")throw ne(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw ff(e);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw ne(`${t} 响应缺少 result`);return e.result}function ni(e,t){if(!Te(e))throw ne(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw ne(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw ne(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw ne(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw ne(`${t} 返回的 score 必须是有限数字`);if(!Te(e.extra))throw ne(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw ne(`${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 ff(e){if(e.status==="login"||e.status==="relogin")throw we("UNAUTHORIZED",Bt(e.msg)||"当前用户未登录");const t=ls(e.result)??ls(e),r=Bt(t?.user_message)||Bt(e.msg)||Bt(t?.developer_message)||"排行榜请求失败";throw t?we(hf(t),r,{status:e.status,sbe:t}):we("HEYBOX_API_ERROR",r,{status:e.status})}function ls(e){return Te(e)&&Te(e.sbe)?e.sbe:void 0}function hf(e){const t=Bt(e.developer_message);if(t&&/^[A-Z][A-Z0-9_]+$/.test(t))return t;const r=e.code;if(typeof r=="number"&&Number.isInteger(r))return cf[r]||t||"HEYBOX_API_ERROR";if(typeof r=="string"){const n=/^([A-Za-z][A-Za-z0-9_]*)(?:\(\d+\))?$/.exec(r.trim());if(n?.[1])return n[1]}return t||"HEYBOX_API_ERROR"}function us(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Ut(...e){return JSON.stringify(e)}function Te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Vt(e,t){return Te(e)&&e.code===t}function we(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function ne(e){return we("INVALID_RESPONSE",e)}function fs(){return we("REQUEST_FAILED","排行榜请求失败")}function hs(e){return e instanceof Error&&e.name==="AbortError"}const mf=/^[A-Za-z0-9_-]{1,64}$/,ms=20,pf=100,ps=2048;function gf(e){const t=lf(e);return{handlers:{[ke]:async n=>t.submit(yf(n)),[Ie]:async n=>t.getList(Ef(n)),[ze]:async n=>t.getCurrentUserEntry(ii(n,ze)),[st]:async n=>t.deleteCurrentUserEntry(ii(n,st)),[De]:async n=>t.getInfo(ii(n,De))},dispose:()=>t.dispose()}}function yf(e){const t=bo(e,ke,!1);if(Io(t,["key","score","extra"],ke),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw Ce("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{..._o(t.key,ke),score:t.score,...t.extra===void 0?{}:{extra:wf(t.extra)}}}function Ef(e){if(e===void 0)return{limit:ms};const t=bo(e,Ie,!0);Io(t,["key","limit","cursor"],Ie);const r=t.limit===void 0?ms:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>pf)throw Ce("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw Ce("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{..._o(t.key,Ie),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function ii(e,t){if(e===void 0)return{};const r=bo(e,t,!0);return Io(r,["key"],t),_o(r.key,t)}function bo(e,t,r){if(e===void 0&&r)return{};if(!Pc(e))throw Ce("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Io(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Ce("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function _o(e,t){if(e===void 0)return{};if(typeof e!="string"||!mf.test(e))throw Ce("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function wf(e){if(!Pc(e))throw Ce("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw Ce("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw Ce("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>ps)throw Ce("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${ps} 字节`);return e}function Pc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ce(e,t){return{code:e,message:t}}const Af=new Set(["stdio","attachments","notifications"]),Nc=new Set(["windows-x64","macos-arm64"]),bf=new Set(["unsigned","valid","invalid","unknown"]),If=/^[a-f0-9]{64}$/,_f=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Sf=new Set(ac),vf=new Set([...ac,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Dc=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 Of(e){const t=async(n,i,o,s)=>{const a=Rf(n);try{Ne(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Ne(i.signal),c}catch(c){throw ji(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw y("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(l=>Pf(l,i)).catch(l=>{throw ji(l)});Ne(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Ne(o.signal),c.status!=="granted")throw y("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[Tn]:(n,i)=>t(n,i,async(o,s)=>Gi(await e.companion.getInfo(o,s),o)),[Cn]:(n,i)=>t(n,i,async(o,s)=>gs(await e.companion.getPreparationStatus(o,s))),[Ln]:(n,i)=>t(n,i,async(o,s)=>{const a=gs(await e.companion.getPreparationStatus(o,s));return Ne(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Ne(i.signal),Gi(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(Cc(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[Mn]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[kn]:(n,i)=>t(n,i,async(o,s)=>ys(await e.companion.getActiveSession(o,s),o)),[Un]:(n,i)=>t(n,i,async(o,s)=>{const a=ys(await e.companion.getActiveSession(o,s),o);return Ne(i.signal),a||(await r("launch",o,i),Ne(i.signal),Lc(await e.companion.launch(o,s),o))}),[xn]:(n,i)=>mt(n,i,e,"write"),[Hn]:(n,i)=>mt(n,i,e,"closeStdin"),[Fn]:(n,i)=>mt(n,i,e,"terminate"),[Bn]:(n,i)=>mt(n,i,e,"ackOutput"),[Vn]:async(n,i)=>{const o=await mt(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[qn]:(n,i)=>mt(n,i,e,"showNotification")}}function Rf(e){if(!B(e)||typeof e.alias!="string"||!bl.test(e.alias))throw y("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Ne(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function mt(e,t,r,n){if(!B(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw y("INVALID_PARAMS","Companion Session controller 不合法");try{Ne(t.signal);const i=await r.companion[n](Nf(e,n),{...r.operationContext,signal:t.signal});return Ne(t.signal),i}catch(i){throw ji(i)}}function Se(){throw y("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Tc(e){return!Array.isArray(e)||e.some(t=>!Af.has(t))?Se():Object.freeze([...new Set(e)])}function Gi(e,t){return!B(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Nc.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!bf.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?Se():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Tc(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function Pf(e,t){const r=Gi(e,t);return!B(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!If.test(e.sha256)?Se():Object.freeze({...r,sha256:e.sha256})}function Cc(e){return B(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):Se():Se()}function gs(e){return B(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Cc(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&B(e.error)&&typeof e.error.code=="string"&&Sf.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:Dc[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):Se():Se()}function Lc(e,t){return!B(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Nc.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?Se():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Tc(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function ys(e,t){return e===void 0?void 0:Lc(e,t)}function Nf(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!ic(r.data))throw y("INVALID_PARAMS","Companion write data 不合法");return{...n,data:new Uint8Array(r.data)}}if(t==="ackOutput"){if(r.stream!=="stdout"&&r.stream!=="stderr"||!Number.isSafeInteger(r.sequence)||Number(r.sequence)<0)throw y("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw y("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw y("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function Df(e){return!B(e)||!_f.has(String(e.reason))?Se():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):Se():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?Se():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Tf(e){if(!B(e)||!B(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,r=t.sessionId;if(e.type==="companion.session.output")return!Number.isSafeInteger(t.controllerGeneration)||Number(t.controllerGeneration)<0||t.stream!=="stdout"&&t.stream!=="stderr"||!Number.isSafeInteger(t.sequence)||Number(t.sequence)<0||!ic(t.data)?void 0:{type:e.type,payload:{sessionId:r,controllerGeneration:t.controllerGeneration,stream:t.stream,sequence:t.sequence,data:new Uint8Array(t.data)}};if(e.type==="companion.session.exit")try{return{type:e.type,payload:{sessionId:r,exit:Df(t.exit)}}}catch{return}if(e.type==="companion.session.ownershipLost"&&Number.isSafeInteger(t.controllerGeneration)&&Number(t.controllerGeneration)>=0)return{type:e.type,payload:{sessionId:r,controllerGeneration:t.controllerGeneration}}}function ji(e,t){return B(e)&&typeof e.code=="string"&&vf.has(e.code)?y(e.code,Dc[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&B(e)&&e.name==="AbortError"?y(t,"Companion 准备已取消"):y("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Es=5e3,ws=1e4;function le(e){throw{code:"INVALID_PARAMS",message:e}}function So(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mc(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&le(`${r} 不支持字段: ${n.join(", ")}`)}function Cf(e){if(e===void 0)return{intensity:"light",delay:0};if(!So(e))return le("device.vibrate 参数必须是对象");Mc(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return le("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Es?le(`device.vibrate delay 必须是 0-${Es} 的整数毫秒`):{intensity:r,delay:n}}function Lf(e){return So(e)?(Mc(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?le("device.setClipboard text 必须是非空字符串"):e.text.length>ws?le(`device.setClipboard text 不能超过 ${ws} 字符`):{text:e.text}):le("device.setClipboard 参数必须是对象")}function Mf(e){return typeof e=="string"?e.trim()?e:le("device.executeProtocol 协议字符串不能为空"):So(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?le("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):($i(e,new Set),e):le("device.executeProtocol 参数必须是协议字符串或协议对象")}function $i(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||le("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":le("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":le(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&le("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)$i(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&le("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))$i(i,t);t.delete(r)}function kf(e){return{[En]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.vibrate(Cf(t),e.operationContext),e.operationContext.signal)},[wn]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.setClipboard(Lf(t),e.operationContext),e.operationContext.signal)},[An]:async(t,r)=>{const n=Tt(e.operationContext,r.signal);te(n.signal);const i=Mf(t);await X(()=>e.protocol.invoke(i,n),n.signal)}}}const Uf=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"]),xf={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 cr(e){const t=vo(e),r=t&&Uf.has(t)?y(t,xf[t]??"文件操作失败"):y("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Me(e){try{return e()}catch(t){throw cr(t)}}function vo(e){try{if(!B(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function kc(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:n,create:i?(s,a)=>e.create(s,a):Wi,remove:o?s=>e.remove(s):xc,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Wi,stat:s=>e.stat(s)})}function Uc(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1,s=o&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:n,file:a=>kc(e.file(a),n,{allowRemove:o}),directory:a=>Uc(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Wi,remove:s?(a,c)=>e.remove(a,c):xc,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Wi(){return Promise.reject(y("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function xc(){return Promise.reject(y("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const As=1024;class Hf{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareFile(t,r,n),[o]=this.registerMany([i]);return vr(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Me(()=>{if(!Array.isArray(t))throw y("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw y("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>As)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let l=0;l<a;l+=1){if(!Object.prototype.hasOwnProperty.call(t,l))throw y("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[l],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>vr(a.handle,{kind:"file",handleId:s[c]}))}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[o]=this.registerMany([i]);return Is(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!zn(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Bf(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=dr(r.relativePath),o=this.prepareFile(Me(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Vf(t);if("handleId"in r){const s=this.readDirect(r.handleId,"directory");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=r.relativePath==="."?".":dr(r.relativePath),o=this.prepareDirectory(i==="."?n.hostHandle:Me(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Ss(t),vr(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Me(()=>{if(!Array.isArray(r))throw y("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw y("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw y("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,r[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Me(()=>{if(B(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return vr(n.handle,bs(t.ref,n.handle.name))}if(B(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return Is(n.handle,Ff(t.ref,n.handle.name))}throw y("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=yr(r),i=this.prepareFile(Me(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:bs(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw y("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Me(()=>{Ss(t);const i=n??t.mode;return _s(t.mode,i),{handle:kc(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Me(()=>{Gf(t,i);const o=n??t.mode;return _s(t.mode,o),{handle:Uc(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>As)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=qf();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw y("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!zf(t))throw y("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw y("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw y("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw _e("files.sandbox");return this.prepareDirectory(Me(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw y("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw _e("files")}}function dr(e){if(!yo(e))throw y("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function yr(e,t="文件名"){const r=dr(e);if(r.includes("/"))throw y("INVALID_PARAMS",`${t} 只能是 basename`);return r}function bs(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:dr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Ff(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:dr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function vr(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function Is(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function _s(e,t){if(t==="readwrite"&&e!=="readwrite")throw y("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Bf(e){return zn(e)||Hc(),e}function Vf(e){return nc(e)||Hc(),e}function Hc(){throw y("INVALID_PARAMS","文件引用不合法")}function qf(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw y("FILE_IO_FAILED","当前环境缺少安全随机数能力");const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function zf(e){return/^[0-9a-f]{32}$/.test(e)}function Ss(e){if(!B(e)||e.kind!=="file"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.create!="function"||typeof e.read!="function"||typeof e.write!="function"||typeof e.stat!="function")throw y("FILE_IO_FAILED","Host 返回了无效 File handle");yr(e.name,"Host File name")}function Gf(e,t=!1){if(!B(e)||e.kind!=="directory"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.file!="function"||typeof e.directory!="function"||typeof e.create!="function"||typeof e.stat!="function"||typeof e.list!="function")throw y("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw y("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&yr(e.name,"Host Directory name")}const vs=1e3,jf=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function $f(e){const t=r=>Tt(e.operationContext,r.signal);return{files:{[sn]:async(r,n)=>{oi(n);const i=si(e.picker),o=Wf(r),s=await me(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[an]:async(r,n)=>{oi(n);const i=si(e.picker),o=Kf(r),s=await me(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[cn]:async(r,n)=>{oi(n);const i=si(e.picker),o=Yf(r).suggestedName,s=t(n);if(!i.saveFile)throw _e("files.saveFile");const a=await me(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[tr]:async(r,n)=>{const i=Ee(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);pt(o.mode),await me(()=>o.create(Os(i),t(n)))},[rr]:async(r,n)=>{const i=Ee(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),pt(o.handle.mode),!o.handle.remove)throw _e(rr);await me(()=>o.handle.remove(t(n)))},[dn]:async(r,n)=>{const i=Ee(r);return Rs(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!B(o)||o.kind!=="file")throw Ns()})},[nr]:async(r,n)=>{const i=Ee(r),o=Ps(await me(()=>e.registry.resolveFile(i.target).read(t(n))));try{const s=new TextDecoder("utf-8",{fatal:!0}).decode(o);return s.charCodeAt(0)===65279?s.slice(1):s}catch{throw y("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[ln]:async(r,n)=>{const i=Ee(r,["content"]);typeof i.content!="string"&&be("content 必须是字符串");const o=e.registry.resolveFile(i.target);pt(o.mode),await me(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[ir]:async(r,n)=>{const i=Ee(r),o=await me(()=>e.registry.resolveFile(i.target).read(t(n)));return Ps(o)},[un]:async(r,n)=>{const i=Ee(r,["content"]),o=e.registry.resolveFile(i.target);pt(o.mode),await me(()=>o.write(Jf(i.content),t(n)))},[or]:async(r,n)=>{const i=Ee(r),o=await me(()=>e.registry.resolveFile(i.target).stat(t(n)));return Xf(o)}},directory:{[fn]:async(r,n)=>{const i=Ee(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);pt(o.mode),await me(()=>o.create(Os(i),t(n)))},[sr]:async(r,n)=>{const i=Ee(r,["recursive"]);if(B(i.target)&&i.target.relativePath===".")throw y("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),pt(o.handle.mode),!o.handle.remove)throw _e(sr);await me(()=>o.handle.remove({recursive:i.recursive===void 0?!1:vn(i.recursive,"recursive")},t(n)))},[hn]:async(r,n)=>{const i=Ee(r);return Rs(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!B(o)||o.kind!=="directory")throw Ns()})},[mn]:async(r,n)=>{const i=Ee(r,["limit"]),o=Qf(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await me(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function Wf(e){if(e===void 0)return{mode:"read",multiple:!1};B(e)||be("pickFiles 参数必须是对象"),jn(e,["mode","accept","multiple"]);const t=Fc(e.mode,"read"),r=e.multiple===void 0?!1:vn(e.multiple,"multiple");let n;return e.accept!==void 0&&((!Array.isArray(e.accept)||e.accept.some(i=>typeof i!="string"||!/^\.[a-z0-9][a-z0-9._-]*$/i.test(i)))&&be("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function Kf(e){return e===void 0?{mode:"read"}:(B(e)||be("pickDirectory 参数必须是对象"),jn(e,["mode"]),{mode:Fc(e.mode,"read")})}function Yf(e){return B(e)||be("saveFile 参数必须是对象"),jn(e,["suggestedName"]),{suggestedName:yr(e.suggestedName,"suggestedName")}}function Ee(e,t=[]){return(!B(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&be("文件操作参数必须包含 target"),jn(e,["target",...t]),e}function Os(e){return{recursive:e.recursive===void 0?!1:vn(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:vn(e.exclusive,"exclusive")}}function Fc(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&be("mode 必须是 read 或 readwrite"),e)}function vn(e,t){return typeof e!="boolean"&&be(`${t} 必须是布尔值`),e}function Qf(e){if(e===void 0)return vs;if((!Number.isSafeInteger(e)||e<=0)&&be("limit 必须是正整数"),e>vs)throw y("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function jn(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&be(`不支持字段: ${r.join(", ")}`)}function pt(e){if(e!=="readwrite")throw y("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function oi(e){if(!e.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function si(e){if(!e)throw _e("files.external");return e}async function Rs(e){try{return await e(),!0}catch(t){if(jf.has(vo(t)??""))return!1;throw cr(t)}}async function me(e){try{return await e()}catch(t){throw cr(t)}}function Jf(e){return e instanceof Uint8Array||be("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&be("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Ps(e){if(!(e instanceof Uint8Array))throw y("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Ns(){return y("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Xf(e){if(!B(e)||e.kind!=="file"||!Zf(e.size))throw y("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!eh(e[t]))throw y("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 Zf(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function eh(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function be(e){throw y("INVALID_PARAMS",e)}const Or=4294967296;function th(e){const t=new rh;return t.write(e),t.finish()}class rh{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<Or?(this.writeUint8(206),this.writeUint32(t)):(this.writeUint8(207),this.writeUint64(t));return}t>=-32?this.writeUint8(224|t+32):t>=-128?(this.writeUint8(208),this.writeInt8(t)):t>=-32768?(this.writeUint8(209),this.writeInt16(t)):t>=-2147483648?(this.writeUint8(210),this.writeInt32(t)):(this.writeUint8(211),this.writeInt64(t))}writeString(t){const r=nh(t),n=r.byteLength;if(n<32)this.writeUint8(160+n);else if(n<256)this.writeUint8(217),this.writeUint8(n);else if(n<65536)this.writeUint8(218),this.writeUint16(n);else if(n<Or)this.writeUint8(219),this.writeUint32(n);else throw new Error("share extra string is too long");this.writeBytes(r)}writeArray(t){const r=t.length;r<16?this.writeUint8(144+r):r<65536?(this.writeUint8(220),this.writeUint16(r)):(this.writeUint8(221),this.writeUint32(r));for(const n of t)this.write(n)}writeMap(t){const r=Object.keys(t),n=r.length;n<16?this.writeUint8(128+n):n<65536?(this.writeUint8(222),this.writeUint16(n)):(this.writeUint8(223),this.writeUint32(n));for(const i of r)this.writeString(i),this.write(t[i])}ensureCapacity(t){const r=this.offset+t;if(r<=this.bytes.byteLength)return;const n=new Uint8Array(Math.max(r,this.bytes.byteLength*2));n.set(this.bytes),this.bytes=n,this.view=new DataView(n.buffer)}writeBytes(t){this.ensureCapacity(t.byteLength),this.bytes.set(t,this.offset),this.offset+=t.byteLength}writeUint8(t){this.ensureCapacity(1),this.view.setUint8(this.offset,t),this.offset+=1}writeInt8(t){this.ensureCapacity(1),this.view.setInt8(this.offset,t),this.offset+=1}writeUint16(t){this.ensureCapacity(2),this.view.setUint16(this.offset,t),this.offset+=2}writeInt16(t){this.ensureCapacity(2),this.view.setInt16(this.offset,t),this.offset+=2}writeUint32(t){this.ensureCapacity(4),this.view.setUint32(this.offset,t),this.offset+=4}writeInt32(t){this.ensureCapacity(4),this.view.setInt32(this.offset,t),this.offset+=4}writeFloat64(t){this.ensureCapacity(8),this.view.setFloat64(this.offset,t),this.offset+=8}writeUint64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,t/Or),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Or)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function nh(e){const t=new Uint8Array(ih(e));let r=0,n=0;for(;r<e.length;){let i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<e.length){const o=e.charCodeAt(r);o>=56320&&o<=57343&&(r+=1,i=((i&1023)<<10)+(o&1023)+65536)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6&31|192,t[n++]=i&63|128):i<65536?(t[n++]=i>>12&15|224,t[n++]=i>>6&63|128,t[n++]=i&63|128):(t[n++]=i>>18&7|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=i&63|128)}return t}function ih(e){let t=0,r=0;for(;r<e.length;){let n=e.charCodeAt(r++);if(n<128)t+=1;else if(n<2048)t+=2;else{if(n>=55296&&n<=56319&&r<e.length){const i=e.charCodeAt(r);i>=56320&&i<=57343&&(r+=1,n=((n&1023)<<10)+(i&1023)+65536)}t+=n<65536?3:4}}return t}function Bc(e){Ki(e);const t=th(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 Ki(e,t=0,r=new WeakSet){if(t>8)throw new Error("extra nesting depth exceeded");if(e===null||typeof e=="string"||typeof e=="boolean")return;if(typeof e=="number"){if(Number.isFinite(e))return;throw new Error("extra number must be finite")}if(typeof e!="object")throw new Error("extra value must be JSON-compatible");if(r.has(e))throw new Error("extra value must not contain cycles");if(r.add(e),Array.isArray(e)){if(e.length>64)throw new Error("extra array is too large");for(const o of e)Ki(o,t+1,r);r.delete(e);return}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new Error("extra object must be a plain object");const i=Object.entries(e);if(i.length>64)throw new Error("extra object has too many fields");for(const[o,s]of i){if(o==="__proto__")throw new Error("extra object key is not supported");Ki(s,t+1,r)}r.delete(e)}const oh=["pc","console","mobile"],sh=["game","wiki"];function On(e){throw{code:"INVALID_PARAMS",message:e}}function ah(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function je(e,t){return typeof e!="string"||!e.trim()?On(t):e.trim()}function Ds(e,t,r){return typeof e!="string"||!t.includes(e)?On(r):e}function ch(e){const t={target:"game_detail",appId:je(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Ds(e.gameType,oh,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Ds(e.page,sh,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=je(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=je(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function dh(e){return{target:"user_detail",userId:je(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function lh(e){const t={target:"post_detail",linkId:je(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=je(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=je(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function uh(e){const t={target:"mini_program",miniProgramId:je(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function fh(e){return ah(e)?e.target==="game_detail"?ch(e):e.target==="user_detail"?dh(e):e.target==="post_detail"?lh(e):e.target==="mini_program"?uh(e):On("navigation.openAppPage target 不支持"):On("navigation.openAppPage options 必须是对象")}function hh(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 mh(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function ph(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 gh(e){const t=e;return t.target==="game_detail"?hh(t):t.target==="user_detail"?mh(t):ph(t)}const yh="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",Eh="data-hb-sdk-fullscreen-exit",wh=3e3,Ah=2e3,Ts="var(--white-70a,rgba(255,255,255,.7))",Cs="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function bh(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(Eh,""),t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true");const r=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;t.style.cssText=["position:fixed","right:0","top:50%","z-index:2147483647","box-sizing:border-box","width:48px","height:44px","padding:5px 0",`border:1px solid ${Ts}`,`box-shadow:${Cs}`,"border-radius:var(--radius-m-token,5px)","display:flex","flex-direction:column","align-items:center","justify-content:center","gap:3px","background:var(--general-color-text-2,#64696e)","color:var(--white-100a,#fff)",'font:400 var(--font-size-9,9px)/var(--line-height-12,12px) "PingFang SC",sans-serif',"cursor:pointer","touch-action:manipulation","opacity:1","transform:translateY(-50%)",r?"transition:none":"transition:width var(--token-transition-arrow,220ms cubic-bezier(.2,.8,.2,1))"].join(";");const n=document.createElement("img");n.src=yh,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let o=!0,s=!1,a=!1,c,l;function h(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function g(){o||(t.style.width=h())}function u(){l?.cancel(),l=void 0}function p(O=Ah){clearTimeout(c),c=setTimeout(()=>{u(),o=!1,t.style.width=h(),t.style.opacity="0.5",t.style.borderColor="var(--white-40a,rgba(255,255,255,.4))",t.style.boxShadow="none",n.style.visibility="hidden",i.style.display="none",t.setAttribute("aria-label","展开退出全屏按钮"),t.setAttribute("aria-expanded","false")},O)}function v(){u(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Ts,t.style.boxShadow=Cs,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),p()}async function A(){if(!(s||a)){if(!o){v();return}a=!0,clearTimeout(c),u();try{await e()}catch{}finally{a=!1,s||v()}}}return t.addEventListener("click",A),window.addEventListener("resize",g),document.body.append(t),!r&&t.animate&&(l=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),p(wh),{dispose(){s=!0,clearTimeout(c),u(),t.removeEventListener("click",A),window.removeEventListener("resize",g),t.remove()}}}const Vc=1e4;function qc(e){const t=new AbortController;let r;const n=()=>{r??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},t.abort()};e.addEventListener("abort",n,{once:!0}),e.aborted&&n();const i=setTimeout(()=>{r??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},t.abort()},Vc);return{signal:t.signal,async run(o){try{return await X(o,t.signal)}catch(s){throw r??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",n)}}}function zc(e){if(typeof e!="object"||e===null||Array.isArray(e))throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 参数必须是对象"};const{orientation:t,fullscreen:r}=e;if(t!==void 0&&t!=="portrait"&&t!=="landscape")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay orientation 必须是 portrait 或 landscape"};if(r!==void 0&&typeof r!="boolean")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay fullscreen 必须是布尔值"};if(t===void 0&&r===void 0)throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 至少设置 orientation 或 fullscreen"};return{orientation:t,fullscreen:r}}function ai(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Rr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function Ih(e){let t,r,n={mode:"portrait",hideCapsule:!1},i={mode:"portrait",hideCapsule:!1},o;function s(){o?.dispose(),o=void 0}function a(u){if(!u.hideCapsule){s();return}o??=bh(()=>g.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(u,p){if(t===u){if(t=void 0,clearTimeout(u.timer),e.operationContext.signal.removeEventListener("abort",l),"error"in p)u.controller.abort();else if(r={options:u.options,result:p.result},n=u.options,a(u.options),e.onApplied?.(u.options),p.result.supported&&!ai(i,u.options)){i={...u.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:u.source})}catch{}}for(const v of u.subscribers)v.dispose(),"error"in p?v.reject(p.error):v.resolve(p.result);u.subscribers.clear()}}function l(){t&&c(t,{error:Rr()})}function h(u,p){return new Promise((v,A)=>{const O=()=>{u.subscribers.delete(b),b.dispose(),A(Rr()),u.subscribers.size===0&&c(u,{error:Rr()})},b={resolve:v,reject:A,dispose:()=>p?.removeEventListener("abort",O)};u.subscribers.add(b),p?.addEventListener("abort",O,{once:!0}),p?.aborted&&O()})}const g={async apply(u,p,v="api"){if(te(e.operationContext.signal),p?.aborted)throw Rr();const A=zc(u),O=t?.options??n,b={mode:A.orientation??O.mode,hideCapsule:A.fullscreen??O.hideCapsule};b.mode==="landscape"&&(b.hideCapsule=!0);const D=e.presentation.applyOrientation;if(!D)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&ai(t.options,b))return h(t,p);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),r&&ai(r.options,b))return r.result;r=void 0;const _={options:b,source:v,controller:new AbortController,subscribers:new Set};t=_;const L=h(_,p);return e.operationContext.signal.addEventListener("abort",l,{once:!0}),p||(_.timer=setTimeout(()=>{c(_,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Vc)),X(()=>D.call(e.presentation,b,{...e.operationContext,signal:_.controller.signal}),_.controller.signal).then(F=>c(_,{result:F??{supported:!0}}),F=>c(_,{error:F})),L},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return g}function Gc(e){throw{code:"INVALID_PARAMS",message:e}}function Ls(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Gc(`${t} 不支持参数`)}function _h(e){return{[bn]:async t=>{te(e.operationContext.signal),Ls(t,"navigation.close"),await X(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[In]:async t=>{te(e.operationContext.signal),Ls(t,"navigation.reload"),await X(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[_n]:async(t,r)=>{const n=Tt(e.operationContext,r?.signal);te(n.signal);const i=fh(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Bc(i.extra)}catch{Gc("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=qc(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}te(n.signal),await X(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await X(()=>e.presentation.openAppPage(gh(i),n),n.signal)}}}const Sh=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),vh=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Oh=new Set(["range","if-range","a-im"]),Rh=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"]),Ph=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Pr={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Nh{constructor(t){this.signal=t}phase="initial";transition(t){if(Pr[t]<=Pr[this.phase])throw y("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Pr[this.phase]<Pr.committed&&this.signal.aborted)throw $c()}normalizeHostError(t,r){return this.throwIfCancelled(),Ro(t,r,this.signal)}}async function Dh(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw _e("network.download");const o=Tt(r.operationContext,t.signal),s=new Nh(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Mh(e,i,o)}catch(h){throw s.normalizeHostError(h,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(h){throw s.normalizeHostError(h,"network")}let l=!1;try{s.throwIfCancelled(),s.transition("validate");const h=Uh(c);xh(c,h);const g=Hh(c.status,h);if(e.maxBytes!==void 0&&g.expectedBytes!==void 0&&g.expectedBytes>e.maxBytes)throw y("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const u=kh(e,a,h,i);let p=0;const v=Ch(g.expectedBytes,e.maxBytes);di(t,ci(0,g));const A={...o,onProgress(D){!Number.isSafeInteger(D)||D<p||v!==void 0&&D>v||(p=D,di(t,ci(p,g)))}};s.transition("transfer"),l=!0;let O;try{O=await n.files.writeResource(u.hostHandle,c.body,{mode:u.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...g.expectedBytes===void 0?{}:{expectedBytes:g.expectedBytes}},A)}catch(D){throw s.normalizeHostError(D,"transfer")}s.transition("committed"),p=Th(O,g,p,e.maxBytes),di(t,ci(p,g));const b=i.describeFile(u.handle,u.ref);return s.transition("completed"),b}finally{l||Lh(n.network,c.body)}}function Th(e,t,r,n){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=n===void 0?r:Math.min(r,n);try{const o=e?.committedBytes;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=i&&(n===void 0||o<=n))return o}catch{}return i}function Ch(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Lh(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Mh(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Yi(i.handle.mode),await jh(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Yi(n.handle.mode),await $h(n.handle,r),{kind:"directory",...n}}function kh(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Bh(e,r),o=n.deriveFile(t,i);return Yi(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Uh(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 y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!B(e.headers))throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!Sh.has(r)||!Array.isArray(n)||n.length===0)throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function xh(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw y("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:Gh(t,vh)});if((t["content-range"]?.length??0)>0)throw y("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Hh(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw y("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(l=>l!=="0"))throw y("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw y("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=Fh(t["content-encoding"]),a=e===204||e===205?0:n.length===0&&s?o:void 0,c=a!==void 0;return{...a===void 0?{}:{expectedBytes:a},...c?{total:a}:{},lengthComputable:c}}function Fh(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function ci(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function di(e,t){try{e.postProgress(t)}catch{}}function Bh(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=Vh(i);if(o&&Ur(o))return o}for(const i of r){const o=qh(i);if(o&&Ur(o))return o}if(e.suggestedName!==void 0)return Oo(e.suggestedName);const n=zh(e.url);return n&&Ur(n)?n:"download.bin"}function Vh(e){const t=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(e);if(!t)return;const r=t[1].trim().replace(/^"|"$/g,""),n=/^utf-8'[^']*'(.*)$/i.exec(r);if(n)try{return decodeURIComponent(n[1])}catch{return}}function qh(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 zh(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Oo(e){try{yr(e,"suggestedName")}catch{throw y("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Ur(e))throw y("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Ur(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Ph.test(e))}function Gh(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function jh(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw jc()}catch(r){throw Ro(r,"file",t.signal)}}async function $h(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw jc()}catch(r){throw Ro(r,"file",t.signal)}}function Yi(e){if(e!=="readwrite")throw y("FILE_ACCESS_DENIED","下载目标只允许读取")}const Wh={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 Ro(e,t,r){if(r.aborted)return $c();const n=Kh(e);if(n&&Rh.has(n)){const o=y(n,Wh[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?y("DOWNLOAD_TIMEOUT","下载网络请求超时"):y("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?y("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):y("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function Kh(e){return B(e)&&typeof e.code=="string"?e.code:void 0}function jc(){return y("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function $c(){return y("DOWNLOAD_CANCELLED","下载已取消")}function Yh(e){if(!e)return;const t=Object.keys(e).find(r=>Oh.has(r.trim().toLowerCase()));if(t)throw y("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Ms={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function Qh(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw _e("network.upload");const o=Tt(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw y("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(u){throw s(),cr(u)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw y("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw y("FILE_TOO_LARGE","文件超过大小限制");let l=0,h=!1;const g=u=>{h||o.signal.aborted||!Number.isSafeInteger(u)||u<l||u>c.size||(l=u,t.postProgress({loaded:l,total:c.size,lengthComputable:!0}))};try{const{from:u,...p}=e,v=await n.upload(a,{...p,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:g});if(h=!0,!Number.isSafeInteger(v.uploadedBytes)||v.uploadedBytes<l||v.uploadedBytes>c.size)throw y("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(v.status>=200&&v.status<300&&v.uploadedBytes!==c.size)throw y("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:v.uploadedBytes,total:c.size,lengthComputable:!0}),v}catch(u){h=!0;const p=vo(u);throw p&&Ms[p]?y(p,Ms[p]):o.signal.aborted?y("UPLOAD_CANCELLED","上传已取消"):p?.startsWith("FILE_")||p?.startsWith("DIRECTORY_")?cr(u):y("UPLOAD_NETWORK_FAILED","上传网络失败")}}const Po="withCredentials",Jh=new Set(["url","method","params","data","headers","timeout",Po]),Xh=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Po]),Zh=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),ks=3e4,Qi=2*1024*1024,em=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Wc=/[\u0000-\u0008\u000A-\u001F\u007F]/,tm=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,rm="network.request 不支持 multipart/form-data,请使用专用上传能力";function nm(e){const t=im(e.runtimePermissions),r=Em(e.allowedHttpOrigins);return{[on]:async(n,i)=>{const o=sm(n,{permission:t,allowedHttpOrigins:r}),s=await Qh(o,i,e),{uploadedBytes:a,...c}=s;return xs(c)},[nn]:async(n,i)=>{const o=am(n,{permission:t,allowedHttpOrigins:r});return Dh(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[rn]:async(n,i)=>{const o=Tt(e.operationContext,i?.signal);te(o.signal);const s=om(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await X(()=>e.network.request(s,o),o.signal)}catch(c){throw Am(c)?c:bm(c,"REQUEST_UNSUPPORTED")?q("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):q("REQUEST_FAILED","网络请求失败")}return xs(a)}}}function im(e){const t=Je(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function om(e,t){const r=Ot(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!Jh.has(c));if(n.length>0)throw q("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Kc(r,"network.request");const i=No(r,t,"network.request"),o=dm(r.method),s=r.data;s!==void 0&&fm(s),mm(i.headers,s);const a=pm(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 sm(e,t){const r=Ot(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(h=>!n.has(h)))throw q("INVALID_PARAMS","network.upload 包含不支持的字段");const i=No(r,t,"network.upload");if(i.official)throw q("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw q("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!zn(r.from))throw q("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw q("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw q("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw q("INVALID_PARAMS","上传 HTTP 方法不支持");const s={from:r.from,format:r.format,request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"upload",method:o,...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}};if(r.format==="raw"){if(["fieldName","fields","fileName","contentType"].some(h=>r[h]!==void 0))throw q("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(h=>h.toLowerCase()==="content-type"))throw q("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=Us(r.fieldName),c=r.fields===void 0?void 0:Ot(r.fields,"fields 必须是字符串字典");for(const[h,g]of Object.entries(c??{}))if(Us(h),typeof g!="string"||h===a)throw q("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw q("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||Wc.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw q("INVALID_PARAMS","contentType 必须是有效 MIME type");const l={fieldName:a,fields:c,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(l)).byteLength>Qi)throw q("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:Oo(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function Us(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw q("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function am(e,t){const r=Ot(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!Xh.has(c));if(n.length>0)throw q("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Kc(r,"network.download");const i=No(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw q("INVALID_PARAMS","network.download timeout 必须是有限正数");Yh(i.headers);const o=zn(r.to),s=nc(r.to);if(!o&&!s)throw q("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw q("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw q("INVALID_PARAMS","suggestedName 必须是字符串");a=Oo(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw q("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw q("INVALID_PARAMS","maxBytes 必须是正的 safe integer");return{request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"download",method:"GET",...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},url:i.url,to:r.to,targetKind:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function No(e,t,r){const n=cm(e.url,t.allowedHttpOrigins,r),i=Jl(n);if(i&&!t.permission.useOfficialDomain)throw q("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(Ql(n.pathname,i))throw q("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Ot(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:lm(e.headers,r),timeout:um(e.timeout,r)}}function cm(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw q("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw q("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw q("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function dm(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw q("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!Zh.has(t))throw q("INVALID_PARAMS","network.request method 不合法");return t}function lm(e,t="network.request"){const r=Ot(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!em.test(s)||typeof o!="string"||Wc.test(o))throw q("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Xl(s))throw q("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function Kc(e,t){const r=e[Po];if(r!==void 0&&typeof r!="boolean")throw q("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function um(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw q("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>ks)throw q("INVALID_PARAMS",`${t} timeout 不能超过 ${ks}ms`);return e}}function fm(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw q("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(hm(e)>Qi)throw q("INVALID_PARAMS",`network.request data 不能超过 ${Qi} 字节`)}function hm(e){if(typeof e=="string")return li(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return li(e.toString());try{const t=JSON.stringify(e);return t?li(t):0}catch{throw q("INVALID_PARAMS","network.request data 必须可序列化")}}function mm(e,t){const r=Yc(e),n=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(r?.includes("multipart/form-data")||n)throw q("INVALID_PARAMS",rm)}function pm(e,t,r){if(t===void 0)return;const n=Yc(e);return n?.includes("application/x-www-form-urlencoded")?"form":n?.includes("application/json")?"json":typeof URLSearchParams<"u"&&t instanceof URLSearchParams||r&&(Array.isArray(t)||ym(t))?"form":gm(t)?"json":void 0}function Yc(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function gm(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function ym(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Em(e){const t=new Set;for(const r of e??[])try{const n=new URL(r);n.protocol==="http:"&&!n.username&&!n.password&&n.pathname==="/"&&!n.search&&!n.hash&&wm(n.hostname)&&t.add(n.origin)}catch{}return t}function wm(e){const t=e.toLowerCase();if(t==="[::1]")return!0;const r=t.split(".").map(Number);return r.length!==4||r.some((n,i)=>!/^\d+$/.test(t.split(".")[i])||n<0||n>255)?!1:r[0]===127||r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}function xs(e){return Object.keys(e.headers).some(Hs)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Hs(t)))}:e}function Hs(e){const t=e.trim().toLowerCase();return tm.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Am(e){return e instanceof Error&&e.name==="AbortError"}function bm(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Ot(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw q("INVALID_PARAMS",t);return e}function li(e){return new TextEncoder().encode(e).length}function q(e,t){return{code:e,message:t}}function Im(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _m(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 Sm(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topicIds 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const o=_m(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function vm(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topics 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const o=typeof i=="string"?i.trim():"";!o||o.startsWith("#")||o.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):r.has(o)||(r.add(o),n.push(o))}return{invalidMessages:t,values:n}}function Qc(e,t){if(e==null)return{};if(!Im(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=Sm(e.topicIds),n=vm(e.topics),i=[...r.invalidMessages,...n.invalidMessages];let o=r.values;t.maxTopicIds!==void 0&&o.length>t.maxTopicIds&&(i.push(`${t.method} post.topicIds 最多允许 ${t.maxTopicIds} 项`),o=o.slice(0,t.maxTopicIds));const s=o.length||n.values.length?{...o.length?{topicIds:o}:{},...n.values.length?{topics:n.values}:{}}:void 0;return s||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:s}}function Om(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function Rm(e){try{if(Om(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function de(e){throw{code:"INVALID_PARAMS",message:e}}function Er(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ji(e,t){return typeof e!="string"||!e.trim()?de(t):e}function Pm(e,t){const r=Ji(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?de(t):r}catch{return de(t)}}function Nm(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Jc(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return de(`${t} 缺少有效的小程序分享地址`);try{const o=new URL(e.environment.getCurrentHref()),s=new URL("/tools/common_share",o);s.searchParams.set("user_miniprogram_id",i);const a=n?.version?.trim();a&&s.searchParams.set("miniprogram_version",a);const c=o.searchParams.get("h_src");return c?.trim()&&s.searchParams.set("h_src",c),r!==void 0&&s.searchParams.set("extra",r),s.href}catch{return de(`${t} 缺少有效的小程序分享地址`)}}function Dm(e,t){if(!Er(e))return de("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return de("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!Nm(r))return de("share.showShareMenu channel 不合法");const n=Xc(e.extra,"share.showShareMenu");return{title:Ji(e.title,"share.showShareMenu title 必须是非空字符串"),description:Ji(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Jc(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:Pm(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Xc(e,t){if(e!==void 0)try{return Bc(e)}catch{return de(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function Zc(e,t){return e.invalidMessage&&await X(()=>Rm(t.environment),t.operationContext.signal)?de(e.invalidMessage):e.post}function Fs(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Tm(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Fs(t.windowWidth,0),height:Fs(t.windowHeight,0)}}function Xi(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?de(t):r}function Bs(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?de(t):r}function Cm(e){return Er(e)?{left:Xi(e.left,"share.screenshot rect.left 必须是非负数字"),top:Xi(e.top,"share.screenshot rect.top 必须是非负数字"),width:Bs(e.width,"share.screenshot rect.width 必须是正数"),height:Bs(e.height,"share.screenshot rect.height 必须是正数")}:de("share.screenshot rect 必须是对象")}function Lm(e,t){if(e!=null&&!Er(e))return de("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?de("share.screenshot saveToAlbum 必须是布尔值"):{rect:r.rect===void 0?Tm(t):Cm(r.rect),...r.delay===void 0?{}:{delay:Xi(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function Mm(e,t){te(t.operationContext.signal);const r=Dm(e,t);let n=Qc(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await Zc(n,t);return X(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function km(e,t){if(te(t.operationContext.signal),e!==void 0&&!Er(e))return de("share.copyLink 参数必须是对象");const r=Xc(e?.extra,"share.copyLink"),n=Jc(t,"share.copyLink",r);return await X(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Um(e,t){te(t.operationContext.signal);const r=Lm(e,t.presentation),n=Qc(Er(e)?e.post:void 0,{method:"share.screenshot"}),i=await Zc(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=xm();let a=!1,c;try{a=!0,await X(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),c={status:"fulfilled",value:await X(()=>t.presentation.captureAndShare({...r,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(h){c={status:"rejected",error:h}}const l=a?await Hm(t.presentation,s,t.operationContext.signal):void 0;if(c.status==="rejected")throw c.error;if(l)throw l;return c.value}function xm(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Hm(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await X(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function Fm(e){return{[Jr]:(t,r)=>km(t,e),[Xr]:(t,r)=>Mm(t,e),[Zr]:(t,r)=>Um(t,e)}}const Bm=128,Vm=/^[A-Za-z0-9_-]+$/;function qm(e){const t=zm(e),r={[Zt]:async n=>{te(e.operationContext.signal);const i=Vs(n,Zt,e.storageLimits?.maxKeyLength),o=await X(()=>e.storage.getRaw(ui(t(),i),e.operationContext),e.operationContext.signal);return{data:qs(o)}},[er]:async n=>{te(e.operationContext.signal);const i=ed(n,"storage.setStorage 参数必须是对象"),o=Vs(i,er,e.storageLimits?.maxKeyLength),s=Gm(i.data,e.storageLimits?.maxValueBytes);await X(()=>e.storage.setRaw(ui(t(),o),s,e.operationContext),e.operationContext.signal)}};return e.storageDiagnostics?{handlers:r,diagnostics:{getSnapshot:async()=>{te(e.operationContext.signal);let n;try{n=t()}catch{throw $e("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const i=ui(n,"");return(await X(()=>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:qs(a),serializedValue:a,bytes:td(a)}}).sort((s,a)=>s.key.localeCompare(a.key))}}}:{handlers:r}}function zm(e){let t=!1,r;return()=>{if(!t){const n=e.identity.get()?.miniProgramId.trim();if(n)r=`id_${zs(n)}`;else{const i=e.anonymousStorageScope?.trim();i&&(r=`anon_${zs(i)}`)}t=r!==void 0}if(!r)throw $e("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return r}}function ui(e,t){return`hb_miniprogram_${e}_${t}`}function Vs(e,t,r=Bm){const i=ed(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw $e("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!Vm.test(i))throw $e("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function Gm(e,t){let r;try{r=JSON.stringify(e)}catch{throw $e("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw $e("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&td(r)>t)throw $e("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function qs(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function ed(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw $e("INVALID_PARAMS",t);return e}function zs(e){return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:jm(e)}function jm(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function td(e){return new TextEncoder().encode(e).length}function $e(e,t){return{code:e,message:t}}const Gs=120;function Ve(e){throw{code:"INVALID_PARAMS",message:e}}function Do(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rd(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Ve(`${r} 不支持字段: ${n.join(", ")}`)}function $m(e){if(!Do(e))return Ve("ui.showToast 参数必须是对象");if(rd(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Ve("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Gs)return Ve(`ui.showToast message 不能超过 ${Gs} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Ve("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function Wm(e){return e===void 0?{dismissible:!1}:Do(e)?(rd(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Ve("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Ve("ui.showLoading 参数必须是对象")}function Km(e){e!==void 0&&(!Do(e)||Object.keys(e).length)&&Ve("ui.hideLoading 不支持参数")}function Ym(e){return{[pn]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.showToast($m(t),e.operationContext),e.operationContext.signal)},[gn]:async t=>{te(e.operationContext.signal),await X(()=>e.presentation.showLoading(Wm(t),e.operationContext),e.operationContext.signal)},[yn]:async t=>{te(e.operationContext.signal),Km(t),await X(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const Qm={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ye(e,"当前用户首页资料接口响应异常")}},Jm=3e4;function Xm(e,t,r={}){const n=r.ttlMs??Jm,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function l(){let g;try{g=await Gn(e,Qm,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(u){throw t.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):u instanceof se?y("REQUEST_UNSUPPORTED",u.message):u instanceof gr?y("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof vt?y("REQUEST_FAILED","user home_v2 请求失败"):u instanceof St?i&&(u.status===403||u.status===429)?y("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:u.status,...u.retryAfterMs===void 0?{}:{retryAfterMs:u.retryAfterMs}}):y("REQUEST_FAILED",u.message):ep(u)?u:y("REQUEST_FAILED","user home_v2 请求失败")}return Zm(g,"user home_v2")}function h(g){const u=Date.now();if(a?.userId===g&&a.expiresAt>u)return Promise.resolve(a.value);if(c?.userId===g&&c.generation===s)return c.promise;const p=s,v=l().then(A=>(s===p&&(a={userId:g,value:A,expiresAt:Date.now()+n}),A)).finally(()=>{c?.promise===v&&(c=void 0)});return c={userId:g,generation:p,promise:v},v}return{get:h,clear(){s+=1,a=void 0,c=void 0}}}function Zm(e,t){if(!B(e))throw y("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw y(n,r)}if(!B(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function ep(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}const tp={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 ye(e,"Steam 游戏库接口响应异常")}};function rp(e,t=qi){const r=eu({version:"1",validate:ip}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):qi,memoryMaxEntries:64,diskMaxEntries:256,diskMaxBytes:10*1024*1024,maxEntryBytes:512*1024};return{persistent:e.register({namespace:"user.steam-game-list",codec:r,policy:{...n,persistence:"memory-and-disk"}}),unresolved:e.register({namespace:"user.steam-game-list.unresolved",codec:r,policy:{...n,persistence:"memory"}})}}function js(e,t){if(e.steamId)return e.steamId;for(const r of["steamid","steam_id","steamId"]){const n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}function np(e){const{query:t}=e;return JSON.stringify([e.miniProgramId,e.userId,e.effectiveSteamId??null,e.personalInformationOpen??null,t.limit,t.offset,t.sort,t.q??"",t.includeHidden])}function ip(e){if(!B(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(fi(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Ze();for(const t of e.gameList){if(!B(t)||!Zi(t.appid)||!Zi(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Ze();for(const r of["image","icon"])$s(t,r);for(const r of["playtimeForever","playtime2Weeks"])fi(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Ze();if(t.price!==void 0){if(!B(t.price))throw Ze();for(const r of["current","initial","deadlineDate"])$s(t.price,r);for(const r of["discount","lowestPrice","deadlineTimestamp"])fi(t.price,r)}}return e}function Zi(e){return typeof e=="number"&&Number.isFinite(e)}function fi(e,t){if(e[t]!==void 0&&!Zi(e[t]))throw Ze()}function $s(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Ze()}function Ze(){return y("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const nd=20,op=100,sp=128,id=0,od="weeks",ap=100,cp=new Set(["weeks","all","achieved"]);function dp(){return{nickname:"",avatar:""}}function lp(e){const t=Xm(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??fc(),i=rp(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(d,m){const f=JSON.stringify([d,m]);return(!o||o.key!==f)&&(o={key:f,scope:n.createScope(m,n.createScope(d))}),o.scope}function l(){const d=o;o=void 0,d&&n.invalidateScope(d.scope).catch(()=>{}),s.clear()}const h=_c({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??bc))}),g=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let u=0,p=!1;const v=e.account.onChange(()=>{u+=1,t.clear(),h.invalidate(),l()}),A=e.authorization.onEvent((d,m)=>{d==="user_info_authorization_change"&&Object.values(m).some(f=>f==="denied")&&(u+=1,t.clear(),h.invalidate(),l(),a=a.then(async()=>{if(p)return;const f=await e.account.getCurrentUserId(e.operationContext);typeof f=="string"&&f.trim()&&await n.invalidateScope(c(b(),f.trim()))}).catch(()=>{}))});function O(){if(p||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function b(){const d=e.identity.get()?.miniProgramId?.trim();if(!d)throw y("INVALID_STATE","用户能力缺少 canonical 小程序身份");return d}async function D(){O(),await a,O();let d;try{d=await e.account.getCurrentUserId(e.operationContext)}catch(m){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Ks(m)?m:y("REQUEST_FAILED","读取小黑盒账号失败")}return typeof d=="string"&&d.trim()?d.trim():void 0}async function _(d,m){const f=await D();if(u!==m||f!==d)throw y("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function L(d,m,f=e.operationContext.signal){try{return await Gn(e.network,d,m,{...e.operationContext,signal:f,credentials:"heybox-session",...g?{gate:g}:{}})}catch(E){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):E instanceof se?y("REQUEST_UNSUPPORTED",E.message):E instanceof gr?y("INVALID_RESPONSE","用户接口响应不合法"):E instanceof vt?y("REQUEST_FAILED","用户请求失败"):E instanceof St?r&&(E.status===403||E.status===429)?y("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:E.status,...E.retryAfterMs===void 0?{}:{retryAfterMs:E.retryAfterMs}}):y("REQUEST_FAILED",E.message):Ks(E)?E:y("REQUEST_FAILED","用户请求失败")}}async function F(){b();const d=u,m=await D();if(!m)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[f,E]=await Promise.all([e.authorization.getOrCreateLocalIdentity(m),N(m).catch(()=>dp())]);return await _(m,d),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:f.appUserId,profile:E,...f.steamId?{steam_id:f.steamId}:{}}}}function N(d){return h.read(d,()=>L(Ic,void 0).then(m=>{const f=Ws(m,"账号基础信息");if(f.display_username!==void 0&&typeof f.display_username!="string")throw y("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(f.display_avatar!==void 0&&typeof f.display_avatar!="string")throw y("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:f.display_username??"",avatar:f.display_avatar??""}}))}async function I(d){const m=up(d),f=b(),E=u,w=await D();if(!w)return l(),{isLogin:!1,isBound:!1,data:null};const S=await t.get(w);await _(w,E);const T=To(S.steam_id_info);if(Object.keys(T).length===0)return await n.invalidateScope(c(f,w)).catch(()=>{}),await _(w,E),s.delete(JSON.stringify([f,w])),{isLogin:!0,isBound:!1,data:null};const V=JSON.stringify([f,w]),C=c(f,w),P=js({...m,steamId:void 0},T),M=sd(T.personal_infomation_open??T.personal_information_open),R=JSON.stringify([P??null,M??null]),U=s.get(V);U&&U.identity!==R&&(await n.invalidateScope(C).catch(()=>{}),await _(w,E));const x={identity:R,scope:n.createScope(R,C)};s.set(V,x);const H=js(m,T),z=H?i.persistent:i.unresolved,G=n.createScope(H??"unresolved",x.scope),$=async()=>{if(await _(w,E),b()!==f||s.get(V)?.identity!==R)throw y("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},ee=await z.read({scope:G,key:np({miniProgramId:f,userId:w,effectiveSteamId:H,personalInformationOpen:M,query:m}),signal:e.operationContext.signal,load:async Z=>{const J=await L(tp,{userId:w,...m,personalInformationOpen:M},Z);return await $(),gp(Ws(J,"Steam 游戏库"),m)}}).catch(async Z=>{throw await $(),Z});return await $(),{isLogin:!0,isBound:!0,data:ee}}return{getInfo:F,getSteamGameList:I,async invalidateSteamGameListCache(){const d=b(),m=u,f=await D();if(!f)return;const E=c(d,f);await Promise.all([i.persistent.invalidateScope(E),i.unresolved.invalidateScope(E)]),t.clear(),s.delete(JSON.stringify([d,f])),await _(f,m)},dispose(){p||(p=!0,u+=1,v(),A(),t.clear(),h.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function up(e){if(e==null)return{limit:nd,offset:id,sort:od,includeHidden:!1};if(!B(e))throw qe("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw qe(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:fp(e.limit),offset:hp(e.offset),sort:mp(e.sort),includeHidden:pp(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>sp)throw qe("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw qe("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,ap))}return r}function fp(e){if(e===void 0)return nd;if(!Number.isInteger(e)||Number(e)<1)throw qe("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),op)}function hp(e){if(e===void 0)return id;if(!Number.isInteger(e)||Number(e)<0)throw qe("user.getSteamGameList offset 必须是非负整数");return Number(e)}function mp(e){if(e===void 0)return od;if(typeof e!="string"||!cp.has(e))throw qe("user.getSteamGameList sort 不支持");return e}function pp(e){if(e===void 0)return!1;if(typeof e!="boolean")throw qe("user.getSteamGameList includeHidden 必须是 boolean");return e}function gp(e,t){if(!Array.isArray(e.game_list))throw y("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(yp).filter(a=>a!==void 0),n=Rn(e.total),i=t.offset+r.length,o={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(o.total=n,o.hasMore=i<n);const s=sd(e.is_me);return s!==void 0&&(o.isMe=s),o}function yp(e){const t=To(e),r=Rn(t.appid),n=Rn(t.steam_appid)??r,i=Co(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};Wt(o,"image",t.image),Wt(o,"icon",t.appicon??t.icon),Kt(o,"playtimeForever",t.playtime_forever),Kt(o,"playtime2Weeks",t.playtime_2weeks);const s=wp(t.external_tags??t.tags);s.length&&(o.tags=s);const a=Ep(t.price);return a&&(o.price=a),o}function Ep(e){const t=To(e),r={};return Wt(r,"current",t.current),Wt(r,"initial",t.initial),Kt(r,"discount",t.discount),Kt(r,"lowestPrice",t.lowest_price),Wt(r,"deadlineDate",t.deadline_date),Kt(r,"deadlineTimestamp",t.deadline_timestamp),Object.keys(r).length?r:void 0}function Ws(e,t){if(!B(e))throw y("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw y(n,r)}if(!B(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function To(e){return B(e)?e:{}}function Co(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function wp(e){return Array.isArray(e)?e.map(Co).filter(Boolean):[]}function Rn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function sd(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function Wt(e,t,r){const n=Co(r);n&&Object.assign(e,{[t]:n})}function Kt(e,t,r){const n=Rn(r);n!==void 0&&Object.assign(e,{[t]:n})}function qe(e){return y("INVALID_PARAMS",e)}function Ks(e){return B(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Ap(e){return{[Kr]:async t=>(Ys(t,"user.getInfo"),e.user.getInfo()),[Yr]:async(t,r)=>{Ys(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Qr]:async t=>e.user.getSteamGameList(t)}}function Ys(e,t){if(e!==void 0)throw y("INVALID_PARAMS",`${t} 不接收入参`)}function Qs(e){throw{code:"INVALID_PARAMS",message:e}}function xt(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function ad(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Nr(e,t,r){return Math.min(ad(e,t),r)}async function bp(e){try{return ad(await e.getNavigationBarHeight(),0)}catch{return 0}}function Ip(e,t,r,n){const i=Nr(e.safeArea?.left,0,t),o=Math.max(i,Nr(e.safeArea?.right,t,t)),s=Nr(e.safeArea?.top,n,r),a=Math.max(s,Nr(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Js(e){const t=e.getViewportMetrics(),r=xt(t.windowWidth,0),n=xt(t.windowHeight,0),i=await bp(e);return{pixelRatio:xt(t.pixelRatio,1),screenWidth:xt(t.screenWidth,r),screenHeight:xt(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:Ip(t,r,n,i),screenTop:i}}function _p(e){const t=new AbortController,r={...e,operationContext:{...e.operationContext,signal:t.signal}};let n=!1,i=0,o,s;const a=()=>{if(n||r.operationContext.signal.aborted||!r.onViewportChange)return;const g=++i;Js(r.presentation).then(u=>{if(n||r.operationContext.signal.aborted||g!==i)return;const p=JSON.stringify(u);p!==o&&(o=p,r.onViewportChange?.(u))}).catch(()=>{})},c=Ih({...r,onApplied:a}),l=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",l),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?l():(s=r.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",l,{once:!0})),{handlers:{[ot]:async(g,u)=>c.apply(g,u?.signal),[en]:async()=>(te(r.operationContext.signal),Js(r.presentation)),[tn]:async g=>{if(te(r.operationContext.signal),typeof g!="object"||g===null||Array.isArray(g))return Qs("viewport.setNavigationBarStyle 参数必须是对象");const u=g.foregroundStyle;if(u!=="light"&&u!=="dark")return Qs("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await X(()=>r.presentation.setNavigationBarStyle(u,e.operationContext),r.operationContext.signal)}},applyOrientation:(g,u)=>c.apply({orientation:g.mode,fullscreen:g.hideCapsule},u),notifyChange:()=>{o=void 0,a()},dispose:l}}const Sp=new Map(Ge.map(e=>[e.method,e]));function qt(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function vp(e){const t=Je(e);return r=>{if(r.requirement.kind==="none")return{allowed:!0};for(const n of r.requirement.permissions){const i=t.valid?t.permissions[n]:void 0;if(!i)return{allowed:!1,code:"PERMISSION_NOT_DECLARED",message:`小程序未声明权限: ${n}`,data:{permission:n,method:r.method}};if(i.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${n}`,data:{permission:n,method:r.method}}}return{allowed:!0}}}function Op(e,t,r,n){let i;try{i=Promise.resolve(e(t,r))}catch(o){return n.aborted?Promise.resolve({status:"dropped"}):Promise.reject(o)}return n.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((o,s)=>{let a=!1;const c=h=>{a||(a=!0,n.removeEventListener("abort",l),h())},l=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",l,{once:!0}),i.then(h=>c(()=>o({status:"handled",value:h})),h=>c(()=>s(h)))})}function Rp(e){const t=vp(e.runtimePermissions),r=Je(e.runtimePermissions);let n=0,i=0,o=0;return{async dispatch(s,a,c){const l=e.now??Pp,h=e.onTrace?l():0,g=e.onTrace?`cap_${++n}`:"",u=s===ot?++i:void 0;let p;try{if(e.terminalSignal.aborted)throw qt("RUNTIME_DESTROYED","小程序 Runtime 已终止");Nl(s,e.effectiveCapabilities);const v=Sp.get(s);if(!v)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const A=t(v),O=!A.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!A.allowed&&!O)throw qt(A.code,A.message,A.data);const b=e.handlers[s];if(!b)throw new Error(`Capability method ${s} 缺少 handler`);u!==void 0&&(p=qc(c.signal));const D=p?{...c,signal:p.signal}:c,_=async()=>{for(const F of e.policies??[]){const N=await F.evaluate({method:s,payload:a,capability:v});if(e.terminalSignal.aborted||p?.signal.aborted)throw ea();if(!N.allowed)throw qt(N.code,N.message,N.data)}if(e.terminalSignal.aborted||p?.signal.aborted)throw ea();if(u!==void 0){if(zc(a),u<o)throw qt("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=u}return b(a,D)},L=await Op(()=>p?p.run(_):_(),void 0,c,e.terminalSignal);return Xs(e.onTrace,Zs(g,s,a,h,L),l),L}catch(v){throw Xs(e.onTrace,Zs(g,s,a,h,{status:"error",error:v}),l),v}finally{p?.dispose()}}}}function Pp(){return typeof performance>"u"?Date.now():performance.now()}function Xs(e,t,r){if(!e)return;const n=r();try{e({...t,timestamp:n,durationMs:Math.max(0,Number.isFinite(n-t.startedAt)?n-t.startedAt:0)})}catch{}}function Zs(e,t,r,n,i){const o=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:n,outcome:o,...i.status==="error"?{errorCode:Np(i.error)}:{},...Dp(t,r,i)}}function Np(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function Dp(e,t,r){if(e!=="network.request"||typeof t!="object"||t===null||!("url"in t)||typeof t.url!="string")return{};try{const n=new URL(t.url);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password)return{};const o=("method"in t&&typeof t.method=="string"?t.method:"GET").trim().toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(o))return{};const s=r.status==="handled"&&cd(r.value)&&typeof r.value.status=="number"?r.value.status:void 0;return{network:{method:o,origin:n.origin,pathname:n.pathname,...s===void 0?{}:{responseStatus:s}}}}catch{return{}}}function cd(e){return typeof e=="object"&&e!==null}function ea(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Tp(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=pu(e.requestPolicy);let n;if(e.files)try{n=ou(e.files,t)}catch{}const i=fc({store:n}),o=e.onRequestPolicyReport??(r.debugReport?Cp:void 0),s=r.enabled?uu({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Hf(e.files,e.miniProgramDetail),c=$f({registry:a,picker:e.picker,operationContext:t}),l=Bu({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode,authorizationContext:e.authorizationContext,identityTtlMs:r.identityTtlMs,requestGate:s,requestPolicyEnabled:r.enabled});let h,g,u,p=()=>{},v=()=>{};try{h=_p({operationContext:t,presentation:e.hostPresentation,onDisplayChange:N=>e.eventSink.postEvent("display_change",N),onViewportChange:N=>e.eventSink.postEvent("viewport_change",N)}),g=lp({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:l,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:s,requestPolicyEnabled:r.enabled}),p=l.onEvent((N,I)=>e.eventSink.postEvent(N,I)),v=e.hostCompanion?.onSessionEvent?.(N=>{const I=Tf(N);!e.terminalSignal.aborted&&I&&e.eventSink.postEvent(I.type,I.payload)})??(()=>{}),u=gf({account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const A=qm({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),O=[{name:"auth",handlers:Yu({authorization:l})},{name:"user",handlers:Ap({user:g,authorization:l,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:Fm({environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:h.handlers},{name:"storage",handlers:A.handlers},{name:"network",handlers:nm({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[$r]:async()=>{throw qt("CAPABILITY_UNAVAILABLE","当前 Runtime 不支持工作区卡片刷新")}}},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"ui",handlers:Ym({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:kf({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:_h({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:N=>h.applyOrientation({mode:"portrait",hideCapsule:!1},N)}:{}})},{name:"cloud",handlers:u.handlers},{name:"companion",handlers:Of({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],b=Lp(O);let D=!1;const _=()=>{D||(D=!0,e.terminalSignal.removeEventListener("abort",_),h?.dispose(),u?.dispose(),p(),v(),g?.dispose(),i.dispose(),l.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?_():e.terminalSignal.addEventListener("abort",_,{once:!0});const L=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:O,handlers:b,allowsCompanionAttachmentAccess:(N,I)=>L.has(N)&&cd(I)&&a.isCompanionAttachmentRef(I.target),applyOrientation:h.applyOrientation,notifyViewportChange:h.notifyChange,...A.diagnostics?{storageDiagnostics:A.diagnostics}:{},dispose:_}}catch(A){throw h?.dispose(),u?.dispose(),p(),v(),g?.dispose(),i.dispose(),l.dispose(),s?.dispose(),a.dispose(),A}}function Cp(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Lp(e){const t=new Map(Ge.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[o,s]of Object.entries(i.handlers)){const a=o,c=t.get(a);if(!c)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${a}`);if(c!==i.name)throw new Error(`Capability method ${a} 应由 ${c} 拥有,不能注册到 ${i.name}`);if(r.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);r.set(a,s)}const n=Ge.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Ge.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Mp="heybox-mini-dev:";function ta(e){try{return kp(new URL(e))}catch{return!1}}function kp(e){return e.protocol===Mp}function Up(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||xp(e)}function xp(e){const t=e.split(".");if(t.length!==4)return!1;const r=t.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);return r.some(n=>!Number.isInteger(n)||n<0||n>255)?!1:r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}const Hp=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Fp(e,t){const r=[],n=Bp(e.environmentInfo,r),i=xr(n?.appVersion,"host.appVersion",r),o=qp(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:Vp(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:xr(t.miniProgramId),version:xr(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function Bp(e,t){if(e!=null){if(dd(e))return e;t.push("environmentInfo")}}function Vp(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function qp(e,t){if(e==null)return{name:"unknown",version:null};if(!dd(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=Hp.has(e.name)?e.name:"unknown";return r==="unknown"&&e.name!==void 0&&e.name!==null&&e.name!=="unknown"&&t.push("operatingSystem.name"),{name:r,version:xr(e.version,"operatingSystem.version",t)}}function xr(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function dd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const zp=1,ld="allow-scripts allow-same-origin",Gp="",jp="no-referrer";function $p(e=ld){return!e.split(/\s+/).includes("allow-same-origin")}function ra(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Wp=new Set(["javascript:","data:","blob:","file:"]),na="xiaoheihe.cn";function Kp(e,t=window.location.href,r={}){const n=e.trim();if(!n)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(n)}catch{throw new Error("小程序链接必须是绝对 URL")}if(Wp.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!Zp(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Yp(e,t){const r=new URL(e);return r.searchParams.set(sl,t),r.toString()}function Qp(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Jp(r)??Xp(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Jp(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Xp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function ia(e){const t=new URL(e);return Lo(t)?"loopback":Mo(t)?"lan":"production"}function Zp(e,t,r){return eg(e)||Lo(e)||Mo(e)&&rg(t,r)}function eg(e){return e.protocol==="https:"&&og(e.hostname)}function Lo(e){return e.protocol==="http:"&&tg(e.hostname)}function tg(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Mo(e){return e.protocol==="http:"&&ng(e.hostname)}function rg(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Lo(r)||Mo(r)}catch{return!1}}function ng(e){const t=ig(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function ig(e){const t=e.split(".");if(t.length!==4)return;const r=t.map(n=>{if(!/^\d+$/.test(n))return;const i=Number(n);return Number.isInteger(i)&&i>=0&&i<=255?i:void 0});return r.every(n=>n!==void 0)?r:void 0}function og(e){return e===na||e.endsWith(`.${na}`)}const sg=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"]),ag=new Set(["url","inline","eval","unknown"]),cg=/^\/(?:\:segment(?:\/\:segment)*)?$/,dg=/^[a-f0-9]{64}$/,lg=255,ug=160,fg=256;function hg(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!sg.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>fg||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!ag.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=mg(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>ug||!cg.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!dg.test(o)||i===void 0)))return{effectiveDirective:r.effectiveDirective,violatedDirective:r.effectiveDirective,blockedResourceType:r.blockedResourceType,origin:n,sanitizedPathname:i,sanitizedPathnameHash:o,sdkVersion:r.sdkVersion,timestamp:r.timestamp}}function mg(e){if(e!==void 0&&!(typeof e!="string"||e.length>lg))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const pg=/^(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 gg(e){if(!e?.minimumSdkVersion)throw K("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=tt(e.minimumSdkVersion),r=e.sdkVersion?tt(e.sdkVersion):void 0;if(!t)throw K("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw K("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=tt("0.6.0");if(!r){if(Hr(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw K("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0)throw K("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(Hr(r,t)<0)throw K("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Hr(r,tt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function yg(e,t){if(typeof t!="string"||!tt(t))throw K("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw K("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function Eg(e,t){const r=tt(e),n=tt(t);if(!(!r||!n))return Hr(r,n)}function tt(e){const t=pg.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(r=>/^\d+$/.test(r)?Number(r):r)??[]}}function Hr(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],o=t.prerelease[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const $n=["android","ios","ohos","windows","macos","linux"],wg="0.9.0",Ag=Object.freeze(["android","ios","ohos","windows","macos"]),ud="该小程序暂不支持当前平台",bg="PLATFORM_UNSUPPORTED";function Ig(e){return typeof e=="string"&&$n.includes(e)}function _g(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 Sg(e){const t=e.manifest;if(!Ng(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=sa(e.sdkVersion)??sa(t.sdkVersion);return Rg(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:Og()}const r=fd(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function vg(e){const t=_g(e.operatingSystemName);if(!t)return Et("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Et("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:$n,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=Sg({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Et("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):oa(t,s)}if(r.effectivePlatforms===void 0)return Et("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=fd(r.effectivePlatforms);if("reason"in n)return Et("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=Pg(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return oa(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function oa(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Et("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Et(e,t={}){return{status:"denied",reason:e,message:ud,...t}}function Og(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:Ag,platformsDeclared:!1,policy:"legacy_mobile_default"}}function fd(e){if(!Array.isArray(e))return{reason:"platforms_not_array"};if(e.length===0)return{reason:"platforms_empty"};const t=new Set;for(const r of e){if(!Ig(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze($n.filter(r=>t.has(r)))}}function Rg(e){if(typeof e!="string"||!e.trim())return!1;const t=Eg(e.trim(),wg);return t!==void 0&&t>=0}function sa(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Pg(e){return e==="explicit"||e==="legacy_mobile_default"}function Ng(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Dg=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 Tg(e,t,r){const n=Date.now();try{const i=new URL(t);return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r,origin:i.origin,sanitizedPathname:Cg(i.pathname),sanitizedPathnameHash:Lg(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function Cg(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function Lg(e){const t=new TextEncoder().encode(e),r=Math.ceil((t.length+9)/64)*64,n=new Uint8Array(r);n.set(t),n[t.length]=128,new DataView(n.buffer).setUint32(r-4,t.length*8,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64),s=new DataView(n.buffer);for(let a=0;a<r;a+=64){for(let O=0;O<16;O+=1)o[O]=s.getUint32(a+O*4,!1);for(let O=16;O<64;O+=1){const b=o[O-15],D=o[O-2],_=Re(b,7)^Re(b,18)^b>>>3,L=Re(D,17)^Re(D,19)^D>>>10;o[O]=o[O-16]+_+o[O-7]+L>>>0}let[c,l,h,g,u,p,v,A]=i;for(let O=0;O<64;O+=1){const b=A+(Re(u,6)^Re(u,11)^Re(u,25))+(u&p^~u&v)+Dg[O]+o[O]>>>0,D=(Re(c,2)^Re(c,13)^Re(c,22))+(c&l^c&h^l&h);A=v,v=p,p=u,u=g+b>>>0,g=h,h=l,l=c,c=b+D>>>0}[c,l,h,g,u,p,v,A].forEach((O,b)=>{i[b]=i[b]+O>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function Re(e,t){return e>>>t|e<<32-t}const Mg=1e4,hi=2e3,kg=2,Ug="open-with-native-credential-policy",hd="安全提示",md="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class xg{nonce=ra();runtimeId=ra();terminalController=new AbortController;options;handshakeTimeout;ports;primitiveAvailability;effectiveCapabilities;identity;identityRef;iframe;iframeErrorListener;iframeLoadListener;bridgeServer=null;miniProgramSrc="";launchUrl="";startPromise=null;readyContext=null;resolveReady;rejectReady;terminalError;status="idle";stateValue="idle";handshakeTimeoutTimer;lifecycleDisposer;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;sdkVersionDecision;platformGateDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;unexpectedDocumentLoadTimer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=uc(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities});this.ports=r.ports,this.primitiveAvailability=r.primitiveAvailability,this.effectiveCapabilities=r.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const n=this.identity.miniProgramId?.trim();if(n)return{miniProgramId:n,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??Mg,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics;return t?{storage:t}:{}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??K("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??K("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:($g(),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=K("RUNTIME_DESTROYED","小程序运行时已销毁");this.terminalError=t,this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.teardownIframe(),this.rejectReady?.(t)}show(){const t=this.hostVisible;this.hostVisible=!0,this.emitLifecycleEvent("show"),this.capabilityGraph?.notifyViewportChange(),!t&&this.stateValue==="ready"&&this.sdkVersionDecision?.heartbeatEnabled&&(this.documentRevalidationPending?(this.armDocumentRevalidationTimer(this.documentRevalidationGeneration),this.resendDocumentRevalidationProbe()):this.sendLocationProbe())}hide(){this.hostVisible=!1,this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.emitLifecycleEvent("hide")}prepareForHistoryTraversal(){if(this.stateValue!=="ready"||this.bridgeServer?.protocolVersion!==2||!this.sdkVersionDecision?.heartbeatEnabled)return()=>{};const t=this.beginDocumentRevalidation({deferProbe:!0});return this.preparedHistoryTraversalGeneration=t,()=>{this.preparedHistoryTraversalGeneration===t&&this.cancelPreparedHistoryTraversal()}}createReadyPromise(){return new Promise((t,r)=>{this.resolveReady=t,this.rejectReady=r})}async launch(){const t=await this.resolveRuntimeLaunchConfiguration();if(this.isInactive())return;this.runtimePermissions=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=gg(t.sdkVersionPolicy);const r=Fp(t,this.identity);if(this.environmentInfo=r.info,r.invalidFields.length>0&&this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"environment_invalid",message:`环境字段已降级:${r.invalidFields.join(", ")}`}),this.platformGateDecision=vg({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw Yg(this.platformGateDecision);if(this.miniProgramDetail=Qg(t),this.effectiveCapabilities=lc(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),Vg(this.options.onLaunchConfigurationResolved,t,this.sdkVersionDecision),this.isInactive())return;this.applyIframeDefaults(),this.startBridgeServer(),this.installSubscriptions();const n=await this.normalizeLaunchUrl(t.launchUrl);if(this.isInactive())return;const i=await this.confirmDevMiniProgramLaunch(n);if(!this.isInactive()){if(!i){await this.closeAfterDevLaunchCancellation();return}if(this.bridgeServer?.setTargetOrigin(zg(n)),this.launchUrl=n,this.miniProgramSrc=Yp(n,this.nonce),this.traceSecurityPolicy(n),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=wo(o);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:ot,errorCode:s.code,message:`默认展示设置失败,沿用宿主当前布局:${s.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,xe(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&(n!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(n!=="display_change"||this.effectiveCapabilities[ot])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=Tp({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,hostProtocol:this.ports.protocol,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins,requestPolicy:this.options.requestPolicy,...this.options.onRequestPolicyReport?{onRequestPolicyReport:this.options.onRequestPolicyReport}:{}});const r=Rp({handlers:this.capabilityGraph.handlers,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:l,network:h})=>{const g={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...l?{errorCode:l}:{},...this.identity,...h?{network:h}:{}};xe(this.options.onCapabilityTrace,g)}}:{}});this.bridgeServer=new Rl({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,onHandshake:n=>this.handleBridgeHandshake(n),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:n=>{this.handleInternalBridgeEvent(n)},onResponsePosted:({method:n,outcome:i,errorCode:o})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:n,outcome:i,...o?{errorCode:o}:{}})}}),this.bridgeServer.start(),this.setStatus("bridge_started"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge_started"})}onIframeError(t=new Error("小程序 iframe 加载失败")){if(this.isInactive())return;const r=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(K("IFRAME_LOAD_ERROR",r,t))}emitLifecycleEvent(t){if(this.stateValue!=="ready"){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle_ignored",event:t,reason:this.isInactive()?"inactive":"not_ready"});return}this.bridgeServer?.postEvent(t,{timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle",method:t})}async resolveRuntimeLaunchConfiguration(){try{return await this.options.resolveLaunchConfiguration()}catch(t){throw Bg(t)?t:pd(K("STARTUP_ERROR",t instanceof Error?t.message:"获取小程序启动配置失败"),t)}}bindCanonicalIdentity(t){const r=t?.miniProgramId?.trim();r&&(this.identity.miniProgramId=r);const n=t?.miniProgramVersion?.trim();n&&(this.identity.miniProgramVersion=n)}async normalizeLaunchUrl(t){try{const r=this.options.environment.getCurrentHref();return Kp(t,r,{allowPrivateNetwork:ta(r)||aa(r)||await this.isDevRuntime()})}catch(r){throw K("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??jg)({message:md,title:hd,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(ia(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!ta(r)&&!aa(r)}async closeAfterDevLaunchCancellation(){const t=K("LAUNCH_CANCELLED","小程序启动已取消");this.terminalError=t,this.destroyBridgeServer();const r=new AbortController;let n;try{n=Promise.resolve(this.ports.presentation.close({signal:r.signal}))}catch{ca(),n=Promise.resolve()}this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"launch_cancelled"}),this.rejectReady?.(t),await n.catch(()=>ca())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Gp),this.iframe.setAttribute("referrerpolicy",jp),this.iframe.setAttribute("sandbox",ld)}removeIframeListeners(){this.iframe.removeEventListener("error",this.iframeErrorListener),this.iframe.removeEventListener("load",this.iframeLoadListener)}installSubscriptions(){if(this.options.lifecycle&&!this.lifecycleDisposer){const t=this.options.lifecycle.subscribe({show:this.show.bind(this),hide:this.hide.bind(this)});this.lifecycleDisposer=typeof t=="function"?t:null}}clearLifecycleDisposer(){const t=[this.lifecycleDisposer];this.lifecycleDisposer=null;for(const r of t)try{r?.()}catch{}}handleBridgeReady(){if(this.isInactive())return;if(this.readyContext){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"});return}this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge",method:"ready"}),this.setState("ready"),this.sdkVersionDecision?.heartbeatEnabled&&this.hostVisible&&this.sendLocationProbe(),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),xe(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(),xe(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{yg(r,t?.sdkVersion)}catch(n){return this.failRuntime(n),!1}return!0}armHandshakeTimeout(){this.clearHandshakeTimeout(),!(this.handshakeTimeout<=0)&&(this.handshakeTimeoutTimer=setTimeout(()=>{this.stateValue==="ready"||this.isInactive()||(this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"handshake_timeout"}),this.failRuntime(K("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>=kg)){this.failRuntime(K("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(br,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},hi),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:br})}clearHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0),this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0}beginDocumentRevalidation(t={}){this.clearUnexpectedDocumentLoadFailure(),this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.preparedHistoryTraversalGeneration=void 0,this.documentRevalidationPending=!0;const r=++this.documentRevalidationGeneration;return this.iframeHiddenForRevalidation||(this.iframeVisibilityBeforeRevalidation=this.iframe.style.visibility,this.iframe.style.visibility="hidden",this.iframeHiddenForRevalidation=!0),this.armDocumentRevalidationTimer(r),t.deferProbe||this.sendDocumentRevalidationProbe(),r}sendDocumentRevalidationProbe(){if(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)return;const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(br,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:br})}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(K("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 文档再验证超时")))},hi))}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()},hi))}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===cl){this.handleCspViolation(t.payload);return}if(t.method!==al)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(K("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Qp(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(K("URL_OUT_OF_SCOPE","小程序页面地址超出允许范围"));return}n.probeId!==void 0?(this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.documentRevalidationPending&&this.completeDocumentRevalidation()):this.documentRevalidationPending&&!this.pendingProbeId&&(this.preparedHistoryTraversalGeneration=void 0,this.sendDocumentRevalidationProbe())}}handleCspViolation(t){const r=hg(t,this.sdkVersionDecision?.sdkVersion);r&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:r.timestamp,sdkVersion:r.sdkVersion,origin:r.origin,sanitizedPathname:r.sanitizedPathname,sanitizedPathnameHash:r.sanitizedPathnameHash,effectiveDirective:r.effectiveDirective,violatedDirective:r.violatedDirective,blockedResourceType:r.blockedResourceType})}emitSecurityViolation(t){xe(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=Tg(t,r,this.sdkVersionDecision?.sdkVersion);this.emitSecurityViolation(n)}scheduleUnexpectedDocumentLoadFailure(){this.clearUnexpectedDocumentLoadFailure(),this.unexpectedDocumentLoadTimer=setTimeout(()=>{this.unexpectedDocumentLoadTimer=void 0,this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(K("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:zp,launchUrlType:ia(t),networkPolicy:Ug})}failRuntime(t){const r=Hg(t);return this.isInactive()||(this.terminalError=r,this.terminalController.abort(r),this.postBridgeError(r),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),this.setState("failed"),this.teardownIframe(r),xe(this.options.onError,Fg(r)),this.rejectReady?.(r)),r}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0,this.clearHandshakeTimeout(),this.clearHeartbeat(),this.clearUnexpectedDocumentLoadFailure(),this.clearDocumentRevalidation(),this.destroyBridgeServer(),this.capabilityGraph?.dispose(),this.capabilityGraph=void 0,this.clearLifecycleDisposer(),this.removeIframeListeners();try{this.options.dispose?.()}catch{}}}teardownIframe(t){if(!this.iframeTornDown){this.iframeTornDown=!0;try{this.options.teardownIframe?this.options.teardownIframe(this.iframe,t):this.iframe.remove()}catch{}}}setStatus(t){this.status!==t&&(this.status=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:t}))}setState(t){this.stateValue!==t&&(this.stateValue=t,xe(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){xe(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 Hg(e){const t=wo(e);return Pn(e)&&"cause"in e&&pd(t,e.cause),t}function pd(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function Fg(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function Bg(e){return Pn(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Pn(e){return!!e&&typeof e=="object"}function xe(e,t){try{e?.(t)}catch{}}function Vg(e,t,r){try{e?.(t,r)}catch{}}function aa(e){try{const t=new URL(e);return t.protocol==="http:"&&Up(t.hostname)}catch{return!1}}function qg(e){try{return new URL(e).origin}catch{return}}function zg(e){return $p()?"*":qg(e)}function Gg(e){return`${hd}
|
|
2
|
-
|
|
3
|
-
${md}
|
|
4
|
-
|
|
5
|
-
URL: ${e}`}function jg(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(Gg(e.url))}function ca(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function $g(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,r=typeof window>"u"?void 0:window,n=Object.freeze({protocolVersion:Za,knownMethodCount:Ge.length,supportsFileCreate:Ge.some(i=>i.method===tr),system:Wg(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:gt(e?.hardwareConcurrency),maxTouchPoints:gt(e?.maxTouchPoints),screen:{width:gt(t?.width),height:gt(t?.height)},viewport:{width:gt(r?.innerWidth),height:gt(r?.innerHeight),devicePixelRatio:Kg(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function Wg(e="",t=""){const r=`${t} ${e}`.toLowerCase();return/iphone|ipad|ipod/.test(r)?"ios":r.includes("android")?"android":/win32|win64|windows/.test(r)?"windows":/darwin|macintosh|macintel|mac os/.test(r)?"macos":/linux|x11/.test(r)?"linux":"unknown"}function gt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function Kg(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function Yg(e){return K(bg,ud,{reason:e.reason,...e.platform===void 0?{}:{platform:e.platform},...e.invalidReason===void 0?{}:{invalidReason:e.invalidReason},...e.effectivePlatforms===void 0?{}:{effectivePlatforms:e.effectivePlatforms}})}function Qg(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(!t)return;const r=e.canonicalIdentity?.miniProgramVersion?.trim(),n=e.miniProgramPresentation?.name?.trim(),i=e.miniProgramPresentation?.avatarUrl?.trim(),o=e.miniProgramPresentation?.author?.trim();return Object.freeze({miniProgramId:t,...r?{version:r}:{},...n?{name:n}:{},...i?{iconUrl:i}:{},...o?{author:o}:{},...e.sdkVersionPolicy.releaseChannel===void 0?{}:{releaseChannel:e.sdkVersionPolicy.releaseChannel}})}function Jg(e){if(!Pn(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!Pn(e.environment)||typeof e.environment.getCurrentHref!="function"||typeof e.environment.isDevRuntime!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 environment");if(typeof e.resolveLaunchConfiguration!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 resolveLaunchConfiguration");return new xg(e)}const Xg=/^(?:authentication-info|authorization|cookie|cookie2|proxy-authenticate|proxy-authentication-info|proxy-authorization|set-cookie|set-cookie2|www-authenticate|pkey|x-pkey|x-access-token|x-auth-token)$/i,Zg=new Set(["origin","referer","user-agent"]);function ey(e,t){return Cl({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=ty(r),a=await e.authenticatedRequest(s,o);return iy(a)})}).network}function ty(e){const t=ry(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function ry(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!ny(t)))}function ny(e){const t=e.trim().toLowerCase();return Zg.has(t)}function iy(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:oy(e.headers)??{}}}function oy(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!sy(t)))}function sy(e){const t=e.trim().toLowerCase();return Xg.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function ay(e,t,r){const n=fy(e.presentation,t);return{account:ly(e,t,r),network:ey(e,t),...e.storage===void 0?{}:{storage:uy(e,t)},...e.storage===void 0?{}:cy(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function cy(e,t){const r=e.storage;return typeof r.storage.key!="function"||typeof r.storage.length!="number"?{}:{storageDiagnostics:{listRaw:n=>t.run(n.signal,()=>{const i=[];for(let o=0;o<r.storage.length;o+=1){const s=r.storage.key(o);if(s===null)continue;const a=r.storage.getItem(s);a!==null&&i.push({area:r.area,key:s,value:a})}return i})}}}function dy(e,t){return{getCurrentHref:()=>(t.assertActive(),e.environment.getCurrentHref()),isDevRuntime:()=>t.run(void 0,()=>e.environment.isDevRuntime()),...e.environment.setDocumentTitle===void 0?{}:{setDocumentTitle:r=>{t.assertActive(),e.environment.setDocumentTitle?.(r)}}}}function ly(e,t,r){return{getCurrentUserId:n=>t.run(n.signal,i=>e.account.getCurrentUserId({signal:i})),ensureAuthenticated:n=>t.run(n.signal,i=>e.account.ensureAuthenticated({trustedUserGesture:n.trustedUserGesture,reason:n.reason,signal:i})),onChange:n=>{t.assertActive();const i=e.account.onChange(o=>{t.signal.aborted||n(o)});return r(i)}}}function uy(e,t){const r=e.storage.storage;return{getRaw:(n,i)=>t.run(i.signal,()=>{const o=r.getItem(n);return o===null?void 0:o}),setRaw:(n,i,o)=>t.run(o.signal,()=>{r.setItem(n,i)})}}function fy(e,t){if(!e)return;const r={};return e.close&&(r.close=n=>t.run(n.signal,i=>e.close({signal:i}))),e.reload&&(r.reload=n=>t.run(n.signal,i=>e.reload({signal:i}))),e.openAppPage&&(r.openAppPage=(n,i)=>t.run(i.signal,o=>e.openAppPage(n,{signal:o}))),e.openWindow&&(r.openWindow=(n,i)=>t.run(i.signal,o=>e.openWindow(n,{signal:o}))),e.applyOrientation&&(r.applyOrientation=(n,i)=>t.run(i.signal,o=>e.applyOrientation(n,{...i,signal:o}))),e.onViewportChange&&(r.onViewportChange=n=>{t.assertActive();const i=e.onViewportChange(()=>{t.signal.aborted||n()});let o=!1;const s=()=>{o||(o=!0,t.signal.removeEventListener("abort",s),i())};return t.signal.addEventListener("abort",s,{once:!0}),s}),e.getViewportMetrics&&(r.getViewportMetrics=()=>(t.assertActive(),e.getViewportMetrics())),e.getNavigationBarHeight&&(r.getNavigationBarHeight=()=>(t.assertActive(),e.getNavigationBarHeight())),e.setNavigationBarStyle&&(r.setNavigationBarStyle=(n,i)=>t.run(i.signal,o=>e.setNavigationBarStyle(n,{signal:o}))),e.showShareMenu&&(r.showShareMenu=(n,i)=>t.run(i.signal,o=>e.showShareMenu(n,{signal:o}))),e.setScreenshotChromeHidden&&(r.setScreenshotChromeHidden=(n,i)=>Gl(i)?e.setScreenshotChromeHidden(n,i):t.run(i.signal,o=>e.setScreenshotChromeHidden(n,{signal:o}))),e.captureAndShare&&(r.captureAndShare=(n,i)=>t.run(i.signal,o=>e.captureAndShare(n,{signal:o}))),e.showToast&&(r.showToast=(n,i)=>t.run(i.signal,o=>e.showToast(n,{signal:o}))),e.showLoading&&(r.showLoading=(n,i)=>t.run(i.signal,o=>e.showLoading(n,{signal:o}))),e.hideLoading&&(r.hideLoading=n=>t.run(n.signal,i=>e.hideLoading({signal:i}))),e.vibrate&&(r.vibrate=(n,i)=>t.run(i.signal,o=>e.vibrate(n,{signal:o}))),e.setClipboard&&(r.setClipboard=(n,i)=>t.run(i.signal,o=>e.setClipboard(n,{signal:o}))),Object.keys(r).length===0?void 0:r}function hy(){const e=new AbortController;return{signal:e.signal,abort:t=>{e.signal.aborted||e.abort(t)},assertActive:t=>{const r=[e.signal,t].find(n=>n?.aborted);if(r)throw Dr(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(h=>h.aborted);if(i)throw Dr(i.reason);const o=new AbortController;let s;const a=new Promise((h,g)=>{s=g}),c=n.map(h=>{const g=()=>{o.signal.aborted||o.abort(h.reason),s(Dr(h.reason))};return h.addEventListener("abort",g,{once:!0}),{listener:g,source:h}});let l;try{l=Promise.resolve(r(o.signal))}catch(h){l=Promise.reject(h)}try{const h=await Promise.race([l,a]),g=n.find(u=>u.aborted);if(g)throw Dr(g.reason);return h}finally{for(const{listener:h,source:g}of c)g.removeEventListener("abort",h)}}}}function Dr(e){return new DOMException("Web Host operation aborted","AbortError")}async function my(e){const t=hy(),r=new Set;let n=!1;const i=g=>{if(n||t.signal.aborted)return mi(g),()=>{};let u=!0;const p=()=>{u&&(u=!1,r.delete(p),mi(g))};return r.add(p),p},o=()=>s(e.signal.reason),s=g=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(g);for(const u of[...r])u();e.onDispose&&mi(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=ay(e,t,i),c=uc(a,{hostCapabilities:e.hostCapabilities}),l=dy(e,t);let h;return{platform:"web",ports:a,environment:l,resolveLaunch:()=>(h??=t.run(void 0,async g=>e.resolveLaunch(g)),h),...e.authPresentation===void 0?{}:{authPresentation:py(e.authPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function mi(e){try{e()}catch{}}function py(e,t){return{confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var yt={},pi,da;function gy(){return da||(da=1,pi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),pi}var gi={},He={},la;function at(){if(la)return He;la=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return He.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},He.getSymbolTotalCodewords=function(n){return t[n]},He.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},He.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},He.isKanjiModeEnabled=function(){return typeof e<"u"},He.toSJIS=function(n){return e(n)},He}var yi={},ua;function ko(){return ua||(ua=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,i){if(e.isValid(n))return n;try{return t(n)}catch{return i}}})(yi)),yi}var Ei,fa;function yy(){if(fa)return Ei;fa=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Ei=e,Ei}var wi,ha;function Ey(){if(ha)return wi;ha=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,i){const o=t*this.size+r;this.data[o]=n,i&&(this.reservedBit[o]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},wi=e,wi}var Ai={},ma;function wy(){return ma||(ma=1,(function(e){const t=at().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const i=Math.floor(n/7)+2,o=t(n),s=o===145?26:Math.ceil((o-13)/(2*i-2))*2,a=[o-7];for(let c=1;c<i-1;c++)a[c]=a[c-1]-s;return a.push(6),a.reverse()},e.getPositions=function(n){const i=[],o=e.getRowColCoords(n),s=o.length;for(let a=0;a<s;a++)for(let c=0;c<s;c++)a===0&&c===0||a===0&&c===s-1||a===s-1&&c===0||i.push([o[a],o[c]]);return i}})(Ai)),Ai}var bi={},pa;function Ay(){if(pa)return bi;pa=1;const e=at().getSymbolSize,t=7;return bi.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},bi}var Ii={},ga;function by(){return ga||(ga=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,l=null,h=null;for(let g=0;g<o;g++){a=c=0,l=h=null;for(let u=0;u<o;u++){let p=i.get(g,u);p===l?a++:(a>=5&&(s+=t.N1+(a-5)),l=p,a=1),p=i.get(u,g),p===h?c++:(c>=5&&(s+=t.N1+(c-5)),h=p,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const l=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(l===4||l===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let l=0;l<o;l++){a=c=0;for(let h=0;h<o;h++)a=a<<1&2047|i.get(l,h),h>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(h,l),h>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let l=0;l<s;l++){o(l),e.applyMask(l,i);const h=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(l,i),h<c&&(c=h,a=l)}return a}})(Ii)),Ii}var Tr={},ya;function gd(){if(ya)return Tr;ya=1;const e=ko(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Tr.getBlocksCount=function(i,o){switch(o){case e.L:return t[(i-1)*4+0];case e.M:return t[(i-1)*4+1];case e.Q:return t[(i-1)*4+2];case e.H:return t[(i-1)*4+3];default:return}},Tr.getTotalCodewordsCount=function(i,o){switch(o){case e.L:return r[(i-1)*4+0];case e.M:return r[(i-1)*4+1];case e.Q:return r[(i-1)*4+2];case e.H:return r[(i-1)*4+3];default:return}},Tr}var _i={},Ht={},Ea;function Iy(){if(Ea)return Ht;Ea=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let i=0;i<255;i++)e[i]=n,t[n]=i,n<<=1,n&256&&(n^=285);for(let i=255;i<512;i++)e[i]=e[i-255]})(),Ht.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Ht.exp=function(n){return e[n]},Ht.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},Ht}var wa;function _y(){return wa||(wa=1,(function(e){const t=Iy();e.mul=function(n,i){const o=new Uint8Array(n.length+i.length-1);for(let s=0;s<n.length;s++)for(let a=0;a<i.length;a++)o[s+a]^=t.mul(n[s],i[a]);return o},e.mod=function(n,i){let o=new Uint8Array(n);for(;o.length-i.length>=0;){const s=o[0];for(let c=0;c<i.length;c++)o[c]^=t.mul(i[c],s);let a=0;for(;a<o.length&&o[a]===0;)a++;o=o.slice(a)}return o},e.generateECPolynomial=function(n){let i=new Uint8Array([1]);for(let o=0;o<n;o++)i=e.mul(i,new Uint8Array([1,t.exp(o)]));return i}})(_i)),_i}var Si,Aa;function Sy(){if(Aa)return Si;Aa=1;const e=_y();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(n.length+this.degree);i.set(n);const o=e.mod(i,this.genPoly),s=this.degree-o.length;if(s>0){const a=new Uint8Array(this.degree);return a.set(o,s),a}return o},Si=t,Si}var vi={},Oi={},Ri={},ba;function yd(){return ba||(ba=1,Ri.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Ri}var Pe={},Ia;function Ed(){if(Ia)return Pe;Ia=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
|
|
6
|
-
]))+`;Pe.KANJI=new RegExp(r,"g"),Pe.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Pe.BYTE=new RegExp(n,"g"),Pe.NUMERIC=new RegExp(e,"g"),Pe.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Pe.testKanji=function(c){return i.test(c)},Pe.testNumeric=function(c){return o.test(c)},Pe.testAlphanumeric=function(c){return s.test(c)},Pe}var _a;function ct(){return _a||(_a=1,(function(e){const t=yd(),r=Ed();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(o,s){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!t.isValid(s))throw new Error("Invalid version: "+s);return s>=1&&s<10?o.ccBits[0]:s<27?o.ccBits[1]:o.ccBits[2]},e.getBestModeForData=function(o){return r.testNumeric(o)?e.NUMERIC:r.testAlphanumeric(o)?e.ALPHANUMERIC:r.testKanji(o)?e.KANJI:e.BYTE},e.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},e.isValid=function(o){return o&&o.bit&&o.ccBits};function n(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+i)}}e.from=function(o,s){if(e.isValid(o))return o;try{return n(o)}catch{return s}}})(Oi)),Oi}var Sa;function vy(){return Sa||(Sa=1,(function(e){const t=at(),r=gd(),n=ko(),i=ct(),o=yd(),s=7973,a=t.getBCHDigit(s);function c(u,p,v){for(let A=1;A<=40;A++)if(p<=e.getCapacity(A,v,u))return A}function l(u,p){return i.getCharCountIndicator(u,p)+4}function h(u,p){let v=0;return u.forEach(function(A){const O=l(A.mode,p);v+=O+A.getBitsLength()}),v}function g(u,p){for(let v=1;v<=40;v++)if(h(u,v)<=e.getCapacity(v,p,i.MIXED))return v}e.from=function(p,v){return o.isValid(p)?parseInt(p,10):v},e.getCapacity=function(p,v,A){if(!o.isValid(p))throw new Error("Invalid QR Code version");typeof A>"u"&&(A=i.BYTE);const O=t.getSymbolTotalCodewords(p),b=r.getTotalCodewordsCount(p,v),D=(O-b)*8;if(A===i.MIXED)return D;const _=D-l(A,p);switch(A){case i.NUMERIC:return Math.floor(_/10*3);case i.ALPHANUMERIC:return Math.floor(_/11*2);case i.KANJI:return Math.floor(_/13);case i.BYTE:default:return Math.floor(_/8)}},e.getBestVersionForData=function(p,v){let A;const O=n.from(v,n.M);if(Array.isArray(p)){if(p.length>1)return g(p,O);if(p.length===0)return 1;A=p[0]}else A=p;return c(A.mode,A.getLength(),O)},e.getEncodedBits=function(p){if(!o.isValid(p)||p<7)throw new Error("Invalid QR Code version");let v=p<<12;for(;t.getBCHDigit(v)-a>=0;)v^=s<<t.getBCHDigit(v)-a;return p<<12|v}})(vi)),vi}var Pi={},va;function Oy(){if(va)return Pi;va=1;const e=at(),t=1335,r=21522,n=e.getBCHDigit(t);return Pi.getEncodedBits=function(o,s){const a=o.bit<<3|s;let c=a<<10;for(;e.getBCHDigit(c)-n>=0;)c^=t<<e.getBCHDigit(c)-n;return(a<<10|c)^r},Pi}var Ni={},Di,Oa;function Ry(){if(Oa)return Di;Oa=1;const e=ct();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let i,o,s;for(i=0;i+3<=this.data.length;i+=3)o=this.data.substr(i,3),s=parseInt(o,10),n.put(s,10);const a=this.data.length-i;a>0&&(o=this.data.substr(i),s=parseInt(o,10),n.put(s,a*3+1))},Di=t,Di}var Ti,Ra;function Py(){if(Ra)return Ti;Ra=1;const e=ct(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(i){let o;for(o=0;o+2<=this.data.length;o+=2){let s=t.indexOf(this.data[o])*45;s+=t.indexOf(this.data[o+1]),i.put(s,11)}this.data.length%2&&i.put(t.indexOf(this.data[o]),6)},Ti=r,Ti}var Ci,Pa;function Ny(){if(Pa)return Ci;Pa=1;const e=ct();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,i=this.data.length;n<i;n++)r.put(this.data[n],8)},Ci=t,Ci}var Li,Na;function Dy(){if(Na)return Li;Na=1;const e=ct(),t=at();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(i){return i*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let i;for(i=0;i<this.data.length;i++){let o=t.toSJIS(this.data[i]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+`
|
|
7
|
-
Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},Li=r,Li}var Mi={exports:{}},Da;function Ty(){return Da||(Da=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,l,h,g,u,p,v,A,O;!a.empty();){c=a.pop(),l=c.value,g=c.cost,u=r[l]||{};for(h in u)u.hasOwnProperty(h)&&(p=u[h],v=g+p,A=s[h],O=typeof s[h]>"u",(O||A>v)&&(s[h]=v,a.push(h,v),o[h]=l))}if(typeof i<"u"&&typeof s[i]>"u"){var b=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(b)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var i=[],o=n;o;)i.push(o),r[o],o=r[o];return i.reverse(),i},find_path:function(r,n,i){var o=t.single_source_shortest_paths(r,n,i);return t.extract_shortest_path_from_predecessor_list(o,i)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,i={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);return i.queue=[],i.sorter=r.sorter||n.default_sorter,i},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var i={value:r,cost:n};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Mi)),Mi.exports}var Ta;function Cy(){return Ta||(Ta=1,(function(e){const t=ct(),r=Ry(),n=Py(),i=Ny(),o=Dy(),s=Ed(),a=at(),c=Ty();function l(b){return unescape(encodeURIComponent(b)).length}function h(b,D,_){const L=[];let F;for(;(F=b.exec(_))!==null;)L.push({data:F[0],index:F.index,mode:D,length:F[0].length});return L}function g(b){const D=h(s.NUMERIC,t.NUMERIC,b),_=h(s.ALPHANUMERIC,t.ALPHANUMERIC,b);let L,F;return a.isKanjiModeEnabled()?(L=h(s.BYTE,t.BYTE,b),F=h(s.KANJI,t.KANJI,b)):(L=h(s.BYTE_KANJI,t.BYTE,b),F=[]),D.concat(_,L,F).sort(function(I,d){return I.index-d.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function u(b,D){switch(D){case t.NUMERIC:return r.getBitsLength(b);case t.ALPHANUMERIC:return n.getBitsLength(b);case t.KANJI:return o.getBitsLength(b);case t.BYTE:return i.getBitsLength(b)}}function p(b){return b.reduce(function(D,_){const L=D.length-1>=0?D[D.length-1]:null;return L&&L.mode===_.mode?(D[D.length-1].data+=_.data,D):(D.push(_),D)},[])}function v(b){const D=[];for(let _=0;_<b.length;_++){const L=b[_];switch(L.mode){case t.NUMERIC:D.push([L,{data:L.data,mode:t.ALPHANUMERIC,length:L.length},{data:L.data,mode:t.BYTE,length:L.length}]);break;case t.ALPHANUMERIC:D.push([L,{data:L.data,mode:t.BYTE,length:L.length}]);break;case t.KANJI:D.push([L,{data:L.data,mode:t.BYTE,length:l(L.data)}]);break;case t.BYTE:D.push([{data:L.data,mode:t.BYTE,length:l(L.data)}])}}return D}function A(b,D){const _={},L={start:{}};let F=["start"];for(let N=0;N<b.length;N++){const I=b[N],d=[];for(let m=0;m<I.length;m++){const f=I[m],E=""+N+m;d.push(E),_[E]={node:f,lastCount:0},L[E]={};for(let w=0;w<F.length;w++){const S=F[w];_[S]&&_[S].node.mode===f.mode?(L[S][E]=u(_[S].lastCount+f.length,f.mode)-u(_[S].lastCount,f.mode),_[S].lastCount+=f.length):(_[S]&&(_[S].lastCount=f.length),L[S][E]=u(f.length,f.mode)+4+t.getCharCountIndicator(f.mode,D))}}F=d}for(let N=0;N<F.length;N++)L[F[N]].end=0;return{map:L,table:_}}function O(b,D){let _;const L=t.getBestModeForData(b);if(_=t.from(D,L),_!==t.BYTE&&_.bit<L.bit)throw new Error('"'+b+'" cannot be encoded with mode '+t.toString(_)+`.
|
|
8
|
-
Suggested mode is: `+t.toString(L));switch(_===t.KANJI&&!a.isKanjiModeEnabled()&&(_=t.BYTE),_){case t.NUMERIC:return new r(b);case t.ALPHANUMERIC:return new n(b);case t.KANJI:return new o(b);case t.BYTE:return new i(b)}}e.fromArray=function(D){return D.reduce(function(_,L){return typeof L=="string"?_.push(O(L,null)):L.data&&_.push(O(L.data,L.mode)),_},[])},e.fromString=function(D,_){const L=g(D,a.isKanjiModeEnabled()),F=v(L),N=A(F,_),I=c.find_path(N.map,"start","end"),d=[];for(let m=1;m<I.length-1;m++)d.push(N.table[I[m]].node);return e.fromArray(p(d))},e.rawSplit=function(D){return e.fromArray(g(D,a.isKanjiModeEnabled()))}})(Ni)),Ni}var Ca;function Ly(){if(Ca)return gi;Ca=1;const e=at(),t=ko(),r=yy(),n=Ey(),i=wy(),o=Ay(),s=by(),a=gd(),c=Sy(),l=vy(),h=Oy(),g=ct(),u=Cy();function p(N,I){const d=N.size,m=o.getPositions(I);for(let f=0;f<m.length;f++){const E=m[f][0],w=m[f][1];for(let S=-1;S<=7;S++)if(!(E+S<=-1||d<=E+S))for(let T=-1;T<=7;T++)w+T<=-1||d<=w+T||(S>=0&&S<=6&&(T===0||T===6)||T>=0&&T<=6&&(S===0||S===6)||S>=2&&S<=4&&T>=2&&T<=4?N.set(E+S,w+T,!0,!0):N.set(E+S,w+T,!1,!0))}}function v(N){const I=N.size;for(let d=8;d<I-8;d++){const m=d%2===0;N.set(d,6,m,!0),N.set(6,d,m,!0)}}function A(N,I){const d=i.getPositions(I);for(let m=0;m<d.length;m++){const f=d[m][0],E=d[m][1];for(let w=-2;w<=2;w++)for(let S=-2;S<=2;S++)w===-2||w===2||S===-2||S===2||w===0&&S===0?N.set(f+w,E+S,!0,!0):N.set(f+w,E+S,!1,!0)}}function O(N,I){const d=N.size,m=l.getEncodedBits(I);let f,E,w;for(let S=0;S<18;S++)f=Math.floor(S/3),E=S%3+d-8-3,w=(m>>S&1)===1,N.set(f,E,w,!0),N.set(E,f,w,!0)}function b(N,I,d){const m=N.size,f=h.getEncodedBits(I,d);let E,w;for(E=0;E<15;E++)w=(f>>E&1)===1,E<6?N.set(E,8,w,!0):E<8?N.set(E+1,8,w,!0):N.set(m-15+E,8,w,!0),E<8?N.set(8,m-E-1,w,!0):E<9?N.set(8,15-E-1+1,w,!0):N.set(8,15-E-1,w,!0);N.set(m-8,8,1,!0)}function D(N,I){const d=N.size;let m=-1,f=d-1,E=7,w=0;for(let S=d-1;S>0;S-=2)for(S===6&&S--;;){for(let T=0;T<2;T++)if(!N.isReserved(f,S-T)){let V=!1;w<I.length&&(V=(I[w]>>>E&1)===1),N.set(f,S-T,V),E--,E===-1&&(w++,E=7)}if(f+=m,f<0||d<=f){f-=m,m=-m;break}}}function _(N,I,d){const m=new r;d.forEach(function(T){m.put(T.mode.bit,4),m.put(T.getLength(),g.getCharCountIndicator(T.mode,N)),T.write(m)});const f=e.getSymbolTotalCodewords(N),E=a.getTotalCodewordsCount(N,I),w=(f-E)*8;for(m.getLengthInBits()+4<=w&&m.put(0,4);m.getLengthInBits()%8!==0;)m.putBit(0);const S=(w-m.getLengthInBits())/8;for(let T=0;T<S;T++)m.put(T%2?17:236,8);return L(m,N,I)}function L(N,I,d){const m=e.getSymbolTotalCodewords(I),f=a.getTotalCodewordsCount(I,d),E=m-f,w=a.getBlocksCount(I,d),S=m%w,T=w-S,V=Math.floor(m/w),C=Math.floor(E/w),P=C+1,M=V-C,R=new c(M);let U=0;const x=new Array(w),H=new Array(w);let z=0;const G=new Uint8Array(N.buffer);for(let W=0;W<w;W++){const he=W<T?C:P;x[W]=G.slice(U,U+he),H[W]=R.encode(x[W]),U+=he,z=Math.max(z,he)}const $=new Uint8Array(m);let ee=0,Z,J;for(Z=0;Z<z;Z++)for(J=0;J<w;J++)Z<x[J].length&&($[ee++]=x[J][Z]);for(Z=0;Z<M;Z++)for(J=0;J<w;J++)$[ee++]=H[J][Z];return $}function F(N,I,d,m){let f;if(Array.isArray(N))f=u.fromArray(N);else if(typeof N=="string"){let V=I;if(!V){const C=u.rawSplit(N);V=l.getBestVersionForData(C,d)}f=u.fromString(N,V||40)}else throw new Error("Invalid data");const E=l.getBestVersionForData(f,d);if(!E)throw new Error("The amount of data is too big to be stored in a QR Code");if(!I)I=E;else if(I<E)throw new Error(`
|
|
9
|
-
The chosen QR Code version cannot contain this amount of data.
|
|
10
|
-
Minimum version required to store current data is: `+E+`.
|
|
11
|
-
`);const w=_(I,d,f),S=e.getSymbolSize(I),T=new n(S);return p(T,I),v(T),A(T,I),b(T,d,0),I>=7&&O(T,I),D(T,w),isNaN(m)&&(m=s.getBestMask(T,b.bind(null,T,d))),s.applyMask(m,T),b(T,d,m),{modules:T,version:I,errorCorrectionLevel:d,maskPattern:m,segments:f}}return gi.create=function(I,d){if(typeof I>"u"||I==="")throw new Error("No input text");let m=t.M,f,E;return typeof d<"u"&&(m=t.from(d.errorCorrectionLevel,t.M),f=l.from(d.version),E=s.from(d.maskPattern),d.toSJISFunc&&e.setToSJISFunction(d.toSJISFunc)),F(I,f,m,E)},gi}var ki={},Ui={},La;function wd(){return La||(La=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),l=Math.floor((s+o.margin*2)*c),h=o.margin*c,g=[o.color.light,o.color.dark];for(let u=0;u<l;u++)for(let p=0;p<l;p++){let v=(u*l+p)*4,A=o.color.light;if(u>=h&&p>=h&&u<l-h&&p<l-h){const O=Math.floor((u-h)/c),b=Math.floor((p-h)/c);A=g[a[O*s+b]?1:0]}n[v++]=A.r,n[v++]=A.g,n[v++]=A.b,n[v]=A.a}}})(Ui)),Ui}var Ma;function My(){return Ma||(Ma=1,(function(e){const t=wd();function r(i,o,s){i.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=s,o.width=s,o.style.height=s+"px",o.style.width=s+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(o,s,a){let c=a,l=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(l=n()),c=t.getOptions(c);const h=t.getImageWidth(o.modules.size,c),g=l.getContext("2d"),u=g.createImageData(h,h);return t.qrToImageData(u.data,o,c),r(g,l,h),g.putImageData(u,0,0),l},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const l=e.render(o,s,c),h=c.type||"image/png",g=c.rendererOpts||{};return l.toDataURL(h,g.quality)}})(ki)),ki}var xi={},ka;function ky(){if(ka)return xi;ka=1;const e=wd();function t(i,o){const s=i.a/255,a=o+'="'+i.hex+'"';return s<1?a+" "+o+'-opacity="'+s.toFixed(2).slice(1)+'"':a}function r(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function n(i,o,s){let a="",c=0,l=!1,h=0;for(let g=0;g<i.length;g++){const u=Math.floor(g%o),p=Math.floor(g/o);!u&&!l&&(l=!0),i[g]?(h++,g>0&&u>0&&i[g-1]||(a+=l?r("M",u+s,.5+p+s):r("m",c,0),c=0,l=!1),u+1<o&&i[g+1]||(a+=r("h",h),h=0)):c++}return a}return xi.render=function(o,s,a){const c=e.getOptions(s),l=o.modules.size,h=o.modules.data,g=l+c.margin*2,u=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+g+"v"+g+'H0z"/>':"",p="<path "+t(c.color.dark,"stroke")+' d="'+n(h,l,c.margin)+'"/>',v='viewBox="0 0 '+g+" "+g+'"',O='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+v+' shape-rendering="crispEdges">'+u+p+`</svg>
|
|
12
|
-
`;return typeof a=="function"&&a(null,O),O},xi}var Ua;function Uy(){if(Ua)return yt;Ua=1;const e=gy(),t=Ly(),r=My(),n=ky();function i(o,s,a,c,l){const h=[].slice.call(arguments,1),g=h.length,u=typeof h[g-1]=="function";if(!u&&!e())throw new Error("Callback required as last argument");if(u){if(g<2)throw new Error("Too few arguments provided");g===2?(l=a,a=s,s=c=void 0):g===3&&(s.getContext&&typeof l>"u"?(l=c,c=void 0):(l=c,c=a,a=s,s=void 0))}else{if(g<1)throw new Error("Too few arguments provided");return g===1?(a=s,s=c=void 0):g===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(p,v){try{const A=t.create(a,c);p(o(A,s,c))}catch(A){v(A)}})}try{const p=t.create(a,c);l(null,o(p,s,c))}catch(p){l(p)}}return yt.create=t.create,yt.toCanvas=i.bind(null,r.render),yt.toDataURL=i.bind(null,r.renderToDataURL),yt.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),yt}var xy=Uy();const Hy="/__hb_sdk__/dev-context";function Nn(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=oc(e.localDevGrant);return!r.valid||!e.devSessionId?.trim()||!Number.isSafeInteger(e.contextRevision)||e.contextRevision!==r.grant.revision||!e.expiresAt||!Number.isFinite(e.expiresAt)||e.source!=="remote"&&e.expiresAt<=t?{...e,localDevGrant:void 0,warning:"本地临时授权无效或已过期,已降权"}:{...e,...e.expiresAt<=t?{source:"anonymous",localDevLaunchToken:void 0,expiresAt:t+3e4}:{},localDevGrant:Al({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,revision:r.grant.revision,eligiblePermissionKeys:e.platforms?.some(n=>["windows","macos","linux"].includes(n))?["network","companion","appProtocol"]:["network","appProtocol"]})}}function Fy(e){if(!eo(e)||!xa(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!eo(t)||!xa(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const By={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Wn(e){const t=Je(e.localDevGrant?Eo({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}).runtimePermissions:e.runtimePermissions),r=t.permissions.network;return t.valid&&r?{networkRequest:{status:r.status,useOfficialDomain:r.config.useOfficialDomain===!0}}:zy()}function Vy(e,t,r){return r?.localDevGrant?Eo({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:Ad(e,t,t.networkRequest.useOfficialDomain)}function qy(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=Wn({...e,localDevGrant:void 0});return Ad(e.runtimePermissions,t,!1)}function zy(){return{networkRequest:{...By.networkRequest}}}function Ad(e,t,r){const n=Je(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of ar){const a=n.permissions[s];a&&i.push(s==="network"?{key:s,status:t.networkRequest.status,config:{useOfficialDomain:r}}:{key:s,status:a.status,config:{}})}const o=eo(e)&&typeof e.revision=="number"&&Number.isInteger(e.revision)&&e.revision>=0?e.revision:void 0;return{schema_version:1,...o===void 0?{}:{revision:o},entries:i}}function eo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function xa(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function Gy(e){let t,r=!1,n=!1,i;return{invalidate(a){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(a,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=o().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function o(){let a={ok:!0};for(;r&&!n;){r=!1;const c=new AbortController;t=c;let l;try{l=await e.fetch(c.signal)}catch(g){a={ok:!1},!n&&!c.signal.aborted&&s(g);continue}finally{t===c&&(t=void 0)}if(n)return{ok:!1};let h;try{h=e.apply(l)}catch(g){a={ok:!1},n||s(g);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(h))try{await e.onChanged(h)}catch(g){a={ok:!1},n||s(g)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function jy(e){return Gy({apply:e.applyStatus,fetch:e.fetchStatus,hasChanged:t=>t.changed,onChanged:t=>e.reconcile(t.status),onError:e.onError,shouldSkip:t=>t!==void 0&&t<=e.getCanonicalRevision()})}function $y(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,o;return{schedule:s,reset(){n=t,a()},dispose(){i||(i=!0,a())}};function s(){i||e.isDisposed()||(a(),o=e.timers.setTimeout(async()=>{o=void 0;let c;try{c=await e.invalidate()}catch{c={ok:!1}}if(!(i||e.isDisposed())){if(c.ok){n=t,e.connectEvents();return}n=Math.min(n*2,r),s()}},n))}function a(){o!==void 0&&e.timers.clearTimeout(o),o=void 0}}const Wy={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};function Ky(e){return new Promise((t,r)=>{if(e.signal.aborted){r(e.signal.reason);return}const n=document.createElement("div");n.className="hb-sdk-auth-dialog",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.innerHTML=`
|
|
13
|
-
<div class="hb-sdk-auth-dialog__panel">
|
|
14
|
-
<h2>授权请求</h2>
|
|
15
|
-
<p class="hb-sdk-auth-dialog__app">${Hi(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
|
|
16
|
-
<ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(a=>`<li>${Hi(Wy[a]||a)}</li>`).join("")}</ul>
|
|
17
|
-
${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${Hi(e.userProfile.nickname)}</p>`:""}
|
|
18
|
-
<div class="hb-sdk-auth-dialog__actions">
|
|
19
|
-
<button type="button" data-action="deny">拒绝</button>
|
|
20
|
-
<button type="button" class="primary" data-action="allow">允许</button>
|
|
21
|
-
</div>
|
|
22
|
-
</div>
|
|
23
|
-
`;const i=a=>{s(),t(a)},o=()=>{s(),r(e.signal.reason)},s=()=>{e.signal.removeEventListener("abort",o),n.remove()};n.querySelector('[data-action="allow"]')?.addEventListener("click",()=>{i({status:"granted",grantedScopes:[...e.scopes]})}),n.querySelector('[data-action="deny"]')?.addEventListener("click",()=>{i({status:"cancelled"})}),e.signal.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n)})}function Hi(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Yy(e){return{launchUrl:e.launchUrl,sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:jo,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,platformAccess:{source:"manifest",manifest:{platforms:$n},sdkVersion:jo},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const Ha="hb-sdk-action-dialog-style";function Kn(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}eE();const n=document.createElement("div");n.className="hb-sdk-action-dialog",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.innerHTML=`
|
|
24
|
-
<div class="hb-sdk-action-dialog__panel">
|
|
25
|
-
<h2>${Fa(e.title)}</h2>
|
|
26
|
-
<pre class="hb-sdk-action-dialog__detail">${Fa(e.detail)}</pre>
|
|
27
|
-
<div class="hb-sdk-action-dialog__actions">
|
|
28
|
-
<button type="button" class="primary" data-action="confirm">确定</button>
|
|
29
|
-
</div>
|
|
30
|
-
</div>
|
|
31
|
-
`;const i=()=>{s(),t()},o=()=>{s(),r(e.signal?.reason)},s=()=>{e.signal?.removeEventListener("abort",o),n.remove()};n.querySelector('[data-action="confirm"]')?.addEventListener("click",i),e.signal?.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n)})}async function Qy(e,t){await Kn({title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+Rt(e.params)].join(`
|
|
32
|
-
`),signal:t.signal})}async function Jy(e,t){await Kn({title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+Rt(e.extra)].join(`
|
|
33
|
-
`),signal:t.signal})}async function Xy(e,t){await Kn({title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+Rt(e.channel),"post: "+Rt(e.post)].join(`
|
|
34
|
-
`),signal:t.signal})}async function Zy(e,t){await Kn({title:"截图分享",detail:["rect: "+Rt(e.rect),"post: "+Rt(e.post)].join(`
|
|
35
|
-
`),signal:t.signal})}function Rt(e){return JSON.stringify(e,null,2)}function Fa(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function eE(){if(document.getElementById(Ha))return;const e=document.createElement("style");e.id=Ha,e.textContent=`
|
|
36
|
-
.hb-sdk-action-dialog {
|
|
37
|
-
position: absolute;
|
|
38
|
-
inset: 0;
|
|
39
|
-
z-index: 40;
|
|
40
|
-
display: grid;
|
|
41
|
-
place-items: center;
|
|
42
|
-
padding: 24px;
|
|
43
|
-
background: rgba(15, 23, 42, 0.45);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
.hb-sdk-action-dialog__panel {
|
|
47
|
-
width: min(420px, 100%);
|
|
48
|
-
border-radius: 12px;
|
|
49
|
-
padding: 20px;
|
|
50
|
-
background: #fff;
|
|
51
|
-
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
.hb-sdk-action-dialog__panel h2 {
|
|
55
|
-
margin: 0 0 8px;
|
|
56
|
-
font-size: 18px;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
.hb-sdk-action-dialog__detail {
|
|
60
|
-
margin: 0 0 16px;
|
|
61
|
-
max-height: 40vh;
|
|
62
|
-
overflow: auto;
|
|
63
|
-
color: #1f2933;
|
|
64
|
-
font-family: inherit;
|
|
65
|
-
font-size: 12px;
|
|
66
|
-
line-height: 1.6;
|
|
67
|
-
white-space: pre-wrap;
|
|
68
|
-
overflow-wrap: anywhere;
|
|
69
|
-
word-break: break-word;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
.hb-sdk-action-dialog__actions {
|
|
73
|
-
display: flex;
|
|
74
|
-
justify-content: flex-end;
|
|
75
|
-
gap: 8px;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
.hb-sdk-action-dialog__actions button {
|
|
79
|
-
min-height: 36px;
|
|
80
|
-
border: 1px solid #cad5e2;
|
|
81
|
-
border-radius: 6px;
|
|
82
|
-
padding: 0 12px;
|
|
83
|
-
background: #fff;
|
|
84
|
-
cursor: pointer;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
.hb-sdk-action-dialog__actions .primary {
|
|
88
|
-
border-color: #2563eb;
|
|
89
|
-
color: #fff;
|
|
90
|
-
background: #2563eb;
|
|
91
|
-
}
|
|
92
|
-
`,document.head.appendChild(e)}const tE=44;function rE(e){const t=()=>e.isCapsuleHidden?.()?0:tE;return{...e.applyDisplay?{applyOrientation:async(r,n)=>(await e.applyDisplay(r,n.signal),{supported:!0})}:{},...e.onViewportChange?{onViewportChange:e.onViewportChange}:{},close:async()=>{await e.close()},reload:async()=>{await e.reload()},getViewportMetrics:()=>{const r=e.getDeviceMetrics?.();return r?{windowWidth:r.screenWidth,windowHeight:r.screenHeight,screenWidth:r.screenWidth,screenHeight:r.screenHeight,pixelRatio:r.pixelRatio,safeArea:{top:r.safeAreaInsets.top+t(),right:r.screenWidth-r.safeAreaInsets.right,bottom:r.screenHeight-r.safeAreaInsets.bottom,left:r.safeAreaInsets.left}}:{windowWidth:window.innerWidth,windowHeight:window.innerHeight,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}},getNavigationBarHeight:()=>{const r=e.getDeviceMetrics?.().statusBarHeight;return r===void 0?0:r+t()},setNavigationBarStyle:r=>{document.documentElement.dataset.navigationBarStyle=r,e.onNavigationBarStyleChange?.(r)},setClipboard:async({text:r})=>{await navigator.clipboard.writeText(r)},showToast:async({message:r,status:n})=>{e.pushLog("host.message",{message:r,status:n}),await $d({message:r,status:n})},showLoading:jd,hideLoading:Gd,vibrate:zd,openAppPage:Qy,openWindow:Jy,showShareMenu:Xy,captureAndShare:Zy,setScreenshotChromeHidden:qd}}const Ba=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],Cr=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Va={"launch-only":[],stdio:["stdio"],full:["stdio","attachments","notifications"],"prepare-fail":[],"prepare-cancel":[],"launch-cancel":[],"os-blocked":[],"normal-exit":["stdio"],crash:["stdio"],"output-limit":["stdio"]};class nE{port;presentation;now;schedule;clearSchedule;onDiagnostic;preparations=new Map;sessions=new Map;eventSink;sessionEventListeners=new Set;nextSessionId=0;constructor(t={}){this.now=t.now??Date.now,this.schedule=t.schedule??((r,n)=>setTimeout(r,n)),this.clearSchedule=t.clearSchedule??(r=>clearTimeout(r)),this.onDiagnostic=t.onDiagnostic??(()=>{}),this.port={getInfo:async r=>this.getInfo(r),getPreparationStatus:async r=>this.getPreparationStatus(r),prepare:(r,n)=>this.prepare(r,n),cancelPreparation:async r=>this.cancelPreparation(r),getActiveSession:async r=>this.getActiveSession(r),launch:async r=>this.launch(r),write:async r=>this.write(r),closeStdin:async r=>this.closeStdin(r),terminate:async r=>this.terminate(r),ackOutput:async r=>this.ackOutput(r),openAttachment:async r=>this.openAttachment(r),showNotification:async r=>this.showNotification(r),onSessionEvent:r=>(this.sessionEventListeners.add(r),()=>this.sessionEventListeners.delete(r))},this.presentation={confirmCompanionOperation:async({action:r,companion:n})=>{const i=n.alias===`${r}-cancel`;return this.diagnostic(`authorization.${i?"cancelled":"granted"}`,n.alias,{action:r}),i?{status:"cancelled"}:{status:"granted"}}}}bindEventSink(t){this.eventSink=t,this.diagnostic(t?"runtime.connected":"runtime.disconnected")}reset(t){const r=t?[t]:[...Ba];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(ae("COMPANION_PREPARATION_CANCELLED","固定 Fake 已重置")),this.preparations.delete(n),this.sessions.delete(n)}this.diagnostic("reset",t)}getInfo(t){const r=this.readAlias(t);return{alias:r,displayName:`Browser Fake: ${r}`,target:r==="os-blocked"?"macos-arm64":"windows-x64",capabilities:Va[r],archiveBytes:12,signatureStatus:"unsigned"}}getPreparationStatus(t){const r=this.readAlias(t);return this.preparations.get(r)?.status??{state:"not-prepared"}}prepare(t,r){const n=this.readAlias(t),i=this.preparations.get(n);if(i?.status.state==="ready")return Promise.resolve(this.getInfo(n));if(i?.operation)return i.operation.listeners.add(r.onProgress),this.diagnostic("prepare.joined",n),r.onProgress(i.status.state==="preparing"?i.status.progress:Cr[0]),i.operation.promise;let o,s;const a=new Promise((l,h)=>{o=l,s=h}),c={cancelled:!1,listeners:new Set([r.onProgress]),promise:a,reject:s,resolve:o,timers:new Set};{const l={status:{state:"preparing",progress:Cr[0]},operation:c};this.preparations.set(n,l),this.diagnostic("prepare.started",n),Cr.forEach((h,g)=>{const u=this.schedule(()=>{if(c.timers.delete(u),!c.cancelled){l.status={state:"preparing",progress:h};try{c.listeners.forEach(p=>p(h))}catch(p){c.cancelled=!0;for(const v of c.timers)this.clearSchedule(v);l.operation=void 0,l.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",n,{message:p instanceof Error?p.message:String(p)}),c.reject(p);return}if(this.diagnostic("prepare.progress",n,{phase:h.phase}),g===Cr.length-1){if(l.operation=void 0,n==="prepare-fail"){l.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},c.reject(ae("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",n,{code:"COMPANION_INTEGRITY_FAILED"});return}l.status={state:"ready",preparedAt:this.now()},c.resolve(this.getInfo(n)),this.diagnostic("prepare.ready",n)}}},g+1);c.timers.add(u)})}return a}cancelPreparation(t){const r=this.readAlias(t),n=this.preparations.get(r);if(n?.operation){n.operation.cancelled=!0;for(const i of n.operation.timers)this.clearSchedule(i);n.operation.reject(ae("COMPANION_PREPARATION_CANCELLED","准备已取消")),n.operation=void 0,n.status={state:"not-prepared"},this.diagnostic("prepare.cancelled",r)}}getActiveSession(t){const r=this.readAlias(t),n=this.sessions.get(r);if(!n||n.exited)return;const i=n.snapshot.controllerGeneration;return n.snapshot={...n.snapshot,controllerGeneration:i+1},this.emit(ul,{sessionId:n.snapshot.id,controllerGeneration:i}),n.waitingOutput&&(n.queuedOutput.unshift(n.waitingOutput),n.waitingOutput=void 0,this.flushOutput(n)),this.diagnostic("session.controller-transferred",r,{controllerGeneration:n.snapshot.controllerGeneration}),{...n.snapshot,capabilities:[...n.snapshot.capabilities]}}launch(t){const r=this.readAlias(t);if(this.getPreparationStatus(r).state!=="ready")throw ae("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw ae("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw ae("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:Va[r],state:"running",controllerGeneration:1},o={snapshot:i,stdinClosed:!1,exited:!1,queuedOutput:[]};return this.sessions.set(r,o),this.diagnostic("session.launched",r,{capabilities:[...i.capabilities],sessionId:i.id}),i.capabilities.includes("stdio")&&this.schedule(()=>{this.queueOutput(o,"stdout",1,`fake:ready
|
|
93
|
-
`),this.queueOutput(o,"stderr",1,`fake:diagnostic
|
|
94
|
-
`)},20),r==="normal-exit"&&this.schedule(()=>this.requestExit(o,{reason:"exited",exitCode:0}),40),r==="crash"&&this.schedule(()=>this.requestExit(o,{reason:"crashed",exitCode:1}),40),r==="output-limit"&&this.schedule(()=>this.requestExit(o,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("stdio"))throw ae("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw ae("COMPANION_PIPE_CLOSED","stdin 已关闭");const n=Math.max(1,...r.queuedOutput.map(i=>i.sequence),r.waitingOutput?.sequence??0)+1;this.queueOutput(r,"stdout",n,new Uint8Array(t.data)),this.diagnostic("stdio.write",r.snapshot.alias,{bytes:t.data.byteLength})}closeStdin(t){const r=this.readController(t);r.stdinClosed=!0,this.diagnostic("stdio.closed",r.snapshot.alias)}terminate(t){const r=this.readController(t);this.exit(r,{reason:"terminated"})}ackOutput(t){const r=this.readController(t),n=r.waitingOutput;!n||n.stream!==t.stream||n.sequence!==t.sequence||(r.waitingOutput=void 0,this.diagnostic("stdio.ack",r.snapshot.alias,{sequence:t.sequence,stream:t.stream}),this.flushOutput(r))}openAttachment(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("attachments"))throw ae("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw ae("COMPANION_ATTACHMENT_NOT_FOUND","固定 Fake Attachment 不存在");this.diagnostic("attachment.opened",r.snapshot.alias,{id:t.id});const n=new TextEncoder().encode(`Browser Fake Companion report
|
|
95
|
-
`);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw ae("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw ae("FILE_ACCESS_DENIED","Attachment 只读")},stat:async()=>({kind:"file",size:n.byteLength})}}showNotification(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("notifications"))throw ae("COMPANION_NOTIFICATION_UNAVAILABLE","notifications 未启用");this.diagnostic("notification.shown",r.snapshot.alias,{category:t.category})}queueOutput(t,r,n,i){t.queuedOutput.push({stream:r,sequence:n,data:typeof i=="string"?new TextEncoder().encode(i):i}),this.flushOutput(t)}flushOutput(t){if(t.exited||t.waitingOutput||!this.eventSink&&this.sessionEventListeners.size===0)return;const r=t.queuedOutput.shift();if(!r){t.pendingExit&&this.exit(t,t.pendingExit);return}t.waitingOutput=r,this.emit(dl,{sessionId:t.snapshot.id,controllerGeneration:t.snapshot.controllerGeneration,...r}),this.diagnostic("stdio.chunk",t.snapshot.alias,{bytes:r.data.byteLength,sequence:r.sequence,stream:r.stream})}requestExit(t,r){t.pendingExit=r,!t.waitingOutput&&t.queuedOutput.length===0&&this.exit(t,r)}exit(t,r){t.exited||(t.exited=!0,t.pendingExit=void 0,t.waitingOutput=void 0,t.queuedOutput.length=0,this.emit(ll,{sessionId:t.snapshot.id,exit:r}),this.diagnostic("session.exit",t.snapshot.alias,{...r}))}readController(t){const r=[...this.sessions.values()].find(n=>n.snapshot.id===t.sessionId);if(!r||r.exited)throw ae("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw ae("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!Ba.includes(t))throw ae("COMPANION_NOT_DECLARED","未知固定 Companion Fake 场景");return t}emit(t,r){this.eventSink?.(t,r),this.sessionEventListeners.forEach(n=>n({type:t,payload:r}))}diagnostic(t,r,n){this.onDiagnostic({action:t,...r?{alias:r}:{},...n?{detail:n}:{}})}}const iE=Object.freeze({[Tn]:!0,[Cn]:!0,[Ln]:!0,[Mn]:!0,[kn]:!0,[Un]:!0,[xn]:!0,[Hn]:!0,[Fn]:!0,[Bn]:!0,[Vn]:!0,[qn]:!0,[ir]:!0,[nr]:!0,[or]:!0});function oE(e){return new nE(e)}function ae(e,t){return Object.assign(new Error(t),{code:e})}const sE=/^[A-Za-z0-9_-]{22}$/,aE="https://api.xiaoheihe.cn/open_inapp/";function cE(e){const t=typeof e.port=="number"?e.port:Number(e.port);if(!Number.isInteger(t)||t<=0||t>65535)throw new TypeError("Mobile launch redirect port is invalid");if(!sE.test(e.token))throw new TypeError("Mobile launch redirect token is invalid");const r=new URL(`http://${e.host}:${t}/l/${e.token}`);if(r.protocol!=="http:"||r.hostname!==e.host||r.port!==String(t)||r.username||r.password||r.search||r.hash)throw new TypeError("Mobile launch redirect host is invalid");return r.href}function dE(e){const t=new URL(e);if(t.protocol!=="http:"||t.username||t.password)throw new TypeError("Mobile launch redirect URL must be an HTTP URL without credentials");const r=`heybox://${encodeURIComponent(JSON.stringify({protocol_type:"openWindow",full_screen:!0,navigation_bar:{title:""},webview:{url:t.href,pull:!1,refresh:!1}}))}`;return`${aE}#${r}`}function lE(e){const t=Je(e.runtimePermissions),r=Eo({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[];for(const[i,o]of[["network","Network"],["companion","Companion"],["appProtocol","AppProtocol"]]){if(!e.declaredPermissions?.[i]?.enabled)continue;const s=t.valid&&t.permissions[i]?.status==="enabled",a=r.temporaryPermissionKeys.includes(i);n.push({key:i,label:o,state:s?"approved":a?"temporary":"unavailable",...i==="appProtocol"?{highestRisk:!0}:{},...!s&&!a?{reason:i==="appProtocol"?"最高危险权限:可执行任意协议并绕过其他 SDK 能力权限;当前没有有效临时授权,线上未批准":"没有有效的本地临时授权,线上未批准"}:{}})}if(e.declaredPermissions?.network?.useOfficialDomain){const i=t.valid&&t.permissions.network?.status==="enabled"&&t.permissions.network.config.useOfficialDomain===!0;n.push({key:"network.useOfficialDomain",label:"官方域名",state:i?"approved":"unavailable",...i?{}:{reason:"不支持本地临时授权,获得线上批准后才能使用"}})}return n}function rt(e){return JSON.stringify({source:e.source,miniProgramId:e.miniProgramId,devSessionId:e.devSessionId,contextRevision:e.contextRevision,declaredPermissions:e.declaredPermissions,runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant,companionManifestSha256:e.companionManifestSha256})}const uE="__hb_sdk_mini_dev__",fE="hb-sdk:mini-dev-console",hE="__hb_sdk_mini_dev_console_installed__",qa=hE;function mE(e,t=console){gE(t,e,t)}const pE=["log","debug","info","warn","error"];function gE(e,t,r){if(!r||r[qa]===!0)return!1;let n=!1;for(const i of pE){const o=e[i];if(typeof o!="function")continue;const s=function(...a){try{t(i,a)}catch{}return o.apply(this,a)};try{e[i]=s,n=!0}catch{return n}}return n&&(r[qa]=!0),n}const to=1,za=64*1024,yE=64,EE=/^[A-Za-z0-9_-]{22}$/;class pe extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function wE(e,t=!1){const r=bE(e,t);switch(ro(r,"Server message"),IE(r),r.type){case"grant":return Yt(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),Qt(r.connectionEpoch,"connectionEpoch"),nt(r.nextClientSequence,"nextClientSequence"),nt(r.nextServerSequence,"nextServerSequence"),Ga(r.snapshot),r;case"event":return Yt(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),Qt(r.connectionEpoch,"connectionEpoch"),nt(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&Ye("event must be account.changed or status.changed"),Ga(r.snapshot),r;case"heartbeat":return Yt(r,["version","type","connectionEpoch","sequence"],"heartbeat"),Qt(r.connectionEpoch,"connectionEpoch"),nt(r.sequence,"sequence"),r;default:return Ye("Unknown server message type")}}function AE(e){const t=e.connectionEpoch;Qt(t,"connectionEpoch"),nt(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(Qt(n.connectionEpoch,"connectionEpoch"),nt(n.sequence,"sequence"),n.connectionEpoch!==t)throw new pe("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new pe("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new pe("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function bE(e,t){if(t)throw new pe("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new pe("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>za)throw new pe("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>za)throw new pe("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return _E(e),JSON.parse(e)}catch(r){throw r instanceof pe?r:new pe("INVALID_JSON","Channel frame must contain strict JSON")}}function Ga(e){ro(e,"snapshot"),Yt(e,["account","permissions"],"snapshot"),ro(e.account,"snapshot.account"),Yt(e.account,["revision"],"snapshot.account"),nt(e.account.revision,"snapshot.account.revision"),Fy(e.permissions)||Ye("snapshot.permissions is invalid")}function IE(e){e.version!==to&&Ye("version must be 1")}function ro(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Ye(`${t} must be a plain JSON object`)}function Yt(e,t,r,n=[]){const i=Object.keys(e);(t.some(o=>!Object.hasOwn(e,o))||i.some(o=>!t.includes(o)&&!n.includes(o)))&&Ye(`${r} fields are invalid`)}function nt(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Ye(`${t} must be a non-negative safe integer`)}function Qt(e,t){(typeof e!="string"||!EE.test(e))&&Ye(`${t} must be a 22-character base64url value`)}function Ye(e){throw new pe("INVALID_MESSAGE",e)}function _E(e){new SE(e).scan()}class SE{constructor(t){this.source=t}position=0;scan(){if(this.skipWhitespace(),this.scanValue(),this.skipWhitespace(),this.position!==this.source.length)throw new SyntaxError("Unexpected trailing JSON data")}scanValue(t=0){const r=this.source[this.position];if(r==="{"||r==="["){if(t>=yE)throw new pe("INVALID_JSON","Channel JSON exceeds maximum nesting depth");return r==="{"?this.scanObject(t):this.scanArray(t)}if(r==='"'){this.scanString();return}this.scanPrimitive()}scanObject(t){this.position+=1,this.skipWhitespace();const r=new Set;if(!this.consume("}"))for(;;){if(this.source[this.position]!=='"')throw new SyntaxError("JSON object key must be a string");const n=this.scanString(),i=JSON.parse(n);if(typeof i!="string")throw new SyntaxError("JSON object key must be a string");if(r.has(i))throw new pe("INVALID_JSON","Channel JSON contains a duplicate key");if(r.add(i),this.skipWhitespace(),!this.consume(":"))throw new SyntaxError("Missing JSON object colon");if(this.skipWhitespace(),this.scanValue(t+1),this.skipWhitespace(),this.consume("}"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON object comma");this.skipWhitespace()}}scanArray(t){if(this.position+=1,this.skipWhitespace(),!this.consume("]"))for(;;){if(this.scanValue(t+1),this.skipWhitespace(),this.consume("]"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON array comma");this.skipWhitespace()}}scanString(){const t=this.position;for(this.position+=1;this.position<this.source.length;){const r=this.source[this.position];if(r==='"')return this.position+=1,this.source.slice(t,this.position);r==="\\"?this.position+=2:this.position+=1}throw new SyntaxError("Unterminated JSON string")}scanPrimitive(){const t=this.position;for(;this.position<this.source.length&&!/[\s,\]}]/.test(this.source[this.position]??"");)this.position+=1;if(t===this.position)throw new SyntaxError("Missing JSON value")}skipWhitespace(){for(;/[\t\n\r ]/.test(this.source[this.position]??"");)this.position+=1}consume(t){return this.source[this.position]!==t?!1:(this.position+=1,!0)}}const ja=[1e3,2e3,4e3,8e3,15e3];function vE(e){const t=new Set,r=e.webSocketFactory??(f=>new WebSocket(f)),n=e.randomValues??(f=>crypto.getRandomValues(f)),i=e.timers??{clearTimeout:f=>window.clearTimeout(f),setTimeout:(f,E)=>window.setTimeout(f,E)},o=e.onlineTarget??(typeof window>"u"?void 0:window),s=e.visibilityTarget??(typeof document>"u"?void 0:document),a=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let c,l,h,g=!1,u=0,p,v=!1,A=!1;const O=new Set,b=(f,E)=>{if(!(!e.onDiagnostic||O.has(f))){O.add(f);try{e.onDiagnostic({phase:f,...E?{code:E}:{}})}catch{}}},D=(f,E,w=!1)=>{if(h&&f.account.revision<h.account.revision)return;const S=h&&JSON.stringify(f)===JSON.stringify(h);if(h=f,!(S&&!w))for(const T of t)T(f,E)},_=()=>{if(g||p!==void 0||c)return;const f=ja[Math.min(u,ja.length-1)];u+=1,p=i.setTimeout(()=>{p=void 0,m()},f)},L=()=>{g||!v||c||(p!==void 0&&(i.clearTimeout(p),p=void 0),m())},F=()=>{a()&&L()},N=()=>{s&&!s.hidden&&L()},I=()=>{A||(A=!0,o?.addEventListener("online",F),s?.addEventListener("visibilitychange",N))},d=()=>{A&&(A=!1,o?.removeEventListener("online",F),s?.removeEventListener("visibilitychange",N))},m=()=>{if(g||c)return;v=!0,I(),p!==void 0&&(i.clearTimeout(p),p=void 0);let f,E;try{f=r(e.url)}catch{b("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),_();return}try{E=RE(n)}catch{b("entropy","NONCE_GENERATION_FAILED");try{f?.close(1011,"channel initialization failed")}catch{}_();return}c=f;let w,S,T;const V=()=>{f.removeEventListener("open",P),f.removeEventListener("message",M),f.removeEventListener("close",R),f.removeEventListener("error",U),l===V&&(l=void 0)},C=()=>{if(c===f){c=void 0,V();try{f.close(1008,"invalid channel state")}catch{}_()}},P=()=>{if(!(g||c!==f))try{f.send(JSON.stringify({version:to,type:"hello",csrfToken:e.csrfToken,clientNonce:E}))}catch{b("send","HELLO_SEND_FAILED"),C()}},M=x=>{if(g||c!==f)return;if(typeof x.data!="string"){b("parse","TEXT_FRAME_REQUIRED"),C();return}let H;try{H=wE(x.data)}catch(z){b("parse",z instanceof pe?z.code:"INVALID_MESSAGE"),C();return}if(H.type==="grant"){if(T){b("sequence","DUPLICATE_GRANT"),C();return}w=H.connectionEpoch,S=H.nextClientSequence,T=AE({connectionEpoch:w,nextSequence:H.nextServerSequence}),u=0,O.clear(),D(H.snapshot,{type:"grant"});return}if(!T||!w||S===void 0){b("sequence","MESSAGE_BEFORE_GRANT"),C();return}try{T.accept(H)}catch{b("sequence","INVALID_SEQUENCE"),C();return}if(H.type==="heartbeat"){try{f.send(JSON.stringify({version:to,type:"heartbeat.ack",connectionEpoch:w,sequence:S}))}catch{b("send","HEARTBEAT_ACK_SEND_FAILED"),C()}S=S===Number.MAX_SAFE_INTEGER?void 0:S+1;return}D(H.snapshot,{type:"event",event:H.event},!0)},R=()=>{c===f&&(b("close","SOCKET_CLOSED"),c=void 0,V(),_())},U=()=>{b("open","SOCKET_ERROR"),C()};f.addEventListener("open",P),f.addEventListener("message",M),f.addEventListener("close",R),f.addEventListener("error",U),l=V};return{connect:m,subscribeUpdates(f){return t.add(f),()=>t.delete(f)},dispose(){if(g)return;g=!0,v=!1,d(),p!==void 0&&i.clearTimeout(p),p=void 0;const f=c;c=void 0,l?.(),f?.close(1e3,"client disposed"),t.clear()}}}function OE(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,o=e[n+1],s=e[n+2];r+=t[i>>2],r+=t[(i&3)<<4|(o??0)>>4],o!==void 0&&(r+=t[(o&15)<<2|(s??0)>>6]),s!==void 0&&(r+=t[s&63])}return r}function RE(e){const t=e(new Uint8Array(16));if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("Channel nonce source must fill 16 bytes");const r=OE(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}try{mE((e,t)=>{mr(`console.${e}`,{source:"host",message:t.map(r=>Od(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const PE="/__hb_sdk_bootstrap__",NE="/__hb_sdk__/mobile-launch-redirect",DE="/__hb_sdk__/network",TE="/session/status",CE="/session/request",LE="/session/events",ME=320,kE=1e3,UE=1e3,xE=15e3,$a="dark",bd=new URL(location.href).searchParams,Id=bd.get("mini_url"),dt=bd.get("ui_preview")==="1",Y={device:Ft("#device"),get mobileLanSelect(){return Ft("#mobile-lan-select")},get mobileQrImage(){return Ft("#mobile-qr-image")},get mobileQrStatus(){return Ft("#mobile-qr-status")},storageSnapshot:Ft("#storage-snapshot")};if(!Id&&!dt)throw Y.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const _d=Id??"about:blank",ie=await Ho();j.openPlatformBaseUrl=ie.openPlatformBaseUrl;j.devReadiness=ie.devReadiness;j.miniProgramSupportsDesktop=ie.miniProgramSupportsDesktop;j.desktopLaunch.workspaceCardsEnabled=ie.workspaceCardsEnabled;let Fe=ie.lanAddresses,Fr=ie.defaultLanAddressId,wt=ie.mobileLaunchRedirect,Uo=ie.nativeAppLaunchUnavailableReason,Br=ie.devSessionId,no=ie.miniProgramManifestAccessToken,zt=ie.workspaceCardsEnabled,Vr=ie,xo=Jn(ie),fe=ie.devContext,ge=Nn(fe);Bo();let Pt=Wn(ge),Q=!1,Yn=0;const Qn=new AbortController;let Le=0,It,lr,qr=0,We,io,oo,Be=0,Ke=!1,zr,so,Fi=!1;const Jt=el({apply:tl,waitForLayout:async e=>{await rl(),await nl(e),await il(e)}});let ao,co,Wa=Date.now(),Gt=!1,Ka=Promise.resolve(),Xt=-1,ur=!1,it,lo,uo,Gr,et;const Dn=new Set,fo=oE({onDiagnostic:({action:e,alias:t,detail:r})=>Ae(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Nt=jy({applyStatus:e=>Td(e,!0),fetchStatus:e=>Dd(Hd(Qn.signal,e)),getCanonicalRevision:()=>Xt,onError:lw,reconcile:()=>YE(Yn)}),ho=$y({connectEvents:Cd,invalidate:()=>Nt.invalidate(),isDisposed:()=>Q,maxDelayMs:xE,minDelayMs:UE,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let Bi=0,jt="",Vi=!1,mo;await po(!1);kd();xd(Ud(ie));dt&&VE();Xn();dt||await vd();await wr("initial");dt||(Cd(),WE());HE();ZE();function Sd(){!dt&&!Q&&(mo=window.setTimeout(()=>{vd().finally(Sd)},1e3))}Sd();async function vd(){if(!(Vi||Q)){Vi=!0;try{const e=await fetch(`/__hb_sdk__/device-logs?after=${Bi}&limit=500`,{signal:AbortSignal.any([Qn.signal,AbortSignal.timeout(5e3)])});if(!e.ok)return;const t=await e.json();if(Q)return;if(jt&&t.epoch!==jt){Bi=0,jt=t.epoch;return}jt=t.epoch,j.logDevices=t.devices,t.gap&&mr("console.warn",{message:"部分设备日志已超出服务器缓冲,存在日志缺口"});for(const r of t.items){const n=Wd(r.method||`console.${r.level}`,{...r,source:"app"},r.timestamp,r.level==="debug"?"log":r.level);n.source=r.source,n.summary=r.message,n.detail=r,n.deviceSessionId=r.deviceSessionId,n.deviceName=t.devices.find(i=>i.id===r.deviceSessionId)?.name,n.dedupeKey=void 0,Ya(n)}Bi=t.nextCursor}catch{}finally{Vi=!1}}}function HE(){window.addEventListener("beforeunload",uw),window.addEventListener("hb-sdk:restart-runtime",Pd),window.addEventListener("hb-sdk:refresh-storage",Xn),window.addEventListener("hb-sdk:qr-open-change",Rd),window.addEventListener("message",FE),ao=Kd(()=>document.querySelector("#host-fullscreen-exit-mount")),co=Yd(()=>j.devicePresetId,()=>Jt.notifyViewportChange(),{flush:"post"})}function FE(e){const t=e.data;if(e.source===null||!ue(t)||t.type!==fE||!ue(t.detail))return;const r=t.detail;r.level!=="log"&&r.level!=="debug"&&r.level!=="info"&&r.level!=="warn"&&r.level!=="error"||!Array.isArray(r.args)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||mr(`console.${r.level}`,{source:"app",message:r.args.map(n=>Od(n)).join(" ")},r.timestamp,r.level==="log"||r.level==="debug"?"log":r.level)}function Od(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
|
|
96
|
-
`).slice(0,4).join(`
|
|
97
|
-
`):"")||`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}return String(e)}function Rd(e){const t=e.detail?.open===!0;t!==Ke&&(Ke=t,Be+=1,Zn(),t&&(Y.mobileLanSelect.addEventListener("change",BE),Ld(),Ar()))}function BE(){Ke&&Ar()}function Pd(){fr("manual restart")}function fr(e){Q||It!==void 0||(Ae("runtime.restart",{boundary:Le+1}),It=window.setTimeout(()=>{It=void 0,Q||wr(e)},0))}async function wr(e){if(Gt)return;const t=++Le;if(lr=void 0,hr(e),Nd(),j.runtimeStatus="loading",Vd(Pt),Y.device.replaceChildren(),dt){Y.device.innerHTML=`
|
|
98
|
-
<div class="browser-mock-preview">
|
|
99
|
-
<span class="browser-mock-preview__icon">UI</span>
|
|
100
|
-
<strong>Browser Mock</strong>
|
|
101
|
-
<small>mp_preview</small>
|
|
102
|
-
</div>`,j.runtimeStatus="idle";return}const r=document.createElement("iframe");r.dataset.testid="device-iframe",r.title="小程序预览",r.allow="clipboard-read; clipboard-write",r.name=uE,Y.device.appendChild(r);const n=new AbortController;io=n;let i=!1;try{const o=await my(qE(n.signal,t));if(Q||t!==Le){o.dispose();return}oo=o.dispose,o.ports.companion=fo.port;const s=Jg({iframe:r,ports:o.ports,environment:o.environment,hostCapabilities:{...o.hostCapabilities,...iE},authPresentation:o.authPresentation,companionPresentation:fo.presentation,resolveLaunchConfiguration:async()=>(await o.resolveLaunch()).configuration,dispose:o.dispose,onReady:()=>{j.runtimeStatus="ready",Ae("runtime.ready",{generation:t})},onTrace:a=>jE(t,a),onError:()=>{i=!0,j.runtimeStatus="error"},onCapabilityTrace:a=>{jt||Ae(a.method,a),a.method==="storage.setStorage"&&a.outcome==="success"&&Xn()}});We=s,await s.start()}catch(o){if(Q||t!==Le||n.signal.aborted)return;j.runtimeStatus="error",i||Ae("runtime.start.failed",Qd(o))}}function VE(){Ae("runtime.ready",{generation:1}),mr("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info"),Ae("user.getInfo",{durationMs:34,outcome:"success"}),Ae("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function qE(e,t){const r=ge,n=Vy(r.runtimePermissions,Pt,r);return{signal:e,account:{async getCurrentUserId(){return(await po(!1,e)).user_id},async ensureAuthenticated({signal:i}){await po(!1,i)},onChange(i){return Dn.add(i),()=>Dn.delete(i)}},authenticatedRequest:$E,storage:{area:"local",storage:localStorage},presentation:rE({close:async()=>{Ja(),We?.destroy(),Jt.reset(),Nd(),j.runtimeStatus="closed"},reload:()=>{!Q&&t===Le&&(lr=t)},onNavigationBarStyleChange:Qa,pushLog:Ae,getDeviceMetrics:()=>ol.value,applyDisplay:(i,o)=>Jt.applyDisplay(i,o),isCapsuleHidden:()=>j.display.capsuleHidden,onViewportChange:i=>Jt.onViewportChange(i)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:i=>{document.title=i}},resolveLaunch:async()=>({configuration:Yy({launchUrl:_d,runtimePermissions:n,...r.miniProgramId?{miniProgramId:r.miniProgramId}:{},operatingSystem:Jd.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:i=>Ky(i)},protocol:zE()}}function zE(){return{async invoke(e){Ae("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:GE(e)})}}}function GE(e){if(typeof e!="string")return typeof e.protocol_type=="string"?e.protocol_type:void 0;const t=/^heybox:\/\/(.+)$/i.exec(e.trim());if(t)try{const r=JSON.parse(decodeURIComponent(t[1]));return ue(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function Nd(){document.documentElement.dataset.navigationBarStyle=$a,Qa($a)}function jE(e,t){const r=Xd(t,e);r&&Ya(r),!(t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||lr!==e||e!==Le)&&(lr=void 0,fr("navigation.reload"))}async function $E(e,t){if(e.redirectPolicy!=="error")throw new Error("Browser Dev Host network 只允许 no-follow redirect policy");const n=e.target.kind==="absolute-url"&&e.source==="public-sdk"&&e.target.kind==="absolute-url"?{url:e.target.url,method:e.method,params:e.params,data:e.data,bodyEncoding:e.bodyEncoding,headers:e.headers,timeout:e.timeout}:void 0;if(!n&&e.source!=="runtime-private")throw new Error("Browser Dev Host 的公开请求只支持 absolute URL");const i=await Fo(n?DE:CE,{method:"POST",body:JSON.stringify(n??{target:e.target,method:e.method,params:e.params,data:e.data,headers:e.headers,credentials:e.source==="runtime-private"?e.credentials:void 0,bodyEncoding:e.bodyEncoding,timeout:e.timeout}),signal:t.signal});!n&&i.status===401&&Nt.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function po(e,t){const r=Yn,n=await Dd(Hd(Qn.signal,t));return Fd(r)?Td(n,e).status:go()}async function Dd(e){return await(await fetch(TE,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Td(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Xt)return{changed:!1,status:go()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?oe(e.nickname):void 0,i=e.authenticated?oe(e.avatar):void 0,o=e.revision!==Xt||e.authenticated!==ur||r!==it||n!==lo||i!==uo;return Xt=e.revision,ur=e.authenticated,it=r,lo=n,uo=i,kd(),t&&o&&Dn.forEach(s=>s(it)),{changed:o,status:go()}}function go(){return{authenticated:ur,revision:Xt,...ur&&it?{user_id:it}:{}}}function WE(){if(!(!ie.csrfToken||Q))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",et=vE({csrfToken:ie.csrfToken,onDiagnostic:t=>Ae("channel.diagnostic",t),url:e.toString()}),et.subscribeUpdates((t,r)=>KE(t,r)),et.connect()}catch{et?.dispose(),et=void 0}}function KE(e,t){Nt.invalidate(e.account.revision),mw(Pt,e.permissions)?t.type==="event"&&t.event==="status.changed"&&wr("status changed"):(Pt=Vd(e.permissions),QE())}function Cd(){if(Gr?.close(),Gr=void 0,!it||Q)return;const e=new EventSource(LE);Gr=e,e.addEventListener("account-invalidated",()=>{Nt.invalidate()}),e.addEventListener("account-revision",()=>{Nt.invalidate()}),e.onopen=()=>{ho.reset()},e.onerror=()=>{e.close(),ho.schedule()}}async function YE(e){Fd(e)&&await wr("account revision changed")}function hr(e){qr+=1,Ja(),We&&fo.reset(),We?.destroy(),We=void 0,io?.abort(new DOMException(e,"AbortError")),io=void 0,oo?.(),oo=void 0,Jt.reset()}async function QE(){Q||(await wr("permission changed"),!Q&&await Ar())}async function Ho(){const e=await fetch(PE,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error("Browser Dev Host bootstrap request failed");const t=await e.json();if(!ue(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Bd(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new Dt;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:JE(t.devReadiness),csrfToken:typeof t.csrfToken=="string"?t.csrfToken:void 0,defaultLanAddressId:typeof t.defaultLanAddressId=="string"?t.defaultLanAddressId:void 0,devSessionId:typeof t.devSessionId=="string"&&/^[a-f0-9]{32}$/.test(t.devSessionId)?t.devSessionId:void 0,devContext:XE(t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(hw):[],loginAvailable:t.loginAvailable===!0,miniProgram:cw(t.miniProgram),miniProgramSupportsDesktop:t.miniProgramSupportsDesktop===!0,workspaceCardsEnabled:t.workspaceCardsEnabled===!0,mobileLaunchRedirect:r,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof t.miniProgramManifestAccessToken=="string"?t.miniProgramManifestAccessToken:void 0}}function JE(e){if(!ue(e))return;const t=s=>{if(!(!ue(s)||!["ready","pending","blocked","not-configured"].includes(String(s.state))))return{state:s.state,...typeof s.reason=="string"?{reason:s.reason.slice(0,240)}:{}}},r=t(e.browser),n=t(e.mobile),i=t(e.companion);if(!r||!n||!i||!ue(e.companion))return;const o=e.companion;return{browser:r,mobile:n,companion:{...i,...typeof o.digest=="string"&&/^[a-f0-9]{64}$/.test(o.digest)?{digest:o.digest}:{},artifacts:Array.isArray(o.artifacts)?o.artifacts.filter(s=>ue(s)&&typeof s.alias=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(s.alias)&&["windows-x64","macos-arm64"].includes(String(s.target))).map(({alias:s,target:a})=>({alias:s,target:a})):[]}}}function XE(e,t){return ue(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId:void 0,localDevLaunchToken:typeof e.localDevLaunchToken=="string"?e.localDevLaunchToken:void 0,runtimePermissions:e.runtimePermissions,warning:typeof e.warning=="string"?e.warning:void 0,declaredPermissions:ue(e.declaredPermissions)?e.declaredPermissions:void 0,platforms:Array.isArray(e.platforms)?e.platforms.filter(r=>["android","ios","ohos","windows","macos","linux"].includes(String(r))):void 0,localDevGrant:e.localDevGrant,contextRevision:typeof e.contextRevision=="number"?e.contextRevision:void 0,devSessionId:typeof e.devSessionId=="string"?e.devSessionId:void 0,expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0,companionManifestSha256:typeof e.companionManifestSha256=="string"?e.companionManifestSha256:void 0}:{source:"anonymous",runtimePermissions:t}}async function Fo(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),ie.csrfToken&&r.set("x-hb-sdk-csrf",ie.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function ZE(){Vo(),dt||(so=window.setInterval(()=>{aw()},kE))}function Ld(e=Y.mobileLanSelect.options.length>0?Y.mobileLanSelect.value:void 0){Y.mobileLanSelect.replaceChildren();for(const t of Fe){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,Y.mobileLanSelect.appendChild(r)}e&&Fe.some(({id:t})=>t===e)?Y.mobileLanSelect.value=e:Fr&&Fe.some(({id:t})=>t===Fr)?Y.mobileLanSelect.value=Fr:Fe[0]&&(Y.mobileLanSelect.value=Fe[0].id),Y.mobileLanSelect.disabled=Fe.length===0}async function Ar(){if(Q)return;const e=++Be;if(Zn(),fe.source!=="remote"||!fe.localDevLaunchToken||fe.expiresAt!==void 0&&fe.expiresAt<=Date.now()){Y.mobileQrImage.removeAttribute("src"),Y.mobileQrStatus.textContent=Uo||"需要有效的本地调试启动票";return}const t=fw();if(!t?.mobileAppQrPayload){Y.mobileQrImage.removeAttribute("src"),Y.mobileQrStatus.textContent="未发现可用的局域网地址";return}Y.mobileQrStatus.textContent="正在生成二维码...";try{const r=await iw(t);if(e!==Be||Q)return;const n=await ew(r.address,r.expiresAt);if(e!==Be||Q)return;const i=await xy.toDataURL(n.payload,{width:ME,margin:1});if(e!==Be||Q)return;Y.mobileQrImage.src=i,Y.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,sw(n.expiresAt,e)}catch(r){if(e!==Be||Q)return;if(r instanceof Dt){jr();return}Y.mobileQrImage.removeAttribute("src"),Y.mobileQrStatus.textContent=qo(r)}}async function ew(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await tw(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:dE(cE({host:e.address,port:location.port,token:n.token}))}}catch{throw new Dt}}async function tw(e,t){if(wt?.addressId===e.id)return wt;if(!wt)return;const r=await Fo(NE,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:wt.token})});if(!r.ok)throw new Dt;const n=await r.json(),i=ue(n)?Bd({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new Dt;return wt=i,Vr={...Vr,mobileLaunchRedirect:i},xo=Jn(Vr),i}async function rw(e){const t=await Ho(),r=nw(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return Md(t),{...r,mobileAppQrPayload:n}}function nw(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function Md(e){const t=rt(ge);j.devReadiness=e.devReadiness,j.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,zt=e.workspaceCardsEnabled,Vr=e,xo=Jn(e),fe=e.devContext,ge=Nn(fe),Pt=Wn(ge),Bo(),Fe=e.lanAddresses,Fr=e.defaultLanAddressId,wt=e.mobileLaunchRedirect,Uo=e.nativeAppLaunchUnavailableReason,Br=e.devSessionId,no=e.miniProgramManifestAccessToken,xd(Ud(e)),Ke&&Ld(),Vo(),t!==rt(ge)&&(Le+=1,hr("local permission context changed"),fr("local permission context changed"))}function Bo(){j.localPermissions=lE(ge),j.devContextWarning=ge.source==="anonymous"?"未连接线上上下文":ge.warning?"本地上下文受限,请检查 CLI 状态":""}function Vo(){let e;try{e=Zd(_d)}catch{}const t=fe.miniProgramId?.trim().toLowerCase();let r=Uo?.trim()??"";!r&&(fe.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!fe.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&zt&&!Br&&(r="本地调试会话尚未就绪"),!r&&fe.expiresAt!==void 0&&fe.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),Xa({...e?{address:e}:{},...t?{miniProgramId:t}:{},...zt&&Br?{devSessionId:Br}:{},...zt&&no?{miniProgramManifestToken:no}:{},workspaceCardsEnabled:zt,ready:r==="",...r?{unavailableReason:r}:{}})}class Dt extends Error{}async function iw(e){const t=Ka.then(()=>ow(e));return Ka=t.then(()=>{},()=>{}),t}async function ow(e){const t=new URL(e.appUrl),r=new URL(Hy,location.origin),n=await Fo(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:qy(fe)})}),i=await n.json();if(!n.ok||!ue(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await rw(e.id),expiresAt:i.expires_at}}function sw(e,t){zr=window.setTimeout(()=>{!Q&&Ke&&t===Be&&Ar()},Math.max(1e3,e-Date.now()-3e4))}async function aw(){if(!(Fi||Q)){Fi=!0;try{const e=await Ho();Wa=Date.now();const t=Gt;Gt=!1;const r=Jn(e);if(!t&&r===xo&&rt(Nn(e.devContext))===rt(ge))return;Md(e),t&&fr("CLI dev session reconnected"),Ke&&Ar()}catch(e){e instanceof Dt&&jr();const t=Nn(fe);rt(t)!==rt(ge)&&(ge=t,Pt=Wn(ge),Bo(),Le+=1,hr("local permission context expired"),fr("local permission context expired"),Vo(),Ke&&jr()),Date.now()-Wa>=3e4&&!Gt&&(Gt=!0,Le+=1,hr("CLI dev session disconnected"),Y.device.replaceChildren(),j.runtimeStatus="closed",j.localPermissions=[],j.devContextWarning="调试会话已断开",Xa({ready:!1,unavailableReason:"调试会话已断开"}),j.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},Ke&&jr())}finally{Fi=!1}}}function jr(){Be+=1,Zn(),Y.mobileQrImage.removeAttribute("src"),Y.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Jn(e){return JSON.stringify({devReadiness:e.devReadiness,devSessionId:e.devSessionId,defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,devContext:{permissionContext:rt(e.devContext),expiresAt:e.devContext.expiresAt,localDevLaunchToken:e.devContext.localDevLaunchToken,miniProgramId:e.devContext.miniProgramId,source:e.devContext.source},nativeAppLaunchUnavailableReason:e.nativeAppLaunchUnavailableReason,miniProgramManifestAccessToken:e.miniProgramManifestAccessToken,miniProgramSupportsDesktop:e.miniProgramSupportsDesktop,workspaceCardsEnabled:e.workspaceCardsEnabled})}function kd(){if(!ur){j.account={authenticated:!1,avatar:"",nickname:"未登录"};return}j.account={authenticated:!0,avatar:uo??"",nickname:lo||it||"已登录"}}function Ud(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function xd(e){if(!!!e?.miniProgramId||!e){j.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}j.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function cw(e){if(e===null)return null;if(!ue(e))return;const t=oe(e.miniProgramId)??oe(e.mini_program_id);if(t)return{miniProgramId:t,...oe(e.name)?{name:oe(e.name)}:{},...oe(e.iconUrl)??oe(e.icon_url)?{iconUrl:oe(e.iconUrl)??oe(e.icon_url)}:{},...oe(e.status)?{status:oe(e.status)}:{},...oe(e.version)?{version:oe(e.version)}:{},...oe(e.developerName)??oe(e.developer_name)?{developerName:oe(e.developerName)??oe(e.developer_name)}:{}}}function oe(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function Xn(){const e=++qr,t=We,r=t?.diagnostics.storage;if(!r){j.storage=[],j.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(Q||e!==qr||t!==We)return;j.storage=n.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),j.storageError=""}catch(n){if(Q||e!==qr||t!==We)return;j.storage=[],j.storageError=qo(n)}}function dw(e,t){Ae("host.message",{message:e,status:t})}function lw(e){Q||dw(qo(e),"error")}function Ae(e,t){mr(e,t)}function uw(){mo!==void 0&&window.clearTimeout(mo),!Q&&(Q=!0,window.removeEventListener("hb-sdk:restart-runtime",Pd),window.removeEventListener("hb-sdk:refresh-storage",Xn),window.removeEventListener("hb-sdk:qr-open-change",Rd),Yn+=1,Qn.abort(new DOMException("Browser Dev Host disposed","AbortError")),Nt.dispose(),Le+=1,hr("Browser Dev Host disposed"),Gr?.close(),et?.dispose(),et=void 0,ho.dispose(),lr=void 0,It!==void 0&&window.clearTimeout(It),It=void 0,Zn(),so!==void 0&&window.clearInterval(so),Dn.clear(),ao?.(),ao=void 0,co?.(),co=void 0)}function Zn(){zr!==void 0&&window.clearTimeout(zr),zr=void 0}function Hd(e,t){return t?AbortSignal.any([e,t]):e}function Fd(e){return!Q&&e===Yn}function fw(){return Fe.find(({id:e})=>e===Y.mobileLanSelect.value)}function hw(e){return ue(e)&&typeof e.address=="string"&&typeof e.appUrl=="string"&&typeof e.id=="string"&&typeof e.name=="string"&&(e.mobileAppQrPayload===void 0||typeof e.mobileAppQrPayload=="string")}function Bd(e){if(!(!ue(e)||typeof e.addressId!="string"||!e.addressId||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||typeof e.token!="string"||!/^[A-Za-z0-9_-]{22}$/.test(e.token)))return{addressId:e.addressId,expiresAt:e.expiresAt,token:e.token}}function Vd(e){return{networkRequest:{...e.networkRequest}}}function mw(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function qo(e){return e instanceof Error&&e.message?e.message:"操作失败"}function ue(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ft(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}
|