@heybox/hb-sdk 0.9.1-alpha.11 → 0.9.1-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +1 -1
  3. package/dist/cli-chunks/{build-CSTdWNu1.cjs → build-CDvX6mZ_.cjs} +5 -5
  4. package/dist/cli-chunks/{context-Bej2XR0w.cjs → context-ycfj98q4.cjs} +2 -2
  5. package/dist/cli-chunks/{create-Cz5tqvMR.cjs → create-TQBnsU6A.cjs} +1 -1
  6. package/dist/cli-chunks/{dev-6nGC0_bZ.cjs → dev-DIlr0XsT.cjs} +8 -8
  7. package/dist/cli-chunks/{doctor-BSSJ7n8i.cjs → doctor-CNvx5BMQ.cjs} +1 -1
  8. package/dist/cli-chunks/{index-CQtu_5c7.cjs → index-B7zxtWTI.cjs} +16 -16
  9. package/dist/cli-chunks/{index-gqsUj-Am.cjs → index-CPAecgVy.cjs} +1 -1
  10. package/dist/cli-chunks/{index.esm-BuwSVK1U.cjs → index.esm-CshHset7.cjs} +6 -6
  11. package/dist/cli-chunks/{login-BB07gOy9.cjs → login-D9IsRXmh.cjs} +1 -1
  12. package/dist/cli-chunks/{project-vite-DqbyiCMm.cjs → project-vite-B4bIN6iT.cjs} +1 -1
  13. package/dist/cli-chunks/{remote-BvvAbGIG.cjs → remote-DeUMkvWX.cjs} +6 -6
  14. package/dist/cli-chunks/{runtime-gate-Bh1vm1an.cjs → runtime-gate-C8LOiCNj.cjs} +2 -2
  15. package/dist/cli-chunks/{runtime-permission-env-DuRchECp.cjs → runtime-permission-env-DJh53zIV.cjs} +2 -2
  16. package/dist/cli-chunks/{skill-D1pYV7g_.cjs → skill-5dzzu2QT.cjs} +2 -2
  17. package/dist/cli-chunks/{version-BaMa3UQg.cjs → version-DJMVnGTf.cjs} +1 -1
  18. package/dist/cli.cjs +1 -1
  19. package/dist/devtools/browser-dev-host/assets/{browser-dev-host-wMCyX_zc.js → browser-dev-host-WX0SWy37.js} +12 -12
  20. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-D1z3MxUY.js → desktop-app-launch-F0wNWGvm.js} +1 -1
  21. package/dist/devtools/browser-dev-host/assets/{index-CuH8wWTJ.js → index-BdfQ_aP4.js} +3 -3
  22. package/dist/devtools/browser-dev-host/index.html +2 -2
  23. package/dist/index.cjs.js +7 -1
  24. package/dist/index.esm.js +7 -1
  25. package/dist/vite.cjs.js +1 -1
  26. package/dist/vite.esm.js +1 -1
  27. package/package.json +4 -4
  28. package/skill/SKILL.md +10 -0
  29. package/skill/skill.json +5 -5
  30. package/types/index.d.ts +6 -1
@@ -1,15 +1,15 @@
1
- import{H as Yo,ax as Bd,aY as Qd,M as Yd,aH as Gd,aI as qd,aj as mr,b6 as Y,aa as Wd,ak as Ka,aq as $d,b0 as Kd,am as Jd,d as Zd,aE as Ja,a8 as Xd,at as Za,r as eu,az as Xa,o as tu,aD as ru,a5 as nu,a_ as iu,aZ as ou,c as su}from"./desktop-app-launch-D1z3MxUY.js";const Gr="workspaceCards.requestRefresh",qr="auth.login",Wr="user.getInfo",$r="user.revokeAuthorization",Kr="user.getSteamGameList",Jr="share.copyLink",Zr="share.showShareMenu",Xr="share.screenshot",ot="viewport.setDisplay",en="viewport.getWindowInfo",tn="viewport.setNavigationBarStyle",Xt="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",un="file.writeText",ir="file.readBytes",ln="file.writeBytes",or="file.stat",fn="directory.create",sr="directory.remove",hn="directory.exists",mn="directory.list",gn="ui.showToast",pn="ui.showLoading",yn="ui.hideLoading",En="device.vibrate",In="device.setClipboard",wn="device.executeProtocol",Mn="navigation.close",Nn="navigation.reload",An="navigation.openAppPage",ke="cloud.leaderboard.submit",Ne="cloud.leaderboard.getList",Qe="cloud.leaderboard.getCurrentUserEntry",st="cloud.leaderboard.deleteCurrentUserEntry",Le="cloud.leaderboard.getInfo",vn="companion.getInfo",Cn="companion.getPreparationStatus",Rn="companion.prepare",Pn="companion.cancelPreparation",kn="companion.getActiveSession",xn="companion.launch",jn="companion.session.write",zn="companion.session.closeStdin",Un="companion.session.terminate",Hn="companion.session.ackOutput",Fn="companion.openAttachment",Vn="companion.showNotification",Ye=[{method:Gr,module:"workspaceCards",capability:Gr,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:qr,module:"auth",capability:qr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Wr,module:"user",capability:Wr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:$r,module:"user",capability:$r,requirement:{kind:"none"},risk:"high"},{method:Kr,module:"user",capability:Kr,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:Jr,module:"share",capability:Jr,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Zr,module:"share",capability:Zr,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Xr,module:"share",capability:Xr,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:Xt,module:"storage",capability:Xt,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:un,module:"file",capability:un,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ir,module:"file",capability:ir,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ln,module:"file",capability:ln,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:gn,module:"ui",capability:gn,requirement:{kind:"none"},risk:"low"},{method:pn,module:"ui",capability:pn,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:In,module:"device",capability:In,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:wn,module:"device",capability:wn,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:Mn,module:"navigation",capability:Mn,requirement:{kind:"none"},risk:"medium"},{method:Nn,module:"navigation",capability:Nn,requirement:{kind:"none"},risk:"medium"},{method:An,module:"navigation",capability:An,requirement:{kind:"none"},risk:"medium"},{method:ke,module:"cloud",capability:ke,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ne,module:"cloud",capability:Ne,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Qe,module:"cloud",capability:Qe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:st,module:"cloud",capability:st,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Le,module:"cloud",capability:Le,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},...[vn,Cn,Rn,Pn,kn,xn,jn,zn,Un,Hn,Fn,Vn].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],Ze="heybox:miniprogram",ec=2,au="hb_mini_bridge_nonce",tc="sdk.handshake",Mr="runtime.location.probe",cu="sdk.location.report",du="sdk.csp.violation",rc="operation.progress",uu="companion.session.output",lu="companion.session.exit",fu="companion.session.ownershipLost";function hu(e){return!Ke(e)||e.namespace!==Ze||e.version!==1&&e.version!==2||!de(e.nonce)?!1:e.type==="handshake"?de(e.id)&&e.method===tc&&e.error===void 0&&yu(e.payload):e.type==="request"?de(e.id)&&de(e.method)&&e.error===void 0:e.type==="response"?de(e.id)&&(e.method===void 0||de(e.method))&&(e.error===void 0||Eu(e.error)):e.type==="event"?!de(e.method)||e.error!==void 0?!1:e.method===rc?e.version===2&&de(e.id)&&pu(e.payload):e.id===void 0||de(e.id):e.type==="cancel"?e.version===2&&de(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 nc(e){return Ke(e)?e.kind==="sandbox"?je(e,["kind"]):e.kind==="directory"&&de(e.handleId)&&je(e,["kind","handleId"]):!1}function Bn(e){return!Ke(e)||e.kind!=="file"?!1:de(e.handleId)?je(e,["kind","handleId"]):nc(e.root)&&yo(e.relativePath)&&je(e,["kind","root","relativePath"])}function ic(e){return!Ke(e)||e.kind!=="directory"?!1:de(e.handleId)?je(e,["kind","handleId"]):nc(e.root)&&(e.relativePath==="."||yo(e.relativePath))&&je(e,["kind","root","relativePath"])}function oc(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function mu(e){return!Ke(e)||!Mt(e.loaded)||typeof e.lengthComputable!="boolean"||!je(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Mt(e.total)&&e.loaded<=e.total:e.total===void 0}function gu(e){return Ke(e)?e.phase==="downloading"?Mt(e.loaded)&&(e.total===void 0||Mt(e.total)&&e.loaded<=e.total)&&je(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Mt(e.processed)&&Mt(e.total)&&e.processed<=e.total&&je(e,["phase","processed","total"]):!1}function pu(e){return mu(e)||gu(e)}function yu(e){return Ke(e)&&de(e.href)&&typeof e.userAgent=="string"&&de(e.sdkVersion)}function Eu(e){return Ke(e)&&de(e.code)&&typeof e.message=="string"}function Mt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function de(e){return typeof e=="string"&&e.length>0}function je(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Ke(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 Iu=new Set(ar);function wu(e){return Iu.has(e)}function Je(e){if(!Nr(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(!Nr(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),!!wu(o)){if(o==="network"){const s=n.config;if(!Nr(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&&(!Nr(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 Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Rr=["network","companion","appProtocol"];function sc(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>Rr.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)=>Rr.indexOf(n.key)-Rr.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Mu(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 Rr)!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=sc(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=ac(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 ac(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ct(e,t){return ac(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Dt=["identity","profile","steam_account"],Nu=/^[a-z][a-z0-9-]{0,31}$/,cc=["COMPANION_UNSUPPORTED","COMPANION_PREVIEW_UNSUPPORTED","COMPANION_NOT_DECLARED","COMPANION_TARGET_UNSUPPORTED","COMPANION_NOT_PREPARED","COMPANION_PREPARATION_CANCELLED","COMPANION_DOWNLOAD_FAILED","COMPANION_DESCRIPTOR_UNAVAILABLE","COMPANION_ARCHIVE_INVALID","COMPANION_INTEGRITY_FAILED","COMPANION_ENTRYPOINT_INVALID","COMPANION_USER_CANCELLED","COMPANION_ELEVATION_DENIED","COMPANION_OS_BLOCKED","COMPANION_LAUNCH_FAILED","COMPANION_SESSION_VERSION_MISMATCH","COMPANION_SESSION_OWNERSHIP_LOST","COMPANION_SESSION_EXITED","COMPANION_PIPE_CLOSED","COMPANION_OUTPUT_LIMIT","COMPANION_PROCESS_CRASHED","COMPANION_ATTACHMENT_NOT_FOUND","COMPANION_NOTIFICATION_UNAVAILABLE","COMPANION_TERMINATE_FAILED"];Ye.map(e=>e.method);function $(e,t,r){return{code:e,message:t,data:r}}function Io(e){return Au(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?$("RUNTIME_ERROR",e.message):$("UNKNOWN_ERROR","小程序运行时异常",e)}function Au(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function Du(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Tu=1e3;function Su(e,t=Du()){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<=Tu}const bu="runtime.gate.probe",dc=new Set(Ye.map(e=>e.method));class Ou{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=ec;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:Ze,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:Ze,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Ze,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Ze,version:2,nonce:this.nonce,type:"event",id:t,method:rc,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=Su(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&&hu(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:Ze,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:tc,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===bu){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,$("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!dc.has(t.method)){this.postResponse(t,void 0,$("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,$("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=Io(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:Ze,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!_u(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 _u(e){return typeof e=="string"&&dc.has(e)}const uc="METHOD_FORBIDDEN";function Ae(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=uc,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 Lu=/^[A-Za-z0-9_-]{1,64}$/,Go=1e3;function vu(e){return Lu.test(e)?e:ku(e)}function Cu(e,t){return`hb_miniprogram_${e}_${t}`}function Ru(e){return`hb_miniprogram_keys_${e}`}function Pu(e){if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}function ku(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}const qo={[Gr]:["workspaceCards.requestRefresh"],[qr]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Wr]:["account.getCurrentUserId","account.onChange","network.request"],[$r]:["account.getCurrentUserId","account.onChange","network.request"],[Kr]:["account.getCurrentUserId","account.onChange","network.request"],[Jr]:["presentation.setClipboard"],[Zr]:["presentation.showShareMenu"],[Xr]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ot]:["presentation.applyOrientation"],[en]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[tn]:["presentation.setNavigationBarStyle"],[Xt]:["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"],[un]:["files.access"],[ir]:["files.access"],[ln]:["files.access"],[or]:["files.access"],[fn]:["files.access"],[sr]:["files.removeDirectory"],[hn]:["files.access"],[mn]:["files.access"],[gn]:["presentation.showToast"],[pn]:["presentation.showLoading"],[yn]:["presentation.hideLoading"],[En]:["presentation.vibrate"],[In]:["presentation.setClipboard"],[wn]:["protocol.invoke"],[Mn]:["presentation.close"],[Nn]:["presentation.reload"],[An]:["presentation.openAppPage"],[ke]:["account.getCurrentUserId","account.onChange","network.request"],[Ne]:["account.onChange","network.request"],[Qe]:["account.getCurrentUserId","account.onChange","network.request"],[st]:["account.getCurrentUserId","account.onChange","network.request"],[Le]:["account.onChange","network.request"],[vn]:["companion.getInfo"],[Cn]:["companion.getPreparationStatus"],[Rn]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[Pn]:["companion.cancelPreparation"],[kn]:["companion.getActiveSession"],[xn]:["companion.getInfo","companion.launch"],[jn]:["companion.session.write"],[zn]:["companion.session.closeStdin"],[Un]:["companion.session.terminate"],[Hn]:["companion.session.ackOutput"],[Fn]:["companion.openAttachment"],[Vn]:["companion.showNotification"]};function xu(e,t){if(t[e]!==!0)throw Ae(e)}const ju=32*1024*1024,zu=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Uu(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:ju},i);return Hu(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Hu(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:Fu(t,Bu(e,"content-type"))}}function Fu(e,t){Vu(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||!zu.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function Vu(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 Bu(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 Ae(e)}}function re(e){return async(...t)=>{throw Ae(e)}}const Qu=(e,t)=>{},Yu=()=>()=>{};function Gu(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):Yu},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):Qu,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 qu(e){const t=Wu(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 Wu(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 $o(e,t){return t?.[e]!==!1}function $u(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(qo)){const o=qo[n].every(a=>e[a]),s=!$u(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=$o(n,t.callerCapabilities)&&$o(n,t.hostCapabilities)&&o&&s}return r}function fc(e={},t={}){const r=qu(e),n=lc(r,t);return{ports:Gu(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function at(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):Ku(e.signal,t);return{...e,signal:r}}function Ku(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 Ju(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 Zu=4,Xu=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],el=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade"]),tl=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],rl=["/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 nl(e,t){const r=sl(e);return r===null||Ko(r,tl)?!0:t&&Ko(r,rl)}function il(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Xu.some(r=>t===r||t.endsWith(`.${r}`))}function ol(e){const t=e.trim().toLowerCase();return el.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function sl(e){let t=e;for(let r=0;r<Zu;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Jo(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Jo(t)}function Ko(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Jo(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 Zo(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function hc(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,o=new Map,s=new Set,a=new Set;let c=!1;function d(M,S){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:M,type:S})).catch(()=>{})}catch{}}function f(M){const S=r.get(M);if(!S)throw new Error("Unknown runtime cache scope");return S}function h(M,S){return M.flatMap((w,_)=>{const A=JSON.stringify(M.slice(0,_+1));return[JSON.stringify([A]),JSON.stringify([A,S])]})}function u(M,S){return JSON.stringify(h(M,S).map(w=>n.get(w)??0))}async function g(M,S){const w=f(M),_=JSON.stringify([JSON.stringify(w),...S?[S]:[]]),A=(n.get(_)??0)+1;n.set(_,A),i.add(_);for(const v of a)v(w,S);if(!e.store){i.delete(_),d(S??"*","invalidation");return}try{await e.store.invalidate(w,S)}catch(v){throw d(S??"*","storage_error"),v}n.get(_)===A&&i.delete(_),d(S??"*","invalidation")}function T(M){if(c)throw new Error("Runtime cache manager disposed");const S=o.get(M.namespace);if(S){if(S.sourceCodec!==M.codec||S.definition.codec.version!==M.codec.version||JSON.stringify(S.definition.policy)!==JSON.stringify(M.policy))throw new Error("Conflicting runtime cache namespace");return S.cache}if(!M.namespace||!M.codec.version)throw new Error("Invalid runtime cache definition");const w=Object.freeze({...M.policy}),_=Object.freeze({version:M.codec.version,encode:M.codec.encode.bind(M.codec),decode:M.codec.decode.bind(M.codec),validate:M.codec.validate.bind(M.codec),clone:M.codec.clone.bind(M.codec)}),A=M.namespace;for(const O of[w.ttlMs,w.memoryMaxEntries,w.diskMaxEntries,w.diskMaxBytes,w.maxEntryBytes])if(!Number.isFinite(O)||O<0)throw new Error("Invalid runtime cache policy");const v=new Map,U=new Map,L=new Map;let N=!1;function l(O,P,b){if(c||N||O.aborted||u(P,A)!==b)throw lt()}function p(O){return w.ttlMs>0&&w.persistence==="memory-and-disk"&&!!e.store&&!h(O,A).some(P=>i.has(P))}function m(O,P,b){const x=t();return O.envelopeVersion===1&&JSON.stringify(O.address)===JSON.stringify(P)&&Zo(O.revisions,b)&&O.payload.byteLength<=w.maxEntryBytes&&Number.isFinite(O.cachedAt)&&Number.isFinite(O.expiresAt)&&O.cachedAt<=x&&O.cachedAt>=0&&O.expiresAt>O.cachedAt&&Math.min(O.expiresAt,O.cachedAt+w.ttlMs)>x}function E(O,P,b,x,j){if(!(w.ttlMs<=0||w.memoryMaxEntries<1)){for(const[z,B]of v)Math.min(B.entry.expiresAt,B.entry.cachedAt+w.ttlMs)<=t()&&v.delete(z);for(v.delete(O);v.size>=Math.floor(w.memoryMaxEntries);){const z=v.keys().next();if(z.done)break;v.delete(z.value)}v.set(O,{entry:P,value:b,epoch:x,persistent:j})}}async function I(O,P,b,x){const j={namespace:A,codecVersion:_.version,scopeIds:P,key:O.key},z=JSON.stringify(j);let B=[],Q=p(P);if(Q)try{B=await e.store.readRevisions(P,A)}catch{Q=!1,d(A,"storage_error")}l(x.signal,P,b);async function G(){if(!Q)return!0;try{return Zo(B,await e.store.readRevisions(P,A))}catch{return Q=!1,d(A,"storage_error"),!1}}const te=v.get(z);if(w.ttlMs>0&&te&&te.epoch===b&&m(te.entry,j,B)&&te.persistent===Q&&await G())return l(x.signal,P,b),d(A,"memory_hit"),te.value;if(v.delete(z),Q){let q,he;try{q=await e.store.read(j,w.maxEntryBytes),q&&m(q,j,B)?he=_.decode(q.payload):q=void 0}catch{q=void 0,d(A,"storage_error")}if(l(x.signal,P,b),q&&await G())return l(x.signal,P,b),E(z,q,he,b,!0),d(A,"disk_hit"),he}d(A,"miss");const X=_.validate(await O.load(x.signal));l(x.signal,P,b);const Z=_.clone(X);if(!await G()&&Q)throw lt();if(l(x.signal,P,b),w.ttlMs>0){const q=t();let he;try{he=_.encode(Z)}catch{return Z}const Bo={envelopeVersion:1,address:j,revisions:Q?B:[],cachedAt:q,expiresAt:q+w.ttlMs,payload:he};if(Q&&he.byteLength<=w.maxEntryBytes){let ei=!0,Qo=!1;try{ei=await e.store.publish(Bo,w),Qo=ei}catch{d(A,"storage_error")}if(l(x.signal,P,b),!ei)throw lt();Qo&&d(A,"published")}l(x.signal,P,b),E(z,Bo,Z,b,Q)}return Z}async function D(O){if(c||N||O.signal?.aborted)return Promise.reject(lt());const P=f(O.scope),b=u(P,A);let x;if(p(P)){const Q=new AbortController;L.set(Q,P);const G=()=>Q.abort();O.signal?.addEventListener("abort",G,{once:!0});let te=()=>{};try{x=await Promise.race([e.store.readRevisions(P,A),new Promise((X,Z)=>{const q=()=>Z(lt());Q.signal.addEventListener("abort",q,{once:!0}),te=()=>Q.signal.removeEventListener("abort",q)})])}catch{Q.signal.aborted||d(A,"storage_error")}finally{te(),L.delete(Q),O.signal?.removeEventListener("abort",G)}}l(O.signal??new AbortController().signal,P,b);const j=JSON.stringify([P,O.key,b,x]);let z=U.get(j);if(z?.controller.signal.aborted&&(z=void 0),!z){const Q=new AbortController;z={ids:P,controller:Q,waiters:0,promise:Promise.resolve(void 0)};const G=z;G.promise=I(O,P,b,Q).finally(()=>{U.get(j)===G&&U.delete(j)}),U.set(j,G)}const B=z;return B.waiters+=1,new Promise((Q,G)=>{let te=!1;function X(q){te||(te=!0,O.signal?.removeEventListener("abort",Z),B.controller.signal.removeEventListener("abort",Z),B.waiters-=1,B.waiters===0&&B.controller.abort(),q())}function Z(){X(()=>G(lt()))}O.signal?.addEventListener("abort",Z,{once:!0}),B.controller.signal.addEventListener("abort",Z,{once:!0}),B.promise.then(q=>X(()=>{try{l(O.signal??new AbortController().signal,P,b),Q(_.clone(q))}catch(he){G(he)}}),q=>X(()=>G(q)))})}function C(O,P){if(P&&P!==A)return;const b=x=>O.every((j,z)=>x[z]===j);for(const[x,j]of v)b(j.entry.address.scopeIds)&&v.delete(x);for(const[x,j]of U)b(j.ids)&&(j.controller.abort(),U.delete(x));for(const[x,j]of L)b(j)&&x.abort()}function F(){if(!N){N=!0,v.clear();for(const O of L.keys())O.abort();L.clear();for(const O of U.values())O.controller.abort();U.clear(),s.delete(F),a.delete(C),o.get(A)?.cache===R&&o.delete(A)}}const R={read:D,invalidateScope:O=>g(O,A),dispose:F};return s.add(F),a.add(C),o.set(A,{definition:{namespace:A,codec:_,policy:w},sourceCodec:M.codec,cache:R}),R}return{createScope(M,S){if(c||!M)throw new Error("Invalid runtime cache scope");const w=Object.freeze({});return r.set(w,[...S?f(S):[],M]),w},register:T,invalidateScope:M=>g(M),dispose(){if(!c){c=!0;for(const M of[...s])M();o.clear(),n.clear(),i.clear()}}}}function al(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 cl=".hb-runtime-cache-v1",ti=64*1024,ft=1e3,dl=2048,Rt=32*1024*1024,ul=1024,Pr=new TextEncoder,Xo=new TextDecoder("utf-8",{fatal:!0});function Pt(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Ar(e){const t=await globalThis.crypto.subtle.digest("SHA-256",Pr.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Te(e,t){return JSON.stringify(e)===JSON.stringify(t)}function es(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function ll(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function ts(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function fl(e,t){const r=e.sandbox.directory(cl),n=r.directory("revisions"),i=r.directory("entries");for(const l of[r,n,i,i.directory("capability-check")])ts(l,["directory","file","create","stat","list","remove"]),ts(l.file("capability-check"),["create","stat","read","write","remove"]);let o=Promise.resolve(),s=!1;function a(l){if(ll(l))throw s=!0,l}function c(){if(t.signal.aborted)throw Pt();if(s)throw Object.assign(new Error("Host 不支持完整文件能力,磁盘缓存已关闭"),{code:"METHOD_FORBIDDEN"})}function d(l,p=t.signal){const m=o.then(()=>{if(p.aborted)throw Pt();return c(),l()},()=>{if(p.aborted)throw Pt();return c(),l()}).catch(D=>{throw a(D),D});if(o=m.catch(()=>{}),p.aborted)return Promise.reject(Pt());let E=()=>{};const I=new Promise((D,C)=>{const F=()=>C(Pt());p.addEventListener("abort",F,{once:!0}),E=()=>p.removeEventListener("abort",F)});return Promise.race([m,I]).finally(E)}async function f(){c(),await n.create({recursive:!0,exclusive:!1},t),await i.create({recursive:!0,exclusive:!1},t),c()}async function h(l,p){const m=n.file(`${await Ar([l,p??null])}.revision`);await g(m);let E=!1;try{await m.create({recursive:!1,exclusive:!0},t),E=!0}catch(C){a(C),c()}if(E){const C=es();return await m.write(Pr.encode(C),t),c(),C}const I=await m.stat(t);if(I.size<1||I.size>128)throw new Error("缓存 revision 文件损坏");const D=Xo.decode(await m.read(t));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(D))throw new Error("缓存 revision 文件损坏");return c(),D}async function u(l){const p=await l.list({limit:ft},t);if(p.length>=ft)throw new Error("缓存目录超过治理上限");return p}async function g(l){try{await l.stat(t);return}catch(m){if(!Dr(m))throw m}if((await u(n)).length>=ft-1)throw new Error("缓存 metadata 超过治理上限")}async function T(l,p){await f();const m=[];for(let E=0;E<l.length;E+=1){const I=l.slice(0,E+1);m.push(await h(I),await h(I,p))}return m}async function M(l){return r.directory(`entries/${await Ar([l.namespace,l.codecVersion,l.scopeIds])}`)}async function S(l){return(await M(l)).file(`${await Ar(l.key)}.cache`)}async function w(l,p){const m=await l.stat(t);if(m.size<5||m.size>p+ti+4)throw new Error("缓存条目超过大小限制");const E=await l.read(t);if(c(),E.length!==m.size)throw new Error("缓存条目读取不完整");const I=new DataView(E.buffer,E.byteOffset,E.byteLength).getUint32(0);if(I<1||I>ti||I+4>E.length)throw new Error("缓存信封损坏");const D=JSON.parse(Xo.decode(E.subarray(4,I+4))),C=E.slice(I+4);if(D.envelopeVersion!==1||!D.address||!Array.isArray(D.address.scopeIds)||!D.address.scopeIds.every(F=>typeof F=="string")||typeof D.address.namespace!="string"||typeof D.address.codecVersion!="string"||typeof D.address.key!="string"||!Array.isArray(D.revisions)||D.revisions.length!==D.address.scopeIds.length*2||!D.revisions.every(F=>typeof F=="string"&&F.length>0)||!Number.isSafeInteger(D.cachedAt)||!Number.isSafeInteger(D.expiresAt)||D.cachedAt<0||D.expiresAt<=D.cachedAt||D.payloadBytes!==C.length||C.length>p)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:D.address,revisions:D.revisions,cachedAt:D.cachedAt,expiresAt:D.expiresAt,payload:C}}async function _(l){if(!l.remove)throw new Error("Host 不支持缓存文件删除");await l.remove(t)}async function A(l){try{if((await l.file.stat(t)).size!==l.size)return!1;const p=await w(l.file,Rt);return!Te(p.address,l.entry.address)||!Te(p.revisions,l.entry.revisions)||p.cachedAt!==l.entry.cachedAt||p.expiresAt!==l.entry.expiresAt||!Te(await v(p.payload),await v(l.entry.payload))?!1:(await _(l.file),!0)}catch(p){if(Dr(p))return!0;throw p}}async function v(l){const p=await globalThis.crypto.subtle.digest("SHA-256",l);return Array.from(new Uint8Array(p),m=>m.toString(16).padStart(2,"0")).join("")}async function U(){const l=await u(n);let p=0;for(const D of l)if(D.kind==="file"&&(p+=(await D.stat(t)).size,p>Rt))throw new Error("缓存扫描超过字节上限");const m=[];let E=0,I=p;for(const D of await u(i)){if(D.kind!=="directory")throw new Error("缓存目录结构损坏");for(const C of await u(D)){if(C.kind!=="file"||++E>dl)throw new Error("缓存文件超过治理上限");const F=(await C.stat(t)).size;if(I+=F,I>Rt)throw new Error("缓存扫描超过字节上限");try{const R=await w(C,Rt);m.push({file:C,entry:R,size:(await C.stat(t)).size,bucketName:D.name})}catch(R){a(R),c(),Dr(R)||await _(C)}}}return{entries:m,metadataBytes:p}}async function L(){for(const l of await u(i))if(l.kind==="directory"&&l.remove&&(await u(l)).length===0)try{await l.remove({recursive:!1},t)}catch(p){a(p),c()}}function N(l){const{payload:p,...m}=l,E=Pr.encode(JSON.stringify({...m,payloadBytes:p.length}));if(E.length>ti)throw new Error("缓存信封过大");const I=new Uint8Array(4+E.length+p.length);return new DataView(I.buffer).setUint32(0,E.length),I.set(E,4),I.set(p,E.length+4),I}return{readRevisions:(l,p)=>d(()=>T(l,p)),read:(l,p)=>d(async()=>{c();const m=await S(l);let E;try{E=await w(m,p)}catch(I){if(c(),Dr(I))return;throw I}if(!(!Te(E.address,l)||E.expiresAt<=Date.now())&&Te(E.revisions,await T(l.scopeIds,l.namespace)))return E}),publish:(l,p)=>d(async()=>{c();const{address:m}=l;if(!Te(l.revisions,await T(m.scopeIds,m.namespace)))return!1;const E=N(l);if(l.payload.length>p.maxEntryBytes||E.length>p.diskMaxBytes||p.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await f();const I=await M(m),D=await S(m),C=await U(),F=[],R=new Map;for(const b of C.entries){if(b.bucketName===I.name&&b.file.name===D.name)continue;const x=JSON.stringify([b.entry.address.scopeIds,b.entry.address.namespace]);let j=R.get(x);if(j||(j=await T(b.entry.address.scopeIds,b.entry.address.namespace),R.set(x,j)),b.entry.expiresAt<=Date.now()||!Te(b.entry.revisions,j)){if(!await A(b))throw new Error("缓存治理期间条目已变化")}else F.push(b)}F.sort((b,x)=>b.entry.cachedAt-x.entry.cachedAt);function O(){const b=F.filter(x=>x.bucketName===I.name);return F.length+1>ul||E.length+C.metadataBytes+F.reduce((x,j)=>x+j.size,0)>Rt||b.length+1>Math.min(p.diskMaxEntries,ft-1)||E.length+b.reduce((x,j)=>x+j.size,0)>p.diskMaxBytes}for(;O();){const b=F.filter(z=>z.bucketName===I.name),j=b.length+1>Math.min(p.diskMaxEntries,ft-1)||E.length+b.reduce((z,B)=>z+B.size,0)>p.diskMaxBytes?b[0]:F[0];if(!j||!await A(j))throw new Error("缓存容量不足或条目已变化");F.splice(F.indexOf(j),1)}await L();const P=await u(i);if(!P.some(b=>b.name===I.name)&&P.length>=ft-1)throw new Error("缓存目录超过治理上限");if(await I.create({recursive:!0,exclusive:!1},t),!Te(l.revisions,await T(m.scopeIds,m.namespace)))return!1;try{await D.create({recursive:!1,exclusive:!0},t)}catch(b){a(b),await D.stat(t)}return await D.write(E,t),c(),Te(l.revisions,await T(m.scopeIds,m.namespace))}),invalidate:(l,p)=>d(async()=>{await f();const m=n.file(`${await Ar([l,p??null])}.revision`);await g(m);try{await m.create({recursive:!1,exclusive:!0},t)}catch(E){a(E),await m.stat(t)}await m.write(Pr.encode(es()),t),c();try{const{entries:E}=await U();for(const I of E){if(p!==void 0&&I.entry.address.namespace!==p||!l.every((C,F)=>I.entry.address.scopeIds[F]===C))continue;const D=await T(I.entry.address.scopeIds,I.entry.address.namespace);Te(I.entry.revisions,D)||await A(I)}await L()}catch(E){a(E),c()}})}}function Dr(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const hl="RATE_LIMITED_BY_RUNTIME",ml="RATE_LIMITED",mc=20,gc=40,pc=150,yc=20,Ec=1e4,Ic=45e3,wc=1,gl=300*1e3,pl=64;function ht(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function yl(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function El(e={}){const t=e.now??Date.now,r=yl(e.coalesceWindowMs,pc),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,ht(e.budget?.ratePerSecond,mc)),burst:Math.max(1,Math.floor(ht(e.budget?.burst,gc)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(ht(e.loopDetection?.maxCalls,yc))),windowMs:Math.max(1,Math.floor(ht(e.loopDetection?.windowMs,Ec)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(ht(e.circuitBreaker?.failureThreshold,wc))),openMs:Math.max(1,Math.floor(ht(e.circuitBreaker?.openMs,Ic)))},s=new Map,a=new Map,c=new Set,d=new Map,f=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},h={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let u=!1;function g(N){try{e.onReport?.(N)}catch{}}function T(N,l){if(!i)return{exceeded:!1,count:0};const p=a.get(N)??[],m=l-i.windowMs;let E=0;for(;E<p.length&&p[E]<=m;)E+=1;E>0&&p.splice(0,E);const I=p.length>=i.maxCalls;return I||(p.push(l),p.length>i.maxCalls+1&&p.splice(0,p.length-(i.maxCalls+1))),a.set(N,p),{exceeded:I,count:p.length}}function M(N){if(!n)return!0;const l=Math.max(0,N-f.updatedAt)/1e3;return f.tokens=Math.min(n.burst,f.tokens+l*n.ratePerSecond),f.updatedAt=N,f.tokens<1?!1:(f.tokens-=1,!0)}function S(N){if(!n)return 0;const l=Math.max(0,N-f.updatedAt)/1e3,p=Math.min(n.burst,f.tokens+l*n.ratePerSecond);return Math.max(0,Math.ceil((1-p)/n.ratePerSecond*1e3))}function w(N,l,p,m,E){if(!o)return;const I=d.get(l),D=(I?.open?0:I?.failures??0)+1;if(D<o.failureThreshold){d.set(l,{open:!1,openedAt:0,openMs:0,failures:D});return}const C=Math.min(Math.max(o.openMs,m),gl);d.set(l,{open:!0,openedAt:E,openMs:C,failures:D}),h.circuitOpened+=1,g({type:"circuit_opened",capability:N,endpointId:l,status:p,openMs:C,timestamp:E})}function _(N){const l=d.get(N);l&&!l.open&&d.delete(N)}function A(N){for(const[l,p]of s)!p.pending&&p.expiresAt<=N&&s.delete(l);for(;s.size>=pl;){const l=[...s].find(([,p])=>!p.pending);if(!l)break;s.delete(l[0])}}function v(N,l){if(N===void 0)return;const p=s.get(N);p?.promise===l&&(p.pending=!1)}function U(N,l){if(N===void 0)return;s.get(N)?.promise===l&&s.delete(N)}async function L(N){if(u)return N.load();const l=t();if(o){const I=d.get(N.endpointId);if(I?.open){const D=I.openedAt+I.openMs-l;if(D>0)throw h.circuitRejected+=1,g({type:"circuit_rejected",capability:N.capability,endpointId:N.endpointId,retryAfterMs:D,timestamp:l}),Ml("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:N.endpointId,retryAfterMs:D});d.delete(N.endpointId)}}const p=T(N.endpointId,l);p.exceeded&&i?c.has(N.endpointId)||(c.add(N.endpointId),g({type:"loop_detected",capability:N.capability,endpointId:N.endpointId,count:p.count,windowMs:i.windowMs,timestamp:l})):c.delete(N.endpointId);const m=r>0?N.coalesceKey:void 0;if(m!==void 0){const I=s.get(m);if(I&&(I.pending||I.expiresAt>l))return h.coalesced+=1,g({type:"coalesced",capability:N.capability,endpointId:N.endpointId,timestamp:l}),I.promise;I&&s.delete(m)}if(p.exceeded&&i)throw h.loopRejected+=1,rs("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:N.capability,endpointId:N.endpointId,count:p.count,windowMs:i.windowMs});if(!M(l)){h.budgetRejected+=1;const I=S(l);throw g({type:"budget_exhausted",capability:N.capability,endpointId:N.endpointId,retryAfterMs:I,timestamp:l}),rs("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:N.capability,endpointId:N.endpointId,retryAfterMs:I})}m!==void 0&&A(l);const E=N.load().then(I=>(v(m,E),_(N.endpointId),I),I=>{U(m,E);const D=Il(I);throw D!==void 0&&w(N.capability,N.endpointId,D,wl(I),l),I});return m!==void 0&&s.set(m,{promise:E,expiresAt:l+r,pending:!0}),E}return{execute:L,invalidateCoalescing(){s.clear()},snapshot(){return{...h,openCircuits:[...d.entries()].filter(([,N])=>N.open).map(([N])=>N)}},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function Il(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 wl(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 rs(e,t){return{code:hl,message:e,data:t}}function Ml(e,t){return{code:ml,message:e,data:t}}const Mc=3e4,Nc=6e4,Vi=1440*60*1e3;function Nl(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??Mc)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??Nc)):0,steamGameListTtlMs:t?Al(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:mc,burst:gc},coalesceWindowMs:r?.coalesceWindowMs??pc,loopDetection:r?.loopDetection??{maxCalls:yc,windowMs:Ec},circuitBreaker:r?.circuitBreaker??{failureThreshold:wc,openMs:Ic}}}}function Al(e){return e===void 0||!Number.isFinite(e)?Vi: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 H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dl(e){return typeof e=="object"&&e!==null}function ye(e,t){const r=e.data;if(!Dl(r)||typeof r.status!="string")throw new Error(t);return r}const Ac={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Tl={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 gr(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Sl(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function bl(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=Sl(r.consent_challenge)),{...t,result:n}}const Ol={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=>({...gr(e.runtimeContext),challenge:e.challenge}),parse:e=>ye(e,"小程序授权取消接口响应异常")},_l={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=>gr(e.runtimeContext),parse:e=>ye(e,"小程序授权撤销接口响应异常")},Ll={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=>gr(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}:{}}}}},vl={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=>({...gr(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>bl(e)},Cl={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=>({...gr(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}}}},Rl=64;function Dc(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??Rl)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(h){for(const[u,g]of i)g.expiresAt<=h&&i.delete(u)}function d(h,u,g){if(a||t<=0||g!==s)return;const T=n();for(c(T),i.delete(h);i.size>=r;){const M=i.keys().next();if(M.done)break;i.delete(M.value)}i.set(h,{expiresAt:T+t,value:u})}function f(h,u){if(a)return u();if(t>0){const S=i.get(h);if(S&&S.expiresAt>n())return Promise.resolve(S.value);S&&i.delete(h)}const g=o.get(h);if(g)return g;const T=s,M=u().then(S=>(d(h,S,T),S)).finally(()=>{o.get(h)===M&&o.delete(h)});return o.set(h,M),M}return{read:f,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function Pl(e,t){return t?e?"server":"local":"legacy"}function kl(e,t){if(e==="local")throw y("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const xl=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],jl=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),zl=/authorization|cookie|pkey|password|secret|token/i,Tc=/authorization|cookie|pkey|token|password|secret/i;function Se(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ul(e){for(const t of Object.keys(e))if(!jl.has(t))throw new se(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of xl)if(Object.prototype.hasOwnProperty.call(e,t)&&Se(e,t)!==void 0)throw new se(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Se(e,"bodyEncoding")!==void 0&&Se(e,"bodyEncoding")!=="json"&&Se(e,"bodyEncoding")!=="form")throw new se("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Se(e,"failurePresentation")!==void 0&&Se(e,"failurePresentation")!=="none")throw new se("endpoint failurePresentation 必须为 none");if(Se(e,"auth")!==void 0&&Se(e,"auth")!=="none"&&Se(e,"auth")!=="optional"&&Se(e,"auth")!=="required")throw new se("endpoint auth 必须为 none、optional 或 required")}function Gt(e){if(Array.isArray(e))return e.map(Gt);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))zl.test(n)||(r[n]=Gt(i));return r}function ns(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Tc.test(r)||(t[r]=n);return t}function Hl(e){if(!e)return;const t=Object.keys(e).find(r=>Tc.test(r));if(t)throw new se(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Tt 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 is=1440*60*1e3,Fl=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function Vl(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,is):void 0}if(!Fl.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,is):void 0}function Bl(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 Sc(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class St extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Sc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class pr extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Sc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function Ql(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:Gt(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:ns(o),method:e.method,metadata:{endpointId:e.id},query:Gt(n),timeout:e.timeout,url:r},data:Gt(a.data),headers:ns(a.headers)||{},status:a.status,statusText:a.statusText}}async function Qn(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(Ul(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;Hl(a);const c=async()=>{let h;try{h=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(g){throw g instanceof se?g:new St({endpointId:t.id,cause:g})}if(h.status<200||h.status>=300)throw new Tt({endpointId:t.id,status:h.status,retryAfterMs:Vl(h.headers)});const u=Ql(t,r,i,o,s,a,n,h);if(t.parse)try{return await t.parse(u,r)}catch(g){throw new pr({endpointId:t.id,cause:g})}return u.data},d=n.gate;if(!d)return c();const f=Bl(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...f===void 0?{}:{coalesceKey:f},load:c})}const Yl=new Set(Dt),wo="steam_account",bc=new Set(Dt.filter(e=>e!==wo)),Gl=1e3;function ql(e){const t=new Set,r=Dc({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??Mc))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??Pl(e.networkEnabled===!0,c),f=e.requestPolicyEnabled!==!1,h=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 R;try{R=await e.authorizationContext.get(e.operationContext)}catch{throw y("REQUEST_FAILED","读取 Runtime auth context 失败")}if(R.steamAccount!==c||R.userDataMode!==d)throw y("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const O=R.token.trim();if(!O)throw y("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:O}}const g=e.account.onChange(R=>{T(),M("heybox_app_login_change",{isHeyboxAppLoggedIn:!!R})});function T(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function M(R,O){R==="user_info_authorization_change"&&ef(O)&&r.invalidate();for(const P of t)try{P(R,O)}catch{}}function S(){const R=e.identity.get()?.miniProgramId?.trim();if(!R)throw y("INVALID_STATE","当前能力缺少 canonical 小程序身份");return R}function w(){if(o||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function _(){w();let R;try{R=await e.account.getCurrentUserId(e.operationContext)}catch(O){throw cs(O,e.operationContext.signal,"读取小黑盒账号失败")}return typeof R=="string"&&R.trim()?R.trim():void 0}async function A(R,O){const P=await _();if(i!==O||P!==R)throw y("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function v(R){w();try{await e.account.ensureAuthenticated({trustedUserGesture:R,reason:"runtime_auth",signal:e.operationContext.signal})}catch(P){throw cs(P,e.operationContext.signal,"小黑盒登录失败")}const O=await _();if(!O)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return O}async function U(R,O,P=e.operationContext.signal){try{if(P.aborted)throw Bi();return await Xl(Qn(e.network,R,O,{...e.operationContext,credentials:"heybox-session",signal:P,...h?{gate:h}:{}}),P)}catch(b){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):b instanceof se?y("REQUEST_UNSUPPORTED",b.message):b instanceof pr?y("INVALID_RESPONSE","授权接口响应不合法"):b instanceof St?y("REQUEST_FAILED","授权请求失败"):b instanceof Tt?f&&(b.status===403||b.status===429)?y("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:b.status,...b.retryAfterMs===void 0?{}:{retryAfterMs:b.retryAfterMs}}):y("REQUEST_FAILED",b.message):Oc(b)?b:y("REQUEST_FAILED","授权请求失败")}}async function L(R,O){await U(Ol,{runtimeContext:{miniProgramId:R,...await u()},challenge:O}).catch(()=>{})}function N(R){const O=async()=>{const b=ss(e.operationContext.signal);a=b;try{return await R(b.signal)}finally{a===b&&(a=void 0),b.abort()}},P=s.then(O,O);return s=P.then(()=>{},()=>{}),P}async function l(R,O,P,b,x){if(!P)throw await L(R,O.challenge),y("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await L(R,O.challenge),y("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return N(async j=>{await A(b,x);const z=await p(R,O.displayedScopes,j);await A(b,x);let B;try{B=await e.authPresentation.confirmAuthorization({miniProgramId:R,scopes:O.displayedScopes,...z,signal:j})}catch(G){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await A(b,x),await L(R,O.challenge),Wl("REQUEST_FAILED","授权确认界面执行失败",G))}if(await A(b,x),B.status!=="granted")throw await L(R,O.challenge),y("AUTHORIZATION_CANCELLED","用户取消授权");const Q=Jl(B.grantedScopes,O.displayedScopes,c);if(!Q.includes("identity"))throw await L(R,O.challenge),y("AUTHORIZATION_CANCELLED","用户拒绝授权");return Q})}async function p(R,O,P){const b=ss(P),x=setTimeout(()=>b.abort(),Gl);try{const j=Zl(e.miniProgramPresentation),[z,B]=await Promise.all([j?Promise.resolve(j):m(R,b.signal),O.includes("profile")?E(b.signal):Promise.resolve(void 0)]);return{...z?{miniProgram:z}:{},...B?{userProfile:B}:{}}}finally{clearTimeout(x),b.abort()}}async function m(R,O){try{const P=e.identity.get()?.version?.trim(),b=await U(Tl,{mini_program_id:R,...P?{miniprogram_version:P}:{}},O),x=mt(b,"小程序公开资料"),j=Nt(x.name),z=Nt(x.icon_url);return j||z?{...j?{name:j}:{},...z?{avatarUrl:z}:{}}:void 0}catch{return}}async function E(R){try{const O=await U(Ac,void 0,R),P=mt(O,"账号基础信息"),b=Nt(P.display_username),x=Nt(P.display_avatar);return b||x?{...b?{nickname:b}:{},...x?{avatar:x}:{}}:void 0}catch{return}}async function I(R,O){if(kl(d,"auth.login"),!c&&R.includes(wo))throw y("INVALID_PARAMS","auth.login 参数不合法");const P=S(),b=await v(O),x=i,j=await U(vl,{runtimeContext:{miniProgramId:P,...await u()},scopes:R});await A(b,x);const z=mt(j,"小程序登录"),B=as(z,"loginCode"),Q=as(z,"consentChallenge");if(B===Q)throw y("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let G;if(B)G=os(z.loginCode,c);else{const te=$l(z.consentChallenge,c),X=await l(P,te,O,b,x);await A(b,x);const Z=await U(Cl,{runtimeContext:{miniProgramId:P,...await u()},challenge:te.challenge,selectedScopes:X});if(await A(b,x),G=os(mt(Z,"小程序登录确认"),c),G.scopes.some(q=>!X.includes(q)))throw y("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const te of G.scopes)n.add(te);return r.invalidate(),M("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),M("user_info_authorization_change",ri(n,c)),G}async function D(R,O){const P=i,b=await U(Ll,{runtimeContext:{miniProgramId:O,...await u()}});await A(R,P);const x=Kl(mt(b,"用户本地身份"),c);for(const j of c?Dt:bc)n.add(j);return M("user_info_authorization_change",ri(n,c)),x}function C(R){w();const O=S(),P=`${R}\0${O}\0${i}\0${c}`;return r.read(P,()=>D(R,O))}async function F(R){if(!R)throw y("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const O=S(),P=i,b=await _();if(!b)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const x=await U(_l,{runtimeContext:{miniProgramId:O,...await u()}});await A(b,P),mt(x,"用户授权撤销"),T(),M("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{login:I,getOrCreateLocalIdentity:C,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>ri(n,c),revoke:F,onEvent(R){return t.add(R),()=>t.delete(R)},dispose(){o||(o=!0,T(),r.dispose(),g(),t.clear())}}}function Wl(e,t,r){const n=y(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function mt(e,t){if(!H(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(!H(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function os(e,t){if(!H(e))throw y("INVALID_RESPONSE","login code 必须是对象");const r=Dn(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 $l(e,t){if(!H(e))throw y("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Dn(e.requestedScopes,"challenge requestedScopes",t),n=Dn(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 Kl(e,t){if(!H(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 Jl(e,t,r){const n=Dn(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw y("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Nt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Zl(e){const t=Nt(e?.name),r=Nt(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function ss(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 Xl(e,t){return t.aborted?Promise.reject(Bi()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Bi()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Bi(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Dn(e,t,r){const n=r?Yl:bc;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?Dt:Dt.filter(n=>n!==wo);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function as(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ef(e){return H(e)?Object.values(e).some(t=>t==="denied"):!1}function Oc(e){return H(e)&&typeof e.code=="string"&&typeof e.message=="string"}function cs(e,t,r){return t.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Oc(e)?e:y("REQUEST_FAILED",r)}const tf=new Set(Dt);function rf(e){return{[qr]:async(t,r)=>e.authorization.login(nf(t),r.trustedUserGesture)}}function nf(e){if(e===void 0)return["identity"];if(!H(e)||Object.keys(e).some(t=>t!=="scopes"))throw ds();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!tf.has(t))||new Set(e.scopes).size!==e.scopes.length)throw ds();return[...e.scopes]}function ds(){return y("INVALID_PARAMS","auth.login 参数不合法")}const of={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.delete.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/current/delete",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return ye(e,"排行榜记录删除接口响应异常")}},sf={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,"当前排行榜记录接口响应异常")}},af={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,"排行榜信息接口响应异常")}},cf={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,"排行榜列表接口响应异常")}},df={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 us(e){return e instanceof se?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function ee(e){if(e.aborted)throw kr()}function W(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(kr());let n;try{n=e()}catch(i){return Promise.reject(us(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(kr())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(kr()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(us(d))))})}const uf="default",lf=/^[A-Za-z0-9_-]{1,64}$/,ff=300*1e3,hf=250,mf=3,gf={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 pf{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Ef(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(df,{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=xt("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(cf,{miniProgramId:r,...t}),s=kt(o,Ne);if(!ve(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw ne(`${Ne} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw ne(`${Ne} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>ni(a,Ne)),...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=xt("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(sf,{miniProgramId:n,...t}),c=kt(a,Qe);if(!ve(c))throw ne(`${Qe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:ni(c.entry,Qe)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(of,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=kt(i,st);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!ve(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",xt("info"),async()=>{const i=await this.request(af,{miniProgramId:r,...t}),o=kt(i,Le);if(!ve(o)||typeof o.key!="string"||!lf.test(o.key))throw ne(`${Le} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw ne(`${Le} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw ne(`${Le} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw ne(`${Le} 返回的 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=xt(t,n),d=this.inflight.get(c);if(d)return d.promise;const f=this.accountGeneration,h=o?.generation,u=i().then(g=>(this.assertAccountGeneration(f),o&&s&&o.generation===h&&(r==="list"?s.size>=hf&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+ff,value:g})),g)).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>=mf)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)fs(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){fs(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 W(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw ms(n)?n:hs()}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw Ie("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw Ie("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return xt(t,r??uf)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw Ie("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){this.assertUsable();const n={request:async(i,o)=>(this.assertUsable(),this.options.network.request(i,o))};try{return await W(()=>Qn(n,t,r,{...this.options.operationContext,credentials:"heybox-session",...this.requestGateContext?{gate:this.requestGateContext}:{}}),this.options.operationContext.signal)}catch(i){if(ms(i)||Ft(i,"REQUEST_UNSUPPORTED")||Ft(i,"RATE_LIMITED")||Ft(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof se)throw Ie("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求");if(i instanceof St&&Ft(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Tt){if(this.options.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw Ie("RATE_LIMITED","排行榜请求已被网关限流,请稍后重试",{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw Ie("UNAUTHORIZED","当前用户未登录")}throw i instanceof St||i instanceof Tt?hs():i instanceof pr?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(ee(this.options.operationContext.signal),this.disposed)throw Ie("INVALID_STATE","Cloud capability 已释放")}}function yf(e){return new pf(e)}function Ef(e,t){try{return e.onChange(t)}catch(r){if(Ft(r,uc))return()=>{};throw r}}function kt(e,t){if(!ve(e)||typeof e.status!="string")throw ne(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw If(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(!ve(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(!ve(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 If(e){if(e.status==="login"||e.status==="relogin")throw Ie("UNAUTHORIZED",Ht(e.msg)||"当前用户未登录");const t=ls(e.result)??ls(e),r=Ht(t?.user_message)||Ht(e.msg)||Ht(t?.developer_message)||"排行榜请求失败";throw t?Ie(wf(t),r,{status:e.status,sbe:t}):Ie("HEYBOX_API_ERROR",r,{status:e.status})}function ls(e){return ve(e)&&ve(e.sbe)?e.sbe:void 0}function wf(e){const t=Ht(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 gf[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 fs(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function xt(...e){return JSON.stringify(e)}function ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ht(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Ft(e,t){return ve(e)&&e.code===t}function Ie(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function ne(e){return Ie("INVALID_RESPONSE",e)}function hs(){return Ie("REQUEST_FAILED","排行榜请求失败")}function ms(e){return e instanceof Error&&e.name==="AbortError"}const Mf=/^[A-Za-z0-9_-]{1,64}$/,gs=20,Nf=100,ps=2048;function Af(e){const t=yf(e);return{handlers:{[ke]:async n=>t.submit(Df(n)),[Ne]:async n=>t.getList(Tf(n)),[Qe]:async n=>t.getCurrentUserEntry(ii(n,Qe)),[st]:async n=>t.deleteCurrentUserEntry(ii(n,st)),[Le]:async n=>t.getInfo(ii(n,Le))},dispose:()=>t.dispose()}}function Df(e){const t=Mo(e,ke,!1);if(No(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{...Ao(t.key,ke),score:t.score,...t.extra===void 0?{}:{extra:Sf(t.extra)}}}function Tf(e){if(e===void 0)return{limit:gs};const t=Mo(e,Ne,!0);No(t,["key","limit","cursor"],Ne);const r=t.limit===void 0?gs:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>Nf)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{...Ao(t.key,Ne),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function ii(e,t){if(e===void 0)return{};const r=Mo(e,t,!0);return No(r,["key"],t),Ao(r.key,t)}function Mo(e,t,r){if(e===void 0&&r)return{};if(!_c(e))throw Ce("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function No(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Ce("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Ao(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 Sf(e){if(!_c(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 _c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ce(e,t){return{code:e,message:t}}const bf=new Set(["stdio","attachments","notifications"]),Lc=new Set(["windows-x64","macos-arm64"]),Of=new Set(["unsigned","valid","invalid","unknown"]),_f=/^[a-f0-9]{64}$/,Lf=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),vf=new Set(cc),Cf=new Set([...cc,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),vc=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 Rf(e){const t=async(n,i,o,s)=>{const a=Pf(n);try{_e(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return _e(i.signal),c}catch(c){throw Yi(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(d=>kf(d,i)).catch(d=>{throw Yi(d)});_e(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(_e(o.signal),c.status!=="granted")throw y("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[vn]:(n,i)=>t(n,i,async(o,s)=>Qi(await e.companion.getInfo(o,s),o)),[Cn]:(n,i)=>t(n,i,async(o,s)=>ys(await e.companion.getPreparationStatus(o,s))),[Rn]:(n,i)=>t(n,i,async(o,s)=>{const a=ys(await e.companion.getPreparationStatus(o,s));return _e(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),_e(i.signal),Qi(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(Rc(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[Pn]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[kn]:(n,i)=>t(n,i,async(o,s)=>Es(await e.companion.getActiveSession(o,s),o)),[xn]:(n,i)=>t(n,i,async(o,s)=>{const a=Es(await e.companion.getActiveSession(o,s),o);return _e(i.signal),a||(await r("launch",o,i),_e(i.signal),Pc(await e.companion.launch(o,s),o))}),[jn]:(n,i)=>gt(n,i,e,"write"),[zn]:(n,i)=>gt(n,i,e,"closeStdin"),[Un]:(n,i)=>gt(n,i,e,"terminate"),[Hn]:(n,i)=>gt(n,i,e,"ackOutput"),[Fn]:async(n,i)=>{const o=await gt(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Vn]:(n,i)=>gt(n,i,e,"showNotification")}}function Pf(e){if(!H(e)||typeof e.alias!="string"||!Nu.test(e.alias))throw y("INVALID_PARAMS","Companion alias 不合法");return e.alias}function _e(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function gt(e,t,r,n){if(!H(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw y("INVALID_PARAMS","Companion Session controller 不合法");try{_e(t.signal);const i=await r.companion[n](xf(e,n),{...r.operationContext,signal:t.signal});return _e(t.signal),i}catch(i){throw Yi(i)}}function De(){throw y("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Cc(e){return!Array.isArray(e)||e.some(t=>!bf.has(t))?De():Object.freeze([...new Set(e)])}function Qi(e,t){return!H(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Lc.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!Of.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?De():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Cc(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function kf(e,t){const r=Qi(e,t);return!H(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!_f.test(e.sha256)?De():Object.freeze({...r,sha256:e.sha256})}function Rc(e){return H(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}):De():De()}function ys(e){return H(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Rc(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&H(e.error)&&typeof e.error.code=="string"&&vf.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:vc[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):De():De()}function Pc(e,t){return!H(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Lc.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?De():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Cc(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Es(e,t){return e===void 0?void 0:Pc(e,t)}function xf(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!oc(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 jf(e){return!H(e)||!Lf.has(String(e.reason))?De():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):De():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?De():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function zf(e){if(!H(e)||!H(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||!oc(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:jf(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 Yi(e,t){return H(e)&&typeof e.code=="string"&&Cf.has(e.code)?y(e.code,vc[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&H(e)&&e.name==="AbortError"?y(t,"Companion 准备已取消"):y("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Is=5e3,ws=1e4;function ue(e){throw{code:"INVALID_PARAMS",message:e}}function Do(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kc(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&ue(`${r} 不支持字段: ${n.join(", ")}`)}function Uf(e){if(e===void 0)return{intensity:"light",delay:0};if(!Do(e))return ue("device.vibrate 参数必须是对象");kc(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return ue("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Is?ue(`device.vibrate delay 必须是 0-${Is} 的整数毫秒`):{intensity:r,delay:n}}function Hf(e){return Do(e)?(kc(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?ue("device.setClipboard text 必须是非空字符串"):e.text.length>ws?ue(`device.setClipboard text 不能超过 ${ws} 字符`):{text:e.text}):ue("device.setClipboard 参数必须是对象")}function Ff(e){return typeof e=="string"?e.trim()?e:ue("device.executeProtocol 协议字符串不能为空"):Do(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?ue("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(Gi(e,new Set),e):ue("device.executeProtocol 参数必须是协议字符串或协议对象")}function Gi(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||ue("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":ue("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":ue(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&ue("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)Gi(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&ue("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))Gi(i,t);t.delete(r)}function Vf(e){return{[En]:async t=>{ee(e.operationContext.signal),await W(()=>e.presentation.vibrate(Uf(t),e.operationContext),e.operationContext.signal)},[In]:async t=>{ee(e.operationContext.signal),await W(()=>e.presentation.setClipboard(Hf(t),e.operationContext),e.operationContext.signal)},[wn]:async(t,r)=>{const n=at(e.operationContext,r.signal);ee(n.signal);const i=Ff(t);await W(()=>e.protocol.invoke(i,n),n.signal)}}}const Bf=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"]),Qf={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=To(e),r=t&&Bf.has(t)?y(t,Qf[t]??"文件操作失败"):y("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Pe(e){try{return e()}catch(t){throw cr(t)}}function To(e){try{if(!H(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function xc(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):qi,remove:o?s=>e.remove(s):zc,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):qi,stat:s=>e.stat(s)})}function jc(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=>xc(e.file(a),n,{allowRemove:o}),directory:a=>jc(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):qi,remove:s?(a,c)=>e.remove(a,c):zc,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function qi(){return Promise.reject(y("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function zc(){return Promise.reject(y("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Ms=1024;class Yf{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 Tr(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Pe(()=>{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>Ms)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw y("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>Tr(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 As(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Bn(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const r=qf(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(Pe(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Wf(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:Pe(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Ts(t),Tr(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Pe(()=>{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 Pe(()=>{if(H(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Tr(n.handle,Ns(t.ref,n.handle.name))}if(H(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return As(n.handle,Gf(t.ref,n.handle.name))}throw y("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=yr(r),i=this.prepareFile(Pe(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:Ns(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw y("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Pe(()=>{Ts(t);const i=n??t.mode;return Ds(t.mode,i),{handle:xc(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Pe(()=>{Jf(t,i);const o=n??t.mode;return Ds(t.mode,o),{handle:jc(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Ms)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=$f();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(!Kf(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 Ae("files.sandbox");return this.prepareDirectory(Pe(()=>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 Ae("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 Ns(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 Gf(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 Tr(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function As(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Ds(e,t){if(t==="readwrite"&&e!=="readwrite")throw y("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function qf(e){return Bn(e)||Uc(),e}function Wf(e){return ic(e)||Uc(),e}function Uc(){throw y("INVALID_PARAMS","文件引用不合法")}function $f(){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 Kf(e){return/^[0-9a-f]{32}$/.test(e)}function Ts(e){if(!H(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 Jf(e,t=!1){if(!H(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 Ss=1e3,Zf=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function Xf(e){const t=r=>at(e.operationContext,r.signal);return{files:{[sn]:async(r,n)=>{oi(n);const i=si(e.picker),o=eh(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=th(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=rh(r).suggestedName,s=t(n);if(!i.saveFile)throw Ae("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(bs(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 Ae(rr);await me(()=>o.handle.remove(t(n)))},[dn]:async(r,n)=>{const i=Ee(r);return Os(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!H(o)||o.kind!=="file")throw Ls()})},[nr]:async(r,n)=>{const i=Ee(r),o=_s(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 文本")}},[un]:async(r,n)=>{const i=Ee(r,["content"]);typeof i.content!="string"&&Me("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 _s(o)},[ln]:async(r,n)=>{const i=Ee(r,["content"]),o=e.registry.resolveFile(i.target);pt(o.mode),await me(()=>o.write(ih(i.content),t(n)))},[or]:async(r,n)=>{const i=Ee(r),o=await me(()=>e.registry.resolveFile(i.target).stat(t(n)));return oh(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(bs(i),t(n)))},[sr]:async(r,n)=>{const i=Ee(r,["recursive"]);if(H(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 Ae(sr);await me(()=>o.handle.remove({recursive:i.recursive===void 0?!1:Tn(i.recursive,"recursive")},t(n)))},[hn]:async(r,n)=>{const i=Ee(r);return Os(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!H(o)||o.kind!=="directory")throw Ls()})},[mn]:async(r,n)=>{const i=Ee(r,["limit"]),o=nh(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 eh(e){if(e===void 0)return{mode:"read",multiple:!1};H(e)||Me("pickFiles 参数必须是对象"),Yn(e,["mode","accept","multiple"]);const t=Hc(e.mode,"read"),r=e.multiple===void 0?!1:Tn(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)))&&Me("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function th(e){return e===void 0?{mode:"read"}:(H(e)||Me("pickDirectory 参数必须是对象"),Yn(e,["mode"]),{mode:Hc(e.mode,"read")})}function rh(e){return H(e)||Me("saveFile 参数必须是对象"),Yn(e,["suggestedName"]),{suggestedName:yr(e.suggestedName,"suggestedName")}}function Ee(e,t=[]){return(!H(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Me("文件操作参数必须包含 target"),Yn(e,["target",...t]),e}function bs(e){return{recursive:e.recursive===void 0?!1:Tn(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Tn(e.exclusive,"exclusive")}}function Hc(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&Me("mode 必须是 read 或 readwrite"),e)}function Tn(e,t){return typeof e!="boolean"&&Me(`${t} 必须是布尔值`),e}function nh(e){if(e===void 0)return Ss;if((!Number.isSafeInteger(e)||e<=0)&&Me("limit 必须是正整数"),e>Ss)throw y("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Yn(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&Me(`不支持字段: ${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 Ae("files.external");return e}async function Os(e){try{return await e(),!0}catch(t){if(Zf.has(To(t)??""))return!1;throw cr(t)}}async function me(e){try{return await e()}catch(t){throw cr(t)}}function ih(e){return e instanceof Uint8Array||Me("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Me("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function _s(e){if(!(e instanceof Uint8Array))throw y("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Ls(){return y("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function oh(e){if(!H(e)||e.kind!=="file"||!sh(e.size))throw y("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!ah(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 sh(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ah(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Me(e){throw y("INVALID_PARAMS",e)}const Sr=4294967296;function ch(e){const t=new dh;return t.write(e),t.finish()}class dh{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<Sr?(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=uh(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<Sr)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/Sr),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Sr)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function uh(e){const t=new Uint8Array(lh(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 lh(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 Fc(e){Wi(e);const t=ch(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 Wi(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)Wi(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");Wi(s,t+1,r)}r.delete(e)}const fh=["pc","console","mobile"],hh=["game","wiki"];function Sn(e){throw{code:"INVALID_PARAMS",message:e}}function mh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e,t){return typeof e!="string"||!e.trim()?Sn(t):e.trim()}function vs(e,t,r){return typeof e!="string"||!t.includes(e)?Sn(r):e}function gh(e){const t={target:"game_detail",appId:Ge(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:vs(e.gameType,fh,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=vs(e.page,hh,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Ge(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Ge(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function ph(e){return{target:"user_detail",userId:Ge(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function yh(e){const t={target:"post_detail",linkId:Ge(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Ge(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Ge(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Eh(e){const t={target:"mini_program",miniProgramId:Ge(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Ih(e){return mh(e)?e.target==="game_detail"?gh(e):e.target==="user_detail"?ph(e):e.target==="post_detail"?yh(e):e.target==="mini_program"?Eh(e):Sn("navigation.openAppPage target 不支持"):Sn("navigation.openAppPage options 必须是对象")}function wh(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 Nh(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 Ah(e){const t=e;return t.target==="game_detail"?wh(t):t.target==="user_detail"?Mh(t):Nh(t)}const Dh="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",Th="data-hb-sdk-fullscreen-exit",Sh=3e3,bh=2e3,Cs="var(--white-70a,rgba(255,255,255,.7))",Rs="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function Oh(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(Th,""),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 ${Cs}`,`box-shadow:${Rs}`,"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=Dh,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let o=!0,s=!1,a=!1,c,d;function f(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function h(){o||(t.style.width=f())}function u(){d?.cancel(),d=void 0}function g(S=bh){clearTimeout(c),c=setTimeout(()=>{u(),o=!1,t.style.width=f(),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")},S)}function T(){u(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Cs,t.style.boxShadow=Rs,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),g()}async function M(){if(!(s||a)){if(!o){T();return}a=!0,clearTimeout(c),u();try{await e()}catch{}finally{a=!1,s||T()}}}return t.addEventListener("click",M),window.addEventListener("resize",h),document.body.append(t),!r&&t.animate&&(d=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),g(Sh),{dispose(){s=!0,clearTimeout(c),u(),t.removeEventListener("click",M),window.removeEventListener("resize",h),t.remove()}}}const Vc=1e4;function Bc(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 W(o,t.signal)}catch(s){throw r??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",n)}}}function Qc(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 br(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function _h(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??=Oh(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(u,g){if(t===u){if(t=void 0,clearTimeout(u.timer),e.operationContext.signal.removeEventListener("abort",d),"error"in g)u.controller.abort();else if(r={options:u.options,result:g.result},n=u.options,a(u.options),e.onApplied?.(u.options),g.result.supported&&!ai(i,u.options)){i={...u.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:u.source})}catch{}}for(const T of u.subscribers)T.dispose(),"error"in g?T.reject(g.error):T.resolve(g.result);u.subscribers.clear()}}function d(){t&&c(t,{error:br()})}function f(u,g){return new Promise((T,M)=>{const S=()=>{u.subscribers.delete(w),w.dispose(),M(br()),u.subscribers.size===0&&c(u,{error:br()})},w={resolve:T,reject:M,dispose:()=>g?.removeEventListener("abort",S)};u.subscribers.add(w),g?.addEventListener("abort",S,{once:!0}),g?.aborted&&S()})}const h={async apply(u,g,T="api"){if(ee(e.operationContext.signal),g?.aborted)throw br();const M=Qc(u),S=t?.options??n,w={mode:M.orientation??S.mode,hideCapsule:M.fullscreen??S.hideCapsule};w.mode==="landscape"&&(w.hideCapsule=!0);const _=e.presentation.applyOrientation;if(!_)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&ai(t.options,w))return f(t,g);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),r&&ai(r.options,w))return r.result;r=void 0;const A={options:w,source:T,controller:new AbortController,subscribers:new Set};t=A;const v=f(A,g);return e.operationContext.signal.addEventListener("abort",d,{once:!0}),g||(A.timer=setTimeout(()=>{c(A,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Vc)),W(()=>_.call(e.presentation,w,{...e.operationContext,signal:A.controller.signal}),A.controller.signal).then(U=>c(A,{result:U??{supported:!0}}),U=>c(A,{error:U})),v},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return h}function Yc(e){throw{code:"INVALID_PARAMS",message:e}}function Ps(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Yc(`${t} 不支持参数`)}function Lh(e){return{[Mn]:async t=>{ee(e.operationContext.signal),Ps(t,"navigation.close"),await W(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Nn]:async t=>{ee(e.operationContext.signal),Ps(t,"navigation.reload"),await W(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[An]:async(t,r)=>{const n=at(e.operationContext,r?.signal);ee(n.signal);const i=Ih(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Fc(i.extra)}catch{Yc("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=Bc(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}ee(n.signal),await W(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await W(()=>e.presentation.openAppPage(Ah(i),n),n.signal)}}}const vh=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Ch=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Rh=new Set(["range","if-range","a-im"]),Ph=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"]),kh=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Or={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class xh{constructor(t){this.signal=t}phase="initial";transition(t){if(Or[t]<=Or[this.phase])throw y("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Or[this.phase]<Or.committed&&this.signal.aborted)throw qc()}normalizeHostError(t,r){return this.throwIfCancelled(),bo(t,r,this.signal)}}async function jh(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Ae("network.download");const o=at(r.operationContext,t.signal),s=new xh(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Fh(e,i,o)}catch(f){throw s.normalizeHostError(f,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(f){throw s.normalizeHostError(f,"network")}let d=!1;try{s.throwIfCancelled(),s.transition("validate");const f=Bh(c);Qh(c,f);const h=Yh(c.status,f);if(e.maxBytes!==void 0&&h.expectedBytes!==void 0&&h.expectedBytes>e.maxBytes)throw y("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const u=Vh(e,a,f,i);let g=0;const T=Uh(h.expectedBytes,e.maxBytes);di(t,ci(0,h));const M={...o,onProgress(_){!Number.isSafeInteger(_)||_<g||T!==void 0&&_>T||(g=_,di(t,ci(g,h)))}};s.transition("transfer"),d=!0;let S;try{S=await n.files.writeResource(u.hostHandle,c.body,{mode:u.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...h.expectedBytes===void 0?{}:{expectedBytes:h.expectedBytes}},M)}catch(_){throw s.normalizeHostError(_,"transfer")}s.transition("committed"),g=zh(S,h,g,e.maxBytes),di(t,ci(g,h));const w=i.describeFile(u.handle,u.ref);return s.transition("completed"),w}finally{d||Hh(n.network,c.body)}}function zh(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 Uh(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Hh(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Fh(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return $i(i.handle.mode),await Zh(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return $i(n.handle.mode),await Xh(n.handle,r),{kind:"directory",...n}}function Vh(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=qh(e,r),o=n.deriveFile(t,i);return $i(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Bh(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(!H(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()||!vh.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 Qh(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:Jh(t,Ch)});if((t["content-range"]?.length??0)>0)throw y("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Yh(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(d=>d!=="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=Gh(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 Gh(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 qh(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=Wh(i);if(o&&xr(o))return o}for(const i of r){const o=$h(i);if(o&&xr(o))return o}if(e.suggestedName!==void 0)return So(e.suggestedName);const n=Kh(e.url);return n&&xr(n)?n:"download.bin"}function Wh(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 $h(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 Kh(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function So(e){try{yr(e,"suggestedName")}catch{throw y("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!xr(e))throw y("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function xr(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||kh.test(e))}function Jh(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Zh(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Gc()}catch(r){throw bo(r,"file",t.signal)}}async function Xh(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Gc()}catch(r){throw bo(r,"file",t.signal)}}function $i(e){if(e!=="readwrite")throw y("FILE_ACCESS_DENIED","下载目标只允许读取")}const em={METHOD_FORBIDDEN:"当前 Host 未开放下载能力",DOWNLOAD_HTTP_STATUS:"下载请求返回了失败状态",DOWNLOAD_NETWORK_FAILED:"下载网络请求失败",DOWNLOAD_TIMEOUT:"下载网络请求超时",DOWNLOAD_CANCELLED:"下载已取消",FILE_ACCESS_REVOKED:"下载目标授权已失效",FILE_ACCESS_DENIED:"下载目标不允许写入",FILE_NOT_FOUND:"下载目标文件不存在",DIRECTORY_NOT_FOUND:"下载目标目录不存在",FILE_ALREADY_EXISTS:"下载目标文件已存在",DIRECTORY_ALREADY_EXISTS:"下载目标目录已存在",FILE_TYPE_MISMATCH:"下载目标类型不匹配",FILE_TOO_LARGE:"下载响应超过大小限制",FILE_QUOTA_EXCEEDED:"下载目标配额已用尽",FILE_IO_FAILED:"下载文件写入失败"};function bo(e,t,r){if(r.aborted)return qc();const n=tm(e);if(n&&Ph.has(n)){const o=y(n,em[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?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 tm(e){return H(e)&&typeof e.code=="string"?e.code:void 0}function Gc(){return y("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function qc(){return y("DOWNLOAD_CANCELLED","下载已取消")}function rm(e){if(!e)return;const t=Object.keys(e).find(r=>Rh.has(r.trim().toLowerCase()));if(t)throw y("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const ks={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function nm(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw Ae("network.upload");const o=at(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 d=0,f=!1;const h=u=>{f||o.signal.aborted||!Number.isSafeInteger(u)||u<d||u>c.size||(d=u,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:u,...g}=e,T=await n.upload(a,{...g,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:h});if(f=!0,!Number.isSafeInteger(T.uploadedBytes)||T.uploadedBytes<d||T.uploadedBytes>c.size)throw y("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(T.status>=200&&T.status<300&&T.uploadedBytes!==c.size)throw y("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:T.uploadedBytes,total:c.size,lengthComputable:!0}),T}catch(u){f=!0;const g=To(u);throw g&&ks[g]?y(g,ks[g]):o.signal.aborted?y("UPLOAD_CANCELLED","上传已取消"):g?.startsWith("FILE_")||g?.startsWith("DIRECTORY_")?cr(u):y("UPLOAD_NETWORK_FAILED","上传网络失败")}}const Oo="withCredentials",im=new Set(["url","method","params","data","headers","timeout",Oo]),om=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Oo]),sm=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),xs=3e4,Ki=2*1024*1024,am=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Wc=/[\u0000-\u0008\u000A-\u001F\u007F]/,cm=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,dm="network.request 不支持 multipart/form-data,请使用专用上传能力";function um(e){const t=lm(e.runtimePermissions),r=Tm(e.allowedHttpOrigins);return{[on]:async(n,i)=>{const o=hm(n,{permission:t,allowedHttpOrigins:r}),s=await nm(o,i,e),{uploadedBytes:a,...c}=s;return zs(c)},[nn]:async(n,i)=>{const o=mm(n,{permission:t,allowedHttpOrigins:r});return jh(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[rn]:async(n,i)=>{const o=at(e.operationContext,i?.signal);ee(o.signal);const s=fm(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await W(()=>e.network.request(s,o),o.signal)}catch(c){throw bm(c)?c:Om(c,"REQUEST_UNSUPPORTED")?V("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):V("REQUEST_FAILED","网络请求失败")}return zs(a)}}}function lm(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 fm(e,t){const r=bt(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!im.has(c));if(n.length>0)throw V("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);$c(r,"network.request");const i=_o(r,t,"network.request"),o=pm(r.method),s=r.data;s!==void 0&&Im(s),Mm(i.headers,s);const a=Nm(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 hm(e,t){const r=bt(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(f=>!n.has(f)))throw V("INVALID_PARAMS","network.upload 包含不支持的字段");const i=_o(r,t,"network.upload");if(i.official)throw V("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw V("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!Bn(r.from))throw V("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw V("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw V("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw V("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(f=>r[f]!==void 0))throw V("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(f=>f.toLowerCase()==="content-type"))throw V("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=js(r.fieldName),c=r.fields===void 0?void 0:bt(r.fields,"fields 必须是字符串字典");for(const[f,h]of Object.entries(c??{}))if(js(f),typeof h!="string"||f===a)throw V("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw V("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||Wc.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw V("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:a,fields:c,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>Ki)throw V("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:So(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function js(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw V("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function mm(e,t){const r=bt(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!om.has(c));if(n.length>0)throw V("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);$c(r,"network.download");const i=_o(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw V("INVALID_PARAMS","network.download timeout 必须是有限正数");rm(i.headers);const o=Bn(r.to),s=ic(r.to);if(!o&&!s)throw V("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw V("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw V("INVALID_PARAMS","suggestedName 必须是字符串");a=So(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw V("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw V("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 _o(e,t,r){const n=gm(e.url,t.allowedHttpOrigins,r),i=il(n);if(i&&!t.permission.useOfficialDomain)throw V("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(nl(n.pathname,i))throw V("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...bt(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:ym(e.headers,r),timeout:Em(e.timeout,r)}}function gm(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw V("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw V("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw V("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw V("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw V("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function pm(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw V("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!sm.has(t))throw V("INVALID_PARAMS","network.request method 不合法");return t}function ym(e,t="network.request"){const r=bt(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!am.test(s)||typeof o!="string"||Wc.test(o))throw V("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(ol(s))throw V("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function $c(e,t){const r=e[Oo];if(r!==void 0&&typeof r!="boolean")throw V("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Em(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw V("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>xs)throw V("INVALID_PARAMS",`${t} timeout 不能超过 ${xs}ms`);return e}}function Im(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw V("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(wm(e)>Ki)throw V("INVALID_PARAMS",`network.request data 不能超过 ${Ki} 字节`)}function wm(e){if(typeof e=="string")return ui(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return ui(e.toString());try{const t=JSON.stringify(e);return t?ui(t):0}catch{throw V("INVALID_PARAMS","network.request data 必须可序列化")}}function Mm(e,t){const r=Kc(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 V("INVALID_PARAMS",dm)}function Nm(e,t,r){if(t===void 0)return;const n=Kc(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)||Dm(t))?"form":Am(t)?"json":void 0}function Kc(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function Am(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function Dm(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Tm(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&&Sm(n.hostname)&&t.add(n.origin)}catch{}return t}function Sm(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 zs(e){return Object.keys(e.headers).some(Us)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Us(t)))}:e}function Us(e){const t=e.trim().toLowerCase();return cm.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function bm(e){return e instanceof Error&&e.name==="AbortError"}function Om(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function bt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw V("INVALID_PARAMS",t);return e}function ui(e){return new TextEncoder().encode(e).length}function V(e,t){return{code:e,message:t}}function _m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lm(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 vm(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=Lm(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function Cm(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 Jc(e,t){if(e==null)return{};if(!_m(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=vm(e.topicIds),n=Cm(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 Rm(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function Pm(e){try{if(Rm(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function ae(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()?ae(t):e}function km(e,t){const r=Ji(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?ae(t):r}catch{return ae(t)}}function xm(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Zc(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return ae(`${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 ae(`${t} 缺少有效的小程序分享地址`)}}function jm(e,t){if(!Er(e))return ae("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return ae("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!xm(r))return ae("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:Zc(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:km(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Xc(e,t){if(e!==void 0)try{return Fc(e)}catch{return ae(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function ed(e,t){return e.invalidMessage&&await W(()=>Pm(t.environment),t.operationContext.signal)?ae(e.invalidMessage):e.post}function Hs(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function zm(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Hs(t.windowWidth,0),height:Hs(t.windowHeight,0)}}function Zi(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?ae(t):r}function Fs(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?ae(t):r}function Um(e){return Er(e)?{left:Zi(e.left,"share.screenshot rect.left 必须是非负数字"),top:Zi(e.top,"share.screenshot rect.top 必须是非负数字"),width:Fs(e.width,"share.screenshot rect.width 必须是正数"),height:Fs(e.height,"share.screenshot rect.height 必须是正数")}:ae("share.screenshot rect 必须是对象")}function Hm(e,t){if(e!=null&&!Er(e))return ae("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?ae("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?ae("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?zm(t):Um(r.rect),...r.delay===void 0?{}:{delay:Zi(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function Fm(e,t){ee(t.operationContext.signal);const r=jm(e,t);let n=Jc(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await ed(n,t);return W(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function Vm(e,t){if(ee(t.operationContext.signal),e!==void 0&&!Er(e))return ae("share.copyLink 参数必须是对象");const r=Xc(e?.extra,"share.copyLink"),n=Zc(t,"share.copyLink",r);return await W(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Bm(e,t,r){ee(t.operationContext.signal);const n=Jc(Er(e)?e.post:void 0,{method:"share.screenshot"}),i=await ed(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=Qm(),{watermarkTheme:a,...c}=r;let d=!1,f,h;try{d=!0,await W(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),f=await t.prepareScreenshot?.(r.rect,t.operationContext.signal,a),h={status:"fulfilled",value:await W(()=>t.presentation.captureAndShare({...c,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(g){h={status:"rejected",error:g}}finally{f?.()}const u=d?await Ym(t.presentation,s,t.operationContext.signal):void 0;if(h.status==="rejected")throw h.error;if(u)throw u;return h.value}function Qm(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Ym(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await W(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function Gm(e){let t=Promise.resolve();return{[Jr]:(r,n)=>Vm(r,e),[Zr]:(r,n)=>Fm(r,e),[Xr]:async(r,n)=>{const i=at(e.operationContext,n.signal);ee(i.signal);const o=Hm(r,e.presentation),s=t.then(()=>Bm(r,{...e,operationContext:i},o));return t=s.then(()=>{},()=>{}),W(()=>s,i.signal)}}}const qm=128,Wm=/^[A-Za-z0-9_-]+$/;function $m(e){const t=Km(e);let r=Promise.resolve();const n=new Set,i=(s,a)=>{if(n.has(a))return Promise.resolve();const c=r.then(async()=>{const d=Ru(s),f=Pu(await e.storage.getRaw(d,e.operationContext));if(f.forEach(h=>n.add(h)),!n.has(a)){if(f.length>=Go)throw xe("STORAGE_QUOTA_EXCEEDED",`storage key 数量超出 ${Go} 个上限`);f.push(a),await e.storage.setRaw(d,JSON.stringify(f),e.operationContext),n.add(a)}});return r=c.catch(()=>{}),c},o={[Xt]:async s=>{ee(e.operationContext.signal);const a=Vs(s,Xt,e.storageLimits?.maxKeyLength),c=await W(()=>e.storage.getRaw(li(t(),a),e.operationContext),e.operationContext.signal);return{data:Bs(c)}},[er]:async s=>{ee(e.operationContext.signal);const a=td(s,"storage.setStorage 参数必须是对象"),c=Vs(a,er,e.storageLimits?.maxKeyLength),d=Jm(a.data,e.storageLimits?.maxValueBytes),f=t();await W(()=>i(f,c),e.operationContext.signal),await W(()=>e.storage.setRaw(li(f,c),d,e.operationContext),e.operationContext.signal)}};return e.storageDiagnostics?{handlers:o,diagnostics:{getSnapshot:async()=>{ee(e.operationContext.signal);let s;try{s=t()}catch{throw xe("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const a=li(s,"");return(await W(()=>e.storageDiagnostics.listRaw(e.operationContext),e.operationContext.signal)).filter(d=>d.key.startsWith(a)).map(d=>{const f=d.value;return{area:d.area,key:d.key.slice(a.length),value:Bs(f),serializedValue:f,bytes:rd(f)}}).sort((d,f)=>d.key.localeCompare(f.key))}}}:{handlers:o}}function Km(e){let t=!1,r;return()=>{if(!t){const n=e.identity.get()?.miniProgramId.trim();if(n)r=`id_${Qs(n)}`;else{const i=e.anonymousStorageScope?.trim();i&&(r=`anon_${Qs(i)}`)}t=r!==void 0}if(!r)throw xe("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return r}}function li(e,t){return Cu(e,t)}function Vs(e,t,r=qm){const i=td(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw xe("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!Wm.test(i))throw xe("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function Jm(e,t){let r;try{r=JSON.stringify(e)}catch{throw xe("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw xe("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&rd(r)>t)throw xe("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Bs(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function td(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw xe("INVALID_PARAMS",t);return e}function Qs(e){return vu(e)}function rd(e){return new TextEncoder().encode(e).length}function xe(e,t){return{code:e,message:t}}const Ys=120;function Ve(e){throw{code:"INVALID_PARAMS",message:e}}function Lo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nd(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Ve(`${r} 不支持字段: ${n.join(", ")}`)}function Zm(e){if(!Lo(e))return Ve("ui.showToast 参数必须是对象");if(nd(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>Ys)return Ve(`ui.showToast message 不能超过 ${Ys} 字符`);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 Xm(e){return e===void 0?{dismissible:!1}:Lo(e)?(nd(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Ve("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Ve("ui.showLoading 参数必须是对象")}function eg(e){e!==void 0&&(!Lo(e)||Object.keys(e).length)&&Ve("ui.hideLoading 不支持参数")}function tg(e){return{[gn]:async t=>{ee(e.operationContext.signal),await W(()=>e.presentation.showToast(Zm(t),e.operationContext),e.operationContext.signal)},[pn]:async t=>{ee(e.operationContext.signal),await W(()=>e.presentation.showLoading(Xm(t),e.operationContext),e.operationContext.signal)},[yn]:async t=>{ee(e.operationContext.signal),eg(t),await W(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const rg={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ye(e,"当前用户首页资料接口响应异常")}},ng=3e4;function ig(e,t,r={}){const n=r.ttlMs??ng,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function d(){let h;try{h=await Qn(e,rg,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 pr?y("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof St?y("REQUEST_FAILED","user home_v2 请求失败"):u instanceof Tt?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):sg(u)?u:y("REQUEST_FAILED","user home_v2 请求失败")}return og(h,"user home_v2")}function f(h){const u=Date.now();if(a?.userId===h&&a.expiresAt>u)return Promise.resolve(a.value);if(c?.userId===h&&c.generation===s)return c.promise;const g=s,T=d().then(M=>(s===g&&(a={userId:h,value:M,expiresAt:Date.now()+n}),M)).finally(()=>{c?.promise===T&&(c=void 0)});return c={userId:h,generation:g,promise:T},T}return{get:f,clear(){s+=1,a=void 0,c=void 0}}}function og(e,t){if(!H(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(!H(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function sg(e){return H(e)&&typeof e.code=="string"&&typeof e.message=="string"}const ag={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 cg(e,t=Vi){const r=al({version:"1",validate:ug}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):Vi,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 Gs(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 dg(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 ug(e){if(!H(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 Xe();for(const t of e.gameList){if(!H(t)||!Xi(t.appid)||!Xi(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Xe();for(const r of["image","icon"])qs(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 Xe();if(t.price!==void 0){if(!H(t.price))throw Xe();for(const r of["current","initial","deadlineDate"])qs(t.price,r);for(const r of["discount","lowestPrice","deadlineTimestamp"])fi(t.price,r)}}return e}function Xi(e){return typeof e=="number"&&Number.isFinite(e)}function fi(e,t){if(e[t]!==void 0&&!Xi(e[t]))throw Xe()}function qs(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Xe()}function Xe(){return y("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const id=20,lg=100,fg=128,od=0,sd="weeks",hg=100,mg=new Set(["weeks","all","achieved"]);function gg(){return{nickname:"",avatar:""}}function pg(e){const t=ig(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??hc(),i=cg(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(l,p){const m=JSON.stringify([l,p]);return(!o||o.key!==m)&&(o={key:m,scope:n.createScope(p,n.createScope(l))}),o.scope}function d(){const l=o;o=void 0,l&&n.invalidateScope(l.scope).catch(()=>{}),s.clear()}const f=Dc({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??Nc))}),h=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let u=0,g=!1;const T=e.account.onChange(()=>{u+=1,t.clear(),f.invalidate(),d()}),M=e.authorization.onEvent((l,p)=>{l==="user_info_authorization_change"&&Object.values(p).some(m=>m==="denied")&&(u+=1,t.clear(),f.invalidate(),d(),a=a.then(async()=>{if(g)return;const m=await e.account.getCurrentUserId(e.operationContext);typeof m=="string"&&m.trim()&&await n.invalidateScope(c(w(),m.trim()))}).catch(()=>{}))});function S(){if(g||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function w(){const l=e.identity.get()?.miniProgramId?.trim();if(!l)throw y("INVALID_STATE","用户能力缺少 canonical 小程序身份");return l}async function _(){S(),await a,S();let l;try{l=await e.account.getCurrentUserId(e.operationContext)}catch(p){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):$s(p)?p:y("REQUEST_FAILED","读取小黑盒账号失败")}return typeof l=="string"&&l.trim()?l.trim():void 0}async function A(l,p){const m=await _();if(u!==p||m!==l)throw y("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function v(l,p,m=e.operationContext.signal){try{return await Qn(e.network,l,p,{...e.operationContext,signal:m,credentials:"heybox-session",...h?{gate:h}:{}})}catch(E){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):E instanceof se?y("REQUEST_UNSUPPORTED",E.message):E instanceof pr?y("INVALID_RESPONSE","用户接口响应不合法"):E instanceof St?y("REQUEST_FAILED","用户请求失败"):E instanceof Tt?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):$s(E)?E:y("REQUEST_FAILED","用户请求失败")}}async function U(){w();const l=u,p=await _();if(!p)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[m,E]=await Promise.all([e.authorization.getOrCreateLocalIdentity(p),L(p).catch(()=>gg())]);return await A(p,l),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:m.appUserId,profile:E,...m.steamId?{steam_id:m.steamId}:{}}}}function L(l){return f.read(l,()=>v(Ac,void 0).then(p=>{const m=Ws(p,"账号基础信息");if(m.display_username!==void 0&&typeof m.display_username!="string")throw y("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(m.display_avatar!==void 0&&typeof m.display_avatar!="string")throw y("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:m.display_username??"",avatar:m.display_avatar??""}}))}async function N(l){const p=yg(l),m=w(),E=u,I=await _();if(!I)return d(),{isLogin:!1,isBound:!1,data:null};const D=await t.get(I);await A(I,E);const C=vo(D.steam_id_info);if(Object.keys(C).length===0)return await n.invalidateScope(c(m,I)).catch(()=>{}),await A(I,E),s.delete(JSON.stringify([m,I])),{isLogin:!0,isBound:!1,data:null};const F=JSON.stringify([m,I]),R=c(m,I),O=Gs({...p,steamId:void 0},C),P=ad(C.personal_infomation_open??C.personal_information_open),b=JSON.stringify([O??null,P??null]),x=s.get(F);x&&x.identity!==b&&(await n.invalidateScope(R).catch(()=>{}),await A(I,E));const j={identity:b,scope:n.createScope(b,R)};s.set(F,j);const z=Gs(p,C),B=z?i.persistent:i.unresolved,Q=n.createScope(z??"unresolved",j.scope),G=async()=>{if(await A(I,E),w()!==m||s.get(F)?.identity!==b)throw y("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},te=await B.read({scope:Q,key:dg({miniProgramId:m,userId:I,effectiveSteamId:z,personalInformationOpen:P,query:p}),signal:e.operationContext.signal,load:async X=>{const Z=await v(ag,{userId:I,...p,personalInformationOpen:P},X);return await G(),Ng(Ws(Z,"Steam 游戏库"),p)}}).catch(async X=>{throw await G(),X});return await G(),{isLogin:!0,isBound:!0,data:te}}return{getInfo:U,getSteamGameList:N,async invalidateSteamGameListCache(){const l=w(),p=u,m=await _();if(!m)return;const E=c(l,m);await Promise.all([i.persistent.invalidateScope(E),i.unresolved.invalidateScope(E)]),t.clear(),s.delete(JSON.stringify([l,m])),await A(m,p)},dispose(){g||(g=!0,u+=1,T(),M(),t.clear(),f.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function yg(e){if(e==null)return{limit:id,offset:od,sort:sd,includeHidden:!1};if(!H(e))throw Be("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Be(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Eg(e.limit),offset:Ig(e.offset),sort:wg(e.sort),includeHidden:Mg(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>fg)throw Be("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Be("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,hg))}return r}function Eg(e){if(e===void 0)return id;if(!Number.isInteger(e)||Number(e)<1)throw Be("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),lg)}function Ig(e){if(e===void 0)return od;if(!Number.isInteger(e)||Number(e)<0)throw Be("user.getSteamGameList offset 必须是非负整数");return Number(e)}function wg(e){if(e===void 0)return sd;if(typeof e!="string"||!mg.has(e))throw Be("user.getSteamGameList sort 不支持");return e}function Mg(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Be("user.getSteamGameList includeHidden 必须是 boolean");return e}function Ng(e,t){if(!Array.isArray(e.game_list))throw y("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(Ag).filter(a=>a!==void 0),n=bn(e.total),i=t.offset+r.length,o={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(o.total=n,o.hasMore=i<n);const s=ad(e.is_me);return s!==void 0&&(o.isMe=s),o}function Ag(e){const t=vo(e),r=bn(t.appid),n=bn(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};qt(o,"image",t.image),qt(o,"icon",t.appicon??t.icon),Wt(o,"playtimeForever",t.playtime_forever),Wt(o,"playtime2Weeks",t.playtime_2weeks);const s=Tg(t.external_tags??t.tags);s.length&&(o.tags=s);const a=Dg(t.price);return a&&(o.price=a),o}function Dg(e){const t=vo(e),r={};return qt(r,"current",t.current),qt(r,"initial",t.initial),Wt(r,"discount",t.discount),Wt(r,"lowestPrice",t.lowest_price),qt(r,"deadlineDate",t.deadline_date),Wt(r,"deadlineTimestamp",t.deadline_timestamp),Object.keys(r).length?r:void 0}function Ws(e,t){if(!H(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(!H(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function vo(e){return H(e)?e:{}}function Co(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Tg(e){return Array.isArray(e)?e.map(Co).filter(Boolean):[]}function bn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function ad(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function qt(e,t,r){const n=Co(r);n&&Object.assign(e,{[t]:n})}function Wt(e,t,r){const n=bn(r);n!==void 0&&Object.assign(e,{[t]:n})}function Be(e){return y("INVALID_PARAMS",e)}function $s(e){return H(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Sg(e){return{[Wr]:async t=>(Ks(t,"user.getInfo"),e.user.getInfo()),[$r]:async(t,r)=>{Ks(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Kr]:async t=>e.user.getSteamGameList(t)}}function Ks(e,t){if(e!==void 0)throw y("INVALID_PARAMS",`${t} 不接收入参`)}function Js(e){throw{code:"INVALID_PARAMS",message:e}}function jt(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function cd(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function _r(e,t,r){return Math.min(cd(e,t),r)}async function bg(e){try{return cd(await e.getNavigationBarHeight(),0)}catch{return 0}}function Og(e,t,r,n){const i=_r(e.safeArea?.left,0,t),o=Math.max(i,_r(e.safeArea?.right,t,t)),s=_r(e.safeArea?.top,n,r),a=Math.max(s,_r(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Zs(e){const t=e.getViewportMetrics(),r=jt(t.windowWidth,0),n=jt(t.windowHeight,0),i=await bg(e);return{pixelRatio:jt(t.pixelRatio,1),screenWidth:jt(t.screenWidth,r),screenHeight:jt(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:Og(t,r,n,i),screenTop:i}}function _g(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 h=++i;Zs(r.presentation).then(u=>{if(n||r.operationContext.signal.aborted||h!==i)return;const g=JSON.stringify(u);g!==o&&(o=g,r.onViewportChange?.(u))}).catch(()=>{})},c=_h({...r,onApplied:a}),d=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?d():(s=r.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[ot]:async(h,u)=>c.apply(h,u?.signal),[en]:async()=>(ee(r.operationContext.signal),Zs(r.presentation)),[tn]:async h=>{if(ee(r.operationContext.signal),typeof h!="object"||h===null||Array.isArray(h))return Js("viewport.setNavigationBarStyle 参数必须是对象");const u=h.foregroundStyle;if(u!=="light"&&u!=="dark")return Js("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await W(()=>r.presentation.setNavigationBarStyle(u,e.operationContext),r.operationContext.signal)}},applyOrientation:(h,u)=>c.apply({orientation:h.mode,fullscreen:h.hideCapsule},u),notifyChange:()=>{o=void 0,a()},dispose:d}}const Lg=new Map(Ye.map(e=>[e.method,e]));function Vt(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function vg(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 Cg(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=f=>{a||(a=!0,n.removeEventListener("abort",d),f())},d=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",d,{once:!0}),i.then(f=>c(()=>o({status:"handled",value:f})),f=>c(()=>s(f)))})}function Rg(e){const t=vg(e.runtimePermissions),r=Je(e.runtimePermissions);let n=0,i=0,o=0;return{async dispatch(s,a,c){const d=e.now??Pg,f=e.onTrace?d():0,h=e.onTrace?`cap_${++n}`:"",u=s===ot?++i:void 0;let g;try{if(e.terminalSignal.aborted)throw Vt("RUNTIME_DESTROYED","小程序 Runtime 已终止");xu(s,e.effectiveCapabilities);const T=Lg.get(s);if(!T)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const M=t(T),S=!M.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!M.allowed&&!S)throw Vt(M.code,M.message,M.data);const w=e.handlers[s];if(!w)throw new Error(`Capability method ${s} 缺少 handler`);u!==void 0&&(g=Bc(c.signal));const _=g?{...c,signal:g.signal}:c,A=async()=>{for(const U of e.policies??[]){const L=await U.evaluate({method:s,payload:a,capability:T});if(e.terminalSignal.aborted||g?.signal.aborted)throw ta();if(!L.allowed)throw Vt(L.code,L.message,L.data)}if(e.terminalSignal.aborted||g?.signal.aborted)throw ta();if(u!==void 0){if(Qc(a),u<o)throw Vt("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=u}return w(a,_)},v=await Cg(()=>g?g.run(A):A(),void 0,c,e.terminalSignal);return Xs(e.onTrace,ea(h,s,a,f,v),d),v}catch(T){throw Xs(e.onTrace,ea(h,s,a,f,{status:"error",error:T}),d),T}finally{g?.dispose()}}}}function Pg(){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 ea(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:kg(i.error)}:{},...xg(t,r,i)}}function kg(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function xg(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"&&dd(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 dd(e){return typeof e=="object"&&e!==null}function ta(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function jg(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=Nl(e.requestPolicy);let n;if(e.files)try{n=fl(e.files,t)}catch{}const i=hc({store:n}),o=e.onRequestPolicyReport??(r.debugReport?zg:void 0),s=r.enabled?El({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Yf(e.files,e.miniProgramDetail),c=Xf({registry:a,picker:e.picker,operationContext:t}),d=ql({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 f,h,u,g=()=>{},T=()=>{};try{f=_g({operationContext:t,presentation:e.hostPresentation,onDisplayChange:L=>e.eventSink.postEvent("display_change",L),onViewportChange:L=>e.eventSink.postEvent("viewport_change",L)}),h=pg({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:d,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:s,requestPolicyEnabled:r.enabled}),g=d.onEvent((L,N)=>e.eventSink.postEvent(L,N)),T=e.hostCompanion?.onSessionEvent?.(L=>{const N=zf(L);!e.terminalSignal.aborted&&N&&e.eventSink.postEvent(N.type,N.payload)})??(()=>{}),u=Af({account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const M=$m({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),S=[{name:"auth",handlers:rf({authorization:d})},{name:"user",handlers:Sg({user:h,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:Gm({prepareScreenshot:e.prepareScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:f.handlers},{name:"storage",handlers:M.handlers},{name:"network",handlers:um({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[Gr]:async()=>{throw Vt("CAPABILITY_UNAVAILABLE","当前 Runtime 不支持工作区卡片刷新")}}},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"ui",handlers:tg({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Vf({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:Lh({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:L=>f.applyOrientation({mode:"portrait",hideCapsule:!1},L)}:{}})},{name:"cloud",handlers:u.handlers},{name:"companion",handlers:Rf({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],w=Ug(S);let _=!1;const A=()=>{_||(_=!0,e.terminalSignal.removeEventListener("abort",A),f?.dispose(),u?.dispose(),g(),T(),h?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?A():e.terminalSignal.addEventListener("abort",A,{once:!0});const v=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:S,handlers:w,allowsCompanionAttachmentAccess:(L,N)=>v.has(L)&&dd(N)&&a.isCompanionAttachmentRef(N.target),applyOrientation:f.applyOrientation,notifyViewportChange:f.notifyChange,...M.diagnostics?{storageDiagnostics:M.diagnostics}:{},dispose:A}}catch(M){throw f?.dispose(),u?.dispose(),g(),T(),h?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),M}}function zg(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Ug(e){const t=new Map(Ye.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[o,s]of Object.entries(i.handlers)){const a=o,c=t.get(a);if(!c)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${a}`);if(c!==i.name)throw new Error(`Capability method ${a} 应由 ${c} 拥有,不能注册到 ${i.name}`);if(r.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);r.set(a,s)}const n=Ye.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Ye.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Hg="heybox-mini-dev:";function ra(e){try{return Fg(new URL(e))}catch{return!1}}function Fg(e){return e.protocol===Hg}function Vg(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Bg(e)}function Bg(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 Qg=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Yg(e,t){const r=[],n=Gg(e.environmentInfo,r),i=jr(n?.appVersion,"host.appVersion",r),o=Wg(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:qg(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:jr(t.miniProgramId),version:jr(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function Gg(e,t){if(e!=null){if(ud(e))return e;t.push("environmentInfo")}}function qg(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function Wg(e,t){if(e==null)return{name:"unknown",version:null};if(!ud(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=Qg.has(e.name)?e.name:"unknown";return r==="unknown"&&e.name!==void 0&&e.name!==null&&e.name!=="unknown"&&t.push("operatingSystem.name"),{name:r,version:jr(e.version,"operatingSystem.version",t)}}function jr(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function ud(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const $g="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",Kg="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",Jg="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",Zg="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function Xg(e,t,r,n,i="dark"){ee(n);const o=e.defaultView;if(!o||!e.body)throw new Error("截图水印缺少可用的展示窗口");const s=e.createElement("div"),a=i==="light",c=a?"black":"white";s.dataset.miniProgramScreenshotWatermark="",s.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);s.style.cssText=`position:fixed;left:${r.left}px;top:${r.top+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const f=e.createElement("div");f.style.cssText=`display:flex;flex-direction:column;align-items:center;width:${r.width/d}px;height:57px;transform:scale(${d});transform-origin:top left;font-family:"PingFang SC",sans-serif;`;const h=e.createElement("div");h.style.cssText="display:flex;align-items:center;max-width:calc(100% - 24px);height:22px;flex-shrink:0;";const u=e.createElement("img");u.src=a?Jg:$g,u.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const g=e.createElement("div");g.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${c};border-radius:11px;padding:0 7px 0 6px;`;const T=e.createElement("img");T.src=a?Zg:Kg,T.style.cssText="width:12px;height:12px;flex-shrink:0;";const M=e.createElement("span");M.textContent=t?.trim()||"小程序工坊",M.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const S=e.createElement("div");S.textContent="小黑盒工坊小程序",S.style.cssText=`margin-top:6px;color:${a?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,g.append(T,M),h.append(u,g),f.append(h,S),s.append(f),e.body.append(s);const w=()=>{s.remove(),n.removeEventListener("abort",w)};n.addEventListener("abort",w,{once:!0});try{return await W(()=>Promise.all([u.decode(),T.decode()]),n),await W(()=>new Promise(_=>{let A=o.requestAnimationFrame(()=>{A=o.requestAnimationFrame(()=>{n.removeEventListener("abort",v),_()})});const v=()=>o.cancelAnimationFrame(A);n.addEventListener("abort",v,{once:!0})}),n),w}catch(_){throw w(),_}}const ep=1,ld="allow-scripts allow-same-origin",tp="",rp="no-referrer";function np(e=ld){return!e.split(/\s+/).includes("allow-same-origin")}function na(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const ip=new Set(["javascript:","data:","blob:","file:"]),ia="xiaoheihe.cn";function op(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(ip.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!up(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function sp(e,t){const r=new URL(e);return r.searchParams.set(au,t),r.toString()}function ap(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=cp(r)??dp(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function cp(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function dp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function oa(e){const t=new URL(e);return Ro(t)?"loopback":Po(t)?"lan":"production"}function up(e,t,r){return lp(e)||Ro(e)||Po(e)&&hp(t,r)}function lp(e){return e.protocol==="https:"&&pp(e.hostname)}function Ro(e){return e.protocol==="http:"&&fp(e.hostname)}function fp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Po(e){return e.protocol==="http:"&&mp(e.hostname)}function hp(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Ro(r)||Po(r)}catch{return!1}}function mp(e){const t=gp(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function gp(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 pp(e){return e===ia||e.endsWith(`.${ia}`)}const yp=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"]),Ep=new Set(["url","inline","eval","unknown"]),Ip=/^\/(?:\:segment(?:\/\:segment)*)?$/,wp=/^[a-f0-9]{64}$/,Mp=255,Np=160,Ap=256;function Dp(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!yp.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>Ap||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Ep.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=Tp(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>Np||!Ip.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!wp.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 Tp(e){if(e!==void 0&&!(typeof e!="string"||e.length>Mp))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Sp=/^(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 bp(e){if(!e?.minimumSdkVersion)throw $("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=tt(e.minimumSdkVersion),r=e.sdkVersion?tt(e.sdkVersion):void 0;if(!t)throw $("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw $("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=tt("0.6.0");if(!r){if(zr(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw $("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0)throw $("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(zr(r,t)<0)throw $("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:zr(r,tt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Op(e,t){if(typeof t!="string"||!tt(t))throw $("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw $("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function _p(e,t){const r=tt(e),n=tt(t);if(!(!r||!n))return zr(r,n)}function tt(e){const t=Sp.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(r=>/^\d+$/.test(r)?Number(r):r)??[]}}function zr(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],o=t.prerelease[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const Gn=["android","ios","ohos","windows","macos","linux"],Lp="0.9.0",vp=Object.freeze(["android","ios","ohos","windows","macos"]),fd="该小程序暂不支持当前平台",Cp="PLATFORM_UNSUPPORTED";function Rp(e){return typeof e=="string"&&Gn.includes(e)}function Pp(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 kp(e){const t=e.manifest;if(!Hp(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=aa(e.sdkVersion)??aa(t.sdkVersion);return zp(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:jp()}const r=hd(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function xp(e){const t=Pp(e.operatingSystemName);if(!t)return It("host_operating_system_unknown");const r=e.platformAccess;if(!r)return It("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Gn,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=kp({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?It("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):sa(t,s)}if(r.effectivePlatforms===void 0)return It("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=hd(r.effectivePlatforms);if("reason"in n)return It("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=Up(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return sa(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function sa(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:It("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function It(e,t={}){return{status:"denied",reason:e,message:fd,...t}}function jp(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:vp,platformsDeclared:!1,policy:"legacy_mobile_default"}}function hd(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(!Rp(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Gn.filter(r=>t.has(r)))}}function zp(e){if(typeof e!="string"||!e.trim())return!1;const t=_p(e.trim(),Lp);return t!==void 0&&t>=0}function aa(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Up(e){return e==="explicit"||e==="legacy_mobile_default"}function Hp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Fp=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 Vp(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:Bp(i.pathname),sanitizedPathnameHash:Qp(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function Bp(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function Qp(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 S=0;S<16;S+=1)o[S]=s.getUint32(a+S*4,!1);for(let S=16;S<64;S+=1){const w=o[S-15],_=o[S-2],A=be(w,7)^be(w,18)^w>>>3,v=be(_,17)^be(_,19)^_>>>10;o[S]=o[S-16]+A+o[S-7]+v>>>0}let[c,d,f,h,u,g,T,M]=i;for(let S=0;S<64;S+=1){const w=M+(be(u,6)^be(u,11)^be(u,25))+(u&g^~u&T)+Fp[S]+o[S]>>>0,_=(be(c,2)^be(c,13)^be(c,22))+(c&d^c&f^d&f);M=T,T=g,g=u,u=h+w>>>0,h=f,f=d,d=c,c=w+_>>>0}[c,d,f,h,u,g,T,M].forEach((S,w)=>{i[w]=i[w]+S>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function be(e,t){return e>>>t|e<<32-t}const Yp=1e4,hi=2e3,Gp=2,qp="open-with-native-credential-policy",md="安全提示",gd="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class Wp{nonce=na();runtimeId=na();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=fc(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??Yp,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??$("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??$("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(ny(),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=$("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=bp(t.sdkVersionPolicy);const r=Yg(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=xp({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw sy(this.platformGateDecision);if(this.miniProgramDetail=ay(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),Zp(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(ey(n)),this.launchUrl=n,this.miniProgramSrc=sp(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=Io(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,ze(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&(n!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(n!=="display_change"||this.effectiveCapabilities[ot])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=jg({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,prepareScreenshot:(n,i,o)=>Xg(this.iframe.ownerDocument,this.miniProgramPresentation?.name,n,i,o),miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins,requestPolicy:this.options.requestPolicy,...this.options.onRequestPolicyReport?{onRequestPolicyReport:this.options.onRequestPolicyReport}:{}});const r=Rg({handlers:this.capabilityGraph.handlers,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:f})=>{const h={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...f?{network:f}:{}};ze(this.options.onCapabilityTrace,h)}}:{}});this.bridgeServer=new Ou({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($("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 Jp(t)?t:pd($("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 op(t,r,{allowPrivateNetwork:ra(r)||ca(r)||await this.isDevRuntime()})}catch(r){throw $("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??ry)({message:gd,title:md,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(oa(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!ra(r)&&!ca(r)}async closeAfterDevLaunchCancellation(){const t=$("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{da(),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(()=>da())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",tp),this.iframe.setAttribute("referrerpolicy",rp),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(),ze(this.options.onReady,t)}completeCompatibilityLaunch(){if(this.stateValue!=="starting"||this.isInactive()||this.readyContext)return;this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:"bridge_ready"}),this.setState("ready"),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),ze(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Op(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($("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>=Gp)){this.failRuntime($("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Mr,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:Mr})}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(Mr,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Mr})}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($("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===du){this.handleCspViolation(t.payload);return}if(t.method!==cu)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime($("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!ap(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime($("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=Dp(t,this.sdkVersionDecision?.sdkVersion);r&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:r.timestamp,sdkVersion:r.sdkVersion,origin:r.origin,sanitizedPathname:r.sanitizedPathname,sanitizedPathnameHash:r.sanitizedPathnameHash,effectiveDirective:r.effectiveDirective,violatedDirective:r.violatedDirective,blockedResourceType:r.blockedResourceType})}emitSecurityViolation(t){ze(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=Vp(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($("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:ep,launchUrlType:oa(t),networkPolicy:qp})}failRuntime(t){const r=$p(t);return this.isInactive()||(this.terminalError=r,this.terminalController.abort(r),this.postBridgeError(r),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),this.setState("failed"),this.teardownIframe(r),ze(this.options.onError,Kp(r)),this.rejectReady?.(r)),r}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0,this.clearHandshakeTimeout(),this.clearHeartbeat(),this.clearUnexpectedDocumentLoadFailure(),this.clearDocumentRevalidation(),this.destroyBridgeServer(),this.capabilityGraph?.dispose(),this.capabilityGraph=void 0,this.clearLifecycleDisposer(),this.removeIframeListeners();try{this.options.dispose?.()}catch{}}}teardownIframe(t){if(!this.iframeTornDown){this.iframeTornDown=!0;try{this.options.teardownIframe?this.options.teardownIframe(this.iframe,t):this.iframe.remove()}catch{}}}setStatus(t){this.status!==t&&(this.status=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:t}))}setState(t){this.stateValue!==t&&(this.stateValue=t,ze(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){ze(this.options.onTrace,{...t,runtimeId:this.runtimeId,...this.identity})}createLaunchContext(){return{launchUrl:this.launchUrl,src:this.miniProgramSrc,sdkVersion:this.sdkVersionDecision?.sdkVersion,heartbeatEnabled:!!this.sdkVersionDecision?.heartbeatEnabled,...this.identity}}createReadyContext(){return this.readyContext??this.createLaunchContext()}}function $p(e){const t=Io(e);return On(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 Kp(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function Jp(e){return On(e)&&typeof e.code=="string"&&typeof e.message=="string"}function On(e){return!!e&&typeof e=="object"}function ze(e,t){try{e?.(t)}catch{}}function Zp(e,t,r){try{e?.(t,r)}catch{}}function ca(e){try{const t=new URL(e);return t.protocol==="http:"&&Vg(t.hostname)}catch{return!1}}function Xp(e){try{return new URL(e).origin}catch{return}}function ey(e){return np()?"*":Xp(e)}function ty(e){return`${md}
1
+ import{H as Yo,ax as Qd,aY as Yd,M as Gd,aH as qd,aI as Wd,aj as mr,b6 as Y,aa as $d,ak as Ka,aq as Kd,b0 as Jd,am as Zd,d as Xd,aE as Ja,a8 as eu,at as Za,r as tu,az as Xa,o as ru,aD as nu,a5 as iu,a_ as ou,aZ as su,c as au}from"./desktop-app-launch-F0wNWGvm.js";const Gr="workspaceCards.requestRefresh",qr="auth.login",Wr="user.getInfo",$r="user.revokeAuthorization",Kr="user.getSteamGameList",Jr="share.copyLink",Zr="share.showShareMenu",Xr="share.screenshot",ot="viewport.setDisplay",en="viewport.getWindowInfo",tn="viewport.setNavigationBarStyle",Xt="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",un="file.writeText",ir="file.readBytes",ln="file.writeBytes",or="file.stat",fn="directory.create",sr="directory.remove",hn="directory.exists",mn="directory.list",gn="ui.showToast",pn="ui.showLoading",yn="ui.hideLoading",En="device.vibrate",In="device.setClipboard",wn="device.executeProtocol",Mn="navigation.close",Nn="navigation.reload",An="navigation.openAppPage",ke="cloud.leaderboard.submit",Ne="cloud.leaderboard.getList",Qe="cloud.leaderboard.getCurrentUserEntry",st="cloud.leaderboard.deleteCurrentUserEntry",Le="cloud.leaderboard.getInfo",vn="companion.getInfo",Cn="companion.getPreparationStatus",Rn="companion.prepare",Pn="companion.cancelPreparation",kn="companion.getActiveSession",xn="companion.launch",jn="companion.session.write",zn="companion.session.closeStdin",Un="companion.session.terminate",Hn="companion.session.ackOutput",Fn="companion.openAttachment",Vn="companion.showNotification",Ye=[{method:Gr,module:"workspaceCards",capability:Gr,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:qr,module:"auth",capability:qr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Wr,module:"user",capability:Wr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:$r,module:"user",capability:$r,requirement:{kind:"none"},risk:"high"},{method:Kr,module:"user",capability:Kr,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:Jr,module:"share",capability:Jr,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Zr,module:"share",capability:Zr,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Xr,module:"share",capability:Xr,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:Xt,module:"storage",capability:Xt,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:un,module:"file",capability:un,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ir,module:"file",capability:ir,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ln,module:"file",capability:ln,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:gn,module:"ui",capability:gn,requirement:{kind:"none"},risk:"low"},{method:pn,module:"ui",capability:pn,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:In,module:"device",capability:In,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:wn,module:"device",capability:wn,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:Mn,module:"navigation",capability:Mn,requirement:{kind:"none"},risk:"medium"},{method:Nn,module:"navigation",capability:Nn,requirement:{kind:"none"},risk:"medium"},{method:An,module:"navigation",capability:An,requirement:{kind:"none"},risk:"medium"},{method:ke,module:"cloud",capability:ke,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ne,module:"cloud",capability:Ne,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Qe,module:"cloud",capability:Qe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:st,module:"cloud",capability:st,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Le,module:"cloud",capability:Le,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},...[vn,Cn,Rn,Pn,kn,xn,jn,zn,Un,Hn,Fn,Vn].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],Ze="heybox:miniprogram",ec=2,cu="hb_mini_bridge_nonce",tc="sdk.handshake",Mr="runtime.location.probe",du="sdk.location.report",uu="sdk.csp.violation",rc="operation.progress",lu="companion.session.output",fu="companion.session.exit",hu="companion.session.ownershipLost";function mu(e){return!Ke(e)||e.namespace!==Ze||e.version!==1&&e.version!==2||!de(e.nonce)?!1:e.type==="handshake"?de(e.id)&&e.method===tc&&e.error===void 0&&Eu(e.payload):e.type==="request"?de(e.id)&&de(e.method)&&e.error===void 0:e.type==="response"?de(e.id)&&(e.method===void 0||de(e.method))&&(e.error===void 0||Iu(e.error)):e.type==="event"?!de(e.method)||e.error!==void 0?!1:e.method===rc?e.version===2&&de(e.id)&&yu(e.payload):e.id===void 0||de(e.id):e.type==="cancel"?e.version===2&&de(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 nc(e){return Ke(e)?e.kind==="sandbox"?je(e,["kind"]):e.kind==="directory"&&de(e.handleId)&&je(e,["kind","handleId"]):!1}function Bn(e){return!Ke(e)||e.kind!=="file"?!1:de(e.handleId)?je(e,["kind","handleId"]):nc(e.root)&&yo(e.relativePath)&&je(e,["kind","root","relativePath"])}function ic(e){return!Ke(e)||e.kind!=="directory"?!1:de(e.handleId)?je(e,["kind","handleId"]):nc(e.root)&&(e.relativePath==="."||yo(e.relativePath))&&je(e,["kind","root","relativePath"])}function oc(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function gu(e){return!Ke(e)||!Mt(e.loaded)||typeof e.lengthComputable!="boolean"||!je(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Mt(e.total)&&e.loaded<=e.total:e.total===void 0}function pu(e){return Ke(e)?e.phase==="downloading"?Mt(e.loaded)&&(e.total===void 0||Mt(e.total)&&e.loaded<=e.total)&&je(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Mt(e.processed)&&Mt(e.total)&&e.processed<=e.total&&je(e,["phase","processed","total"]):!1}function yu(e){return gu(e)||pu(e)}function Eu(e){return Ke(e)&&de(e.href)&&typeof e.userAgent=="string"&&de(e.sdkVersion)}function Iu(e){return Ke(e)&&de(e.code)&&typeof e.message=="string"}function Mt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function de(e){return typeof e=="string"&&e.length>0}function je(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Ke(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 wu=new Set(ar);function Mu(e){return wu.has(e)}function Je(e){if(!Nr(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(!Nr(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),!!Mu(o)){if(o==="network"){const s=n.config;if(!Nr(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&&(!Nr(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 Nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Rr=["network","companion","appProtocol"];function sc(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>Rr.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)=>Rr.indexOf(n.key)-Rr.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Nu(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 Rr)!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=sc(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=ac(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 ac(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ct(e,t){return ac(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Dt=["identity","profile","steam_account"],Au=/^[a-z][a-z0-9-]{0,31}$/,cc=["COMPANION_UNSUPPORTED","COMPANION_PREVIEW_UNSUPPORTED","COMPANION_NOT_DECLARED","COMPANION_TARGET_UNSUPPORTED","COMPANION_NOT_PREPARED","COMPANION_PREPARATION_CANCELLED","COMPANION_DOWNLOAD_FAILED","COMPANION_DESCRIPTOR_UNAVAILABLE","COMPANION_ARCHIVE_INVALID","COMPANION_INTEGRITY_FAILED","COMPANION_ENTRYPOINT_INVALID","COMPANION_USER_CANCELLED","COMPANION_ELEVATION_DENIED","COMPANION_OS_BLOCKED","COMPANION_LAUNCH_FAILED","COMPANION_SESSION_VERSION_MISMATCH","COMPANION_SESSION_OWNERSHIP_LOST","COMPANION_SESSION_EXITED","COMPANION_PIPE_CLOSED","COMPANION_OUTPUT_LIMIT","COMPANION_PROCESS_CRASHED","COMPANION_ATTACHMENT_NOT_FOUND","COMPANION_NOTIFICATION_UNAVAILABLE","COMPANION_TERMINATE_FAILED"];Ye.map(e=>e.method);function $(e,t,r){return{code:e,message:t,data:r}}function Io(e){return Du(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?$("RUNTIME_ERROR",e.message):$("UNKNOWN_ERROR","小程序运行时异常",e)}function Du(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function Tu(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Su=1e3;function bu(e,t=Tu()){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<=Su}const Ou="runtime.gate.probe",dc=new Set(Ye.map(e=>e.method));class _u{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=ec;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:Ze,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:Ze,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Ze,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Ze,version:2,nonce:this.nonce,type:"event",id:t,method:rc,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=bu(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&&mu(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:Ze,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:tc,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===Ou){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,$("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!dc.has(t.method)){this.postResponse(t,void 0,$("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,$("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=Io(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:Ze,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!Lu(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 Lu(e){return typeof e=="string"&&dc.has(e)}const uc="METHOD_FORBIDDEN";function Ae(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=uc,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 vu=/^[A-Za-z0-9_-]{1,64}$/,Go=1e3;function Cu(e){return vu.test(e)?e:xu(e)}function Ru(e,t){return`hb_miniprogram_${e}_${t}`}function Pu(e){return`hb_miniprogram_keys_${e}`}function ku(e){if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}function xu(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}const qo={[Gr]:["workspaceCards.requestRefresh"],[qr]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Wr]:["account.getCurrentUserId","account.onChange","network.request"],[$r]:["account.getCurrentUserId","account.onChange","network.request"],[Kr]:["account.getCurrentUserId","account.onChange","network.request"],[Jr]:["presentation.setClipboard"],[Zr]:["presentation.showShareMenu"],[Xr]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ot]:["presentation.applyOrientation"],[en]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[tn]:["presentation.setNavigationBarStyle"],[Xt]:["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"],[un]:["files.access"],[ir]:["files.access"],[ln]:["files.access"],[or]:["files.access"],[fn]:["files.access"],[sr]:["files.removeDirectory"],[hn]:["files.access"],[mn]:["files.access"],[gn]:["presentation.showToast"],[pn]:["presentation.showLoading"],[yn]:["presentation.hideLoading"],[En]:["presentation.vibrate"],[In]:["presentation.setClipboard"],[wn]:["protocol.invoke"],[Mn]:["presentation.close"],[Nn]:["presentation.reload"],[An]:["presentation.openAppPage"],[ke]:["account.getCurrentUserId","account.onChange","network.request"],[Ne]:["account.onChange","network.request"],[Qe]:["account.getCurrentUserId","account.onChange","network.request"],[st]:["account.getCurrentUserId","account.onChange","network.request"],[Le]:["account.onChange","network.request"],[vn]:["companion.getInfo"],[Cn]:["companion.getPreparationStatus"],[Rn]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[Pn]:["companion.cancelPreparation"],[kn]:["companion.getActiveSession"],[xn]:["companion.getInfo","companion.launch"],[jn]:["companion.session.write"],[zn]:["companion.session.closeStdin"],[Un]:["companion.session.terminate"],[Hn]:["companion.session.ackOutput"],[Fn]:["companion.openAttachment"],[Vn]:["companion.showNotification"]};function ju(e,t){if(t[e]!==!0)throw Ae(e)}const zu=32*1024*1024,Uu=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Hu(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:zu},i);return Fu(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Fu(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:Vu(t,Qu(e,"content-type"))}}function Vu(e,t){Bu(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||!Uu.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function Bu(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 Qu(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 Ae(e)}}function re(e){return async(...t)=>{throw Ae(e)}}const Yu=(e,t)=>{},Gu=()=>()=>{};function qu(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):Gu},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):Yu,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 Wu(e){const t=$u(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 $u(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 $o(e,t){return t?.[e]!==!1}function Ku(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(qo)){const o=qo[n].every(a=>e[a]),s=!Ku(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=$o(n,t.callerCapabilities)&&$o(n,t.hostCapabilities)&&o&&s}return r}function fc(e={},t={}){const r=Wu(e),n=lc(r,t);return{ports:qu(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function at(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):Ju(e.signal,t);return{...e,signal:r}}function Ju(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 Zu(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 Xu=4,el=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],tl=new Set(["connection","content-length","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade"]),rl=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],nl=["/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 il(e,t){const r=al(e);return r===null||Ko(r,rl)?!0:t&&Ko(r,nl)}function ol(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return el.some(r=>t===r||t.endsWith(`.${r}`))}function sl(e){const t=e.trim().toLowerCase();return tl.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function al(e){let t=e;for(let r=0;r<Xu;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Jo(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Jo(t)}function Ko(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Jo(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 Zo(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function hc(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,o=new Map,s=new Set,a=new Set;let c=!1;function d(M,S){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:M,type:S})).catch(()=>{})}catch{}}function f(M){const S=r.get(M);if(!S)throw new Error("Unknown runtime cache scope");return S}function h(M,S){return M.flatMap((w,_)=>{const A=JSON.stringify(M.slice(0,_+1));return[JSON.stringify([A]),JSON.stringify([A,S])]})}function u(M,S){return JSON.stringify(h(M,S).map(w=>n.get(w)??0))}async function g(M,S){const w=f(M),_=JSON.stringify([JSON.stringify(w),...S?[S]:[]]),A=(n.get(_)??0)+1;n.set(_,A),i.add(_);for(const v of a)v(w,S);if(!e.store){i.delete(_),d(S??"*","invalidation");return}try{await e.store.invalidate(w,S)}catch(v){throw d(S??"*","storage_error"),v}n.get(_)===A&&i.delete(_),d(S??"*","invalidation")}function T(M){if(c)throw new Error("Runtime cache manager disposed");const S=o.get(M.namespace);if(S){if(S.sourceCodec!==M.codec||S.definition.codec.version!==M.codec.version||JSON.stringify(S.definition.policy)!==JSON.stringify(M.policy))throw new Error("Conflicting runtime cache namespace");return S.cache}if(!M.namespace||!M.codec.version)throw new Error("Invalid runtime cache definition");const w=Object.freeze({...M.policy}),_=Object.freeze({version:M.codec.version,encode:M.codec.encode.bind(M.codec),decode:M.codec.decode.bind(M.codec),validate:M.codec.validate.bind(M.codec),clone:M.codec.clone.bind(M.codec)}),A=M.namespace;for(const O of[w.ttlMs,w.memoryMaxEntries,w.diskMaxEntries,w.diskMaxBytes,w.maxEntryBytes])if(!Number.isFinite(O)||O<0)throw new Error("Invalid runtime cache policy");const v=new Map,U=new Map,L=new Map;let N=!1;function l(O,P,b){if(c||N||O.aborted||u(P,A)!==b)throw lt()}function p(O){return w.ttlMs>0&&w.persistence==="memory-and-disk"&&!!e.store&&!h(O,A).some(P=>i.has(P))}function m(O,P,b){const x=t();return O.envelopeVersion===1&&JSON.stringify(O.address)===JSON.stringify(P)&&Zo(O.revisions,b)&&O.payload.byteLength<=w.maxEntryBytes&&Number.isFinite(O.cachedAt)&&Number.isFinite(O.expiresAt)&&O.cachedAt<=x&&O.cachedAt>=0&&O.expiresAt>O.cachedAt&&Math.min(O.expiresAt,O.cachedAt+w.ttlMs)>x}function E(O,P,b,x,j){if(!(w.ttlMs<=0||w.memoryMaxEntries<1)){for(const[z,B]of v)Math.min(B.entry.expiresAt,B.entry.cachedAt+w.ttlMs)<=t()&&v.delete(z);for(v.delete(O);v.size>=Math.floor(w.memoryMaxEntries);){const z=v.keys().next();if(z.done)break;v.delete(z.value)}v.set(O,{entry:P,value:b,epoch:x,persistent:j})}}async function I(O,P,b,x){const j={namespace:A,codecVersion:_.version,scopeIds:P,key:O.key},z=JSON.stringify(j);let B=[],Q=p(P);if(Q)try{B=await e.store.readRevisions(P,A)}catch{Q=!1,d(A,"storage_error")}l(x.signal,P,b);async function G(){if(!Q)return!0;try{return Zo(B,await e.store.readRevisions(P,A))}catch{return Q=!1,d(A,"storage_error"),!1}}const te=v.get(z);if(w.ttlMs>0&&te&&te.epoch===b&&m(te.entry,j,B)&&te.persistent===Q&&await G())return l(x.signal,P,b),d(A,"memory_hit"),te.value;if(v.delete(z),Q){let q,he;try{q=await e.store.read(j,w.maxEntryBytes),q&&m(q,j,B)?he=_.decode(q.payload):q=void 0}catch{q=void 0,d(A,"storage_error")}if(l(x.signal,P,b),q&&await G())return l(x.signal,P,b),E(z,q,he,b,!0),d(A,"disk_hit"),he}d(A,"miss");const X=_.validate(await O.load(x.signal));l(x.signal,P,b);const Z=_.clone(X);if(!await G()&&Q)throw lt();if(l(x.signal,P,b),w.ttlMs>0){const q=t();let he;try{he=_.encode(Z)}catch{return Z}const Bo={envelopeVersion:1,address:j,revisions:Q?B:[],cachedAt:q,expiresAt:q+w.ttlMs,payload:he};if(Q&&he.byteLength<=w.maxEntryBytes){let ei=!0,Qo=!1;try{ei=await e.store.publish(Bo,w),Qo=ei}catch{d(A,"storage_error")}if(l(x.signal,P,b),!ei)throw lt();Qo&&d(A,"published")}l(x.signal,P,b),E(z,Bo,Z,b,Q)}return Z}async function D(O){if(c||N||O.signal?.aborted)return Promise.reject(lt());const P=f(O.scope),b=u(P,A);let x;if(p(P)){const Q=new AbortController;L.set(Q,P);const G=()=>Q.abort();O.signal?.addEventListener("abort",G,{once:!0});let te=()=>{};try{x=await Promise.race([e.store.readRevisions(P,A),new Promise((X,Z)=>{const q=()=>Z(lt());Q.signal.addEventListener("abort",q,{once:!0}),te=()=>Q.signal.removeEventListener("abort",q)})])}catch{Q.signal.aborted||d(A,"storage_error")}finally{te(),L.delete(Q),O.signal?.removeEventListener("abort",G)}}l(O.signal??new AbortController().signal,P,b);const j=JSON.stringify([P,O.key,b,x]);let z=U.get(j);if(z?.controller.signal.aborted&&(z=void 0),!z){const Q=new AbortController;z={ids:P,controller:Q,waiters:0,promise:Promise.resolve(void 0)};const G=z;G.promise=I(O,P,b,Q).finally(()=>{U.get(j)===G&&U.delete(j)}),U.set(j,G)}const B=z;return B.waiters+=1,new Promise((Q,G)=>{let te=!1;function X(q){te||(te=!0,O.signal?.removeEventListener("abort",Z),B.controller.signal.removeEventListener("abort",Z),B.waiters-=1,B.waiters===0&&B.controller.abort(),q())}function Z(){X(()=>G(lt()))}O.signal?.addEventListener("abort",Z,{once:!0}),B.controller.signal.addEventListener("abort",Z,{once:!0}),B.promise.then(q=>X(()=>{try{l(O.signal??new AbortController().signal,P,b),Q(_.clone(q))}catch(he){G(he)}}),q=>X(()=>G(q)))})}function C(O,P){if(P&&P!==A)return;const b=x=>O.every((j,z)=>x[z]===j);for(const[x,j]of v)b(j.entry.address.scopeIds)&&v.delete(x);for(const[x,j]of U)b(j.ids)&&(j.controller.abort(),U.delete(x));for(const[x,j]of L)b(j)&&x.abort()}function F(){if(!N){N=!0,v.clear();for(const O of L.keys())O.abort();L.clear();for(const O of U.values())O.controller.abort();U.clear(),s.delete(F),a.delete(C),o.get(A)?.cache===R&&o.delete(A)}}const R={read:D,invalidateScope:O=>g(O,A),dispose:F};return s.add(F),a.add(C),o.set(A,{definition:{namespace:A,codec:_,policy:w},sourceCodec:M.codec,cache:R}),R}return{createScope(M,S){if(c||!M)throw new Error("Invalid runtime cache scope");const w=Object.freeze({});return r.set(w,[...S?f(S):[],M]),w},register:T,invalidateScope:M=>g(M),dispose(){if(!c){c=!0;for(const M of[...s])M();o.clear(),n.clear(),i.clear()}}}}function cl(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 dl=".hb-runtime-cache-v1",ti=64*1024,ft=1e3,ul=2048,Rt=32*1024*1024,ll=1024,Pr=new TextEncoder,Xo=new TextDecoder("utf-8",{fatal:!0});function Pt(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Ar(e){const t=await globalThis.crypto.subtle.digest("SHA-256",Pr.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Te(e,t){return JSON.stringify(e)===JSON.stringify(t)}function es(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function fl(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function ts(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function hl(e,t){const r=e.sandbox.directory(dl),n=r.directory("revisions"),i=r.directory("entries");for(const l of[r,n,i,i.directory("capability-check")])ts(l,["directory","file","create","stat","list","remove"]),ts(l.file("capability-check"),["create","stat","read","write","remove"]);let o=Promise.resolve(),s=!1;function a(l){if(fl(l))throw s=!0,l}function c(){if(t.signal.aborted)throw Pt();if(s)throw Object.assign(new Error("Host 不支持完整文件能力,磁盘缓存已关闭"),{code:"METHOD_FORBIDDEN"})}function d(l,p=t.signal){const m=o.then(()=>{if(p.aborted)throw Pt();return c(),l()},()=>{if(p.aborted)throw Pt();return c(),l()}).catch(D=>{throw a(D),D});if(o=m.catch(()=>{}),p.aborted)return Promise.reject(Pt());let E=()=>{};const I=new Promise((D,C)=>{const F=()=>C(Pt());p.addEventListener("abort",F,{once:!0}),E=()=>p.removeEventListener("abort",F)});return Promise.race([m,I]).finally(E)}async function f(){c(),await n.create({recursive:!0,exclusive:!1},t),await i.create({recursive:!0,exclusive:!1},t),c()}async function h(l,p){const m=n.file(`${await Ar([l,p??null])}.revision`);await g(m);let E=!1;try{await m.create({recursive:!1,exclusive:!0},t),E=!0}catch(C){a(C),c()}if(E){const C=es();return await m.write(Pr.encode(C),t),c(),C}const I=await m.stat(t);if(I.size<1||I.size>128)throw new Error("缓存 revision 文件损坏");const D=Xo.decode(await m.read(t));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(D))throw new Error("缓存 revision 文件损坏");return c(),D}async function u(l){const p=await l.list({limit:ft},t);if(p.length>=ft)throw new Error("缓存目录超过治理上限");return p}async function g(l){try{await l.stat(t);return}catch(m){if(!Dr(m))throw m}if((await u(n)).length>=ft-1)throw new Error("缓存 metadata 超过治理上限")}async function T(l,p){await f();const m=[];for(let E=0;E<l.length;E+=1){const I=l.slice(0,E+1);m.push(await h(I),await h(I,p))}return m}async function M(l){return r.directory(`entries/${await Ar([l.namespace,l.codecVersion,l.scopeIds])}`)}async function S(l){return(await M(l)).file(`${await Ar(l.key)}.cache`)}async function w(l,p){const m=await l.stat(t);if(m.size<5||m.size>p+ti+4)throw new Error("缓存条目超过大小限制");const E=await l.read(t);if(c(),E.length!==m.size)throw new Error("缓存条目读取不完整");const I=new DataView(E.buffer,E.byteOffset,E.byteLength).getUint32(0);if(I<1||I>ti||I+4>E.length)throw new Error("缓存信封损坏");const D=JSON.parse(Xo.decode(E.subarray(4,I+4))),C=E.slice(I+4);if(D.envelopeVersion!==1||!D.address||!Array.isArray(D.address.scopeIds)||!D.address.scopeIds.every(F=>typeof F=="string")||typeof D.address.namespace!="string"||typeof D.address.codecVersion!="string"||typeof D.address.key!="string"||!Array.isArray(D.revisions)||D.revisions.length!==D.address.scopeIds.length*2||!D.revisions.every(F=>typeof F=="string"&&F.length>0)||!Number.isSafeInteger(D.cachedAt)||!Number.isSafeInteger(D.expiresAt)||D.cachedAt<0||D.expiresAt<=D.cachedAt||D.payloadBytes!==C.length||C.length>p)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:D.address,revisions:D.revisions,cachedAt:D.cachedAt,expiresAt:D.expiresAt,payload:C}}async function _(l){if(!l.remove)throw new Error("Host 不支持缓存文件删除");await l.remove(t)}async function A(l){try{if((await l.file.stat(t)).size!==l.size)return!1;const p=await w(l.file,Rt);return!Te(p.address,l.entry.address)||!Te(p.revisions,l.entry.revisions)||p.cachedAt!==l.entry.cachedAt||p.expiresAt!==l.entry.expiresAt||!Te(await v(p.payload),await v(l.entry.payload))?!1:(await _(l.file),!0)}catch(p){if(Dr(p))return!0;throw p}}async function v(l){const p=await globalThis.crypto.subtle.digest("SHA-256",l);return Array.from(new Uint8Array(p),m=>m.toString(16).padStart(2,"0")).join("")}async function U(){const l=await u(n);let p=0;for(const D of l)if(D.kind==="file"&&(p+=(await D.stat(t)).size,p>Rt))throw new Error("缓存扫描超过字节上限");const m=[];let E=0,I=p;for(const D of await u(i)){if(D.kind!=="directory")throw new Error("缓存目录结构损坏");for(const C of await u(D)){if(C.kind!=="file"||++E>ul)throw new Error("缓存文件超过治理上限");const F=(await C.stat(t)).size;if(I+=F,I>Rt)throw new Error("缓存扫描超过字节上限");try{const R=await w(C,Rt);m.push({file:C,entry:R,size:(await C.stat(t)).size,bucketName:D.name})}catch(R){a(R),c(),Dr(R)||await _(C)}}}return{entries:m,metadataBytes:p}}async function L(){for(const l of await u(i))if(l.kind==="directory"&&l.remove&&(await u(l)).length===0)try{await l.remove({recursive:!1},t)}catch(p){a(p),c()}}function N(l){const{payload:p,...m}=l,E=Pr.encode(JSON.stringify({...m,payloadBytes:p.length}));if(E.length>ti)throw new Error("缓存信封过大");const I=new Uint8Array(4+E.length+p.length);return new DataView(I.buffer).setUint32(0,E.length),I.set(E,4),I.set(p,E.length+4),I}return{readRevisions:(l,p)=>d(()=>T(l,p)),read:(l,p)=>d(async()=>{c();const m=await S(l);let E;try{E=await w(m,p)}catch(I){if(c(),Dr(I))return;throw I}if(!(!Te(E.address,l)||E.expiresAt<=Date.now())&&Te(E.revisions,await T(l.scopeIds,l.namespace)))return E}),publish:(l,p)=>d(async()=>{c();const{address:m}=l;if(!Te(l.revisions,await T(m.scopeIds,m.namespace)))return!1;const E=N(l);if(l.payload.length>p.maxEntryBytes||E.length>p.diskMaxBytes||p.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await f();const I=await M(m),D=await S(m),C=await U(),F=[],R=new Map;for(const b of C.entries){if(b.bucketName===I.name&&b.file.name===D.name)continue;const x=JSON.stringify([b.entry.address.scopeIds,b.entry.address.namespace]);let j=R.get(x);if(j||(j=await T(b.entry.address.scopeIds,b.entry.address.namespace),R.set(x,j)),b.entry.expiresAt<=Date.now()||!Te(b.entry.revisions,j)){if(!await A(b))throw new Error("缓存治理期间条目已变化")}else F.push(b)}F.sort((b,x)=>b.entry.cachedAt-x.entry.cachedAt);function O(){const b=F.filter(x=>x.bucketName===I.name);return F.length+1>ll||E.length+C.metadataBytes+F.reduce((x,j)=>x+j.size,0)>Rt||b.length+1>Math.min(p.diskMaxEntries,ft-1)||E.length+b.reduce((x,j)=>x+j.size,0)>p.diskMaxBytes}for(;O();){const b=F.filter(z=>z.bucketName===I.name),j=b.length+1>Math.min(p.diskMaxEntries,ft-1)||E.length+b.reduce((z,B)=>z+B.size,0)>p.diskMaxBytes?b[0]:F[0];if(!j||!await A(j))throw new Error("缓存容量不足或条目已变化");F.splice(F.indexOf(j),1)}await L();const P=await u(i);if(!P.some(b=>b.name===I.name)&&P.length>=ft-1)throw new Error("缓存目录超过治理上限");if(await I.create({recursive:!0,exclusive:!1},t),!Te(l.revisions,await T(m.scopeIds,m.namespace)))return!1;try{await D.create({recursive:!1,exclusive:!0},t)}catch(b){a(b),await D.stat(t)}return await D.write(E,t),c(),Te(l.revisions,await T(m.scopeIds,m.namespace))}),invalidate:(l,p)=>d(async()=>{await f();const m=n.file(`${await Ar([l,p??null])}.revision`);await g(m);try{await m.create({recursive:!1,exclusive:!0},t)}catch(E){a(E),await m.stat(t)}await m.write(Pr.encode(es()),t),c();try{const{entries:E}=await U();for(const I of E){if(p!==void 0&&I.entry.address.namespace!==p||!l.every((C,F)=>I.entry.address.scopeIds[F]===C))continue;const D=await T(I.entry.address.scopeIds,I.entry.address.namespace);Te(I.entry.revisions,D)||await A(I)}await L()}catch(E){a(E),c()}})}}function Dr(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const ml="RATE_LIMITED_BY_RUNTIME",gl="RATE_LIMITED",mc=20,gc=40,pc=150,yc=20,Ec=1e4,Ic=45e3,wc=1,pl=300*1e3,yl=64;function ht(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function El(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Il(e={}){const t=e.now??Date.now,r=El(e.coalesceWindowMs,pc),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,ht(e.budget?.ratePerSecond,mc)),burst:Math.max(1,Math.floor(ht(e.budget?.burst,gc)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(ht(e.loopDetection?.maxCalls,yc))),windowMs:Math.max(1,Math.floor(ht(e.loopDetection?.windowMs,Ec)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(ht(e.circuitBreaker?.failureThreshold,wc))),openMs:Math.max(1,Math.floor(ht(e.circuitBreaker?.openMs,Ic)))},s=new Map,a=new Map,c=new Set,d=new Map,f=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},h={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let u=!1;function g(N){try{e.onReport?.(N)}catch{}}function T(N,l){if(!i)return{exceeded:!1,count:0};const p=a.get(N)??[],m=l-i.windowMs;let E=0;for(;E<p.length&&p[E]<=m;)E+=1;E>0&&p.splice(0,E);const I=p.length>=i.maxCalls;return I||(p.push(l),p.length>i.maxCalls+1&&p.splice(0,p.length-(i.maxCalls+1))),a.set(N,p),{exceeded:I,count:p.length}}function M(N){if(!n)return!0;const l=Math.max(0,N-f.updatedAt)/1e3;return f.tokens=Math.min(n.burst,f.tokens+l*n.ratePerSecond),f.updatedAt=N,f.tokens<1?!1:(f.tokens-=1,!0)}function S(N){if(!n)return 0;const l=Math.max(0,N-f.updatedAt)/1e3,p=Math.min(n.burst,f.tokens+l*n.ratePerSecond);return Math.max(0,Math.ceil((1-p)/n.ratePerSecond*1e3))}function w(N,l,p,m,E){if(!o)return;const I=d.get(l),D=(I?.open?0:I?.failures??0)+1;if(D<o.failureThreshold){d.set(l,{open:!1,openedAt:0,openMs:0,failures:D});return}const C=Math.min(Math.max(o.openMs,m),pl);d.set(l,{open:!0,openedAt:E,openMs:C,failures:D}),h.circuitOpened+=1,g({type:"circuit_opened",capability:N,endpointId:l,status:p,openMs:C,timestamp:E})}function _(N){const l=d.get(N);l&&!l.open&&d.delete(N)}function A(N){for(const[l,p]of s)!p.pending&&p.expiresAt<=N&&s.delete(l);for(;s.size>=yl;){const l=[...s].find(([,p])=>!p.pending);if(!l)break;s.delete(l[0])}}function v(N,l){if(N===void 0)return;const p=s.get(N);p?.promise===l&&(p.pending=!1)}function U(N,l){if(N===void 0)return;s.get(N)?.promise===l&&s.delete(N)}async function L(N){if(u)return N.load();const l=t();if(o){const I=d.get(N.endpointId);if(I?.open){const D=I.openedAt+I.openMs-l;if(D>0)throw h.circuitRejected+=1,g({type:"circuit_rejected",capability:N.capability,endpointId:N.endpointId,retryAfterMs:D,timestamp:l}),Nl("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:N.endpointId,retryAfterMs:D});d.delete(N.endpointId)}}const p=T(N.endpointId,l);p.exceeded&&i?c.has(N.endpointId)||(c.add(N.endpointId),g({type:"loop_detected",capability:N.capability,endpointId:N.endpointId,count:p.count,windowMs:i.windowMs,timestamp:l})):c.delete(N.endpointId);const m=r>0?N.coalesceKey:void 0;if(m!==void 0){const I=s.get(m);if(I&&(I.pending||I.expiresAt>l))return h.coalesced+=1,g({type:"coalesced",capability:N.capability,endpointId:N.endpointId,timestamp:l}),I.promise;I&&s.delete(m)}if(p.exceeded&&i)throw h.loopRejected+=1,rs("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:N.capability,endpointId:N.endpointId,count:p.count,windowMs:i.windowMs});if(!M(l)){h.budgetRejected+=1;const I=S(l);throw g({type:"budget_exhausted",capability:N.capability,endpointId:N.endpointId,retryAfterMs:I,timestamp:l}),rs("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:N.capability,endpointId:N.endpointId,retryAfterMs:I})}m!==void 0&&A(l);const E=N.load().then(I=>(v(m,E),_(N.endpointId),I),I=>{U(m,E);const D=wl(I);throw D!==void 0&&w(N.capability,N.endpointId,D,Ml(I),l),I});return m!==void 0&&s.set(m,{promise:E,expiresAt:l+r,pending:!0}),E}return{execute:L,invalidateCoalescing(){s.clear()},snapshot(){return{...h,openCircuits:[...d.entries()].filter(([,N])=>N.open).map(([N])=>N)}},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function wl(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 Ml(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 rs(e,t){return{code:ml,message:e,data:t}}function Nl(e,t){return{code:gl,message:e,data:t}}const Mc=3e4,Nc=6e4,Vi=1440*60*1e3;function Al(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??Mc)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??Nc)):0,steamGameListTtlMs:t?Dl(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:mc,burst:gc},coalesceWindowMs:r?.coalesceWindowMs??pc,loopDetection:r?.loopDetection??{maxCalls:yc,windowMs:Ec},circuitBreaker:r?.circuitBreaker??{failureThreshold:wc,openMs:Ic}}}}function Dl(e){return e===void 0||!Number.isFinite(e)?Vi: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 H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tl(e){return typeof e=="object"&&e!==null}function ye(e,t){const r=e.data;if(!Tl(r)||typeof r.status!="string")throw new Error(t);return r}const Ac={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Sl={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 gr(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function bl(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Ol(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=bl(r.consent_challenge)),{...t,result:n}}const _l={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=>({...gr(e.runtimeContext),challenge:e.challenge}),parse:e=>ye(e,"小程序授权取消接口响应异常")},Ll={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=>gr(e.runtimeContext),parse:e=>ye(e,"小程序授权撤销接口响应异常")},vl={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=>gr(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}:{}}}}},Cl={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=>({...gr(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Ol(e)},Rl={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=>({...gr(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}}}},Pl=64;function Dc(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??Pl)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(h){for(const[u,g]of i)g.expiresAt<=h&&i.delete(u)}function d(h,u,g){if(a||t<=0||g!==s)return;const T=n();for(c(T),i.delete(h);i.size>=r;){const M=i.keys().next();if(M.done)break;i.delete(M.value)}i.set(h,{expiresAt:T+t,value:u})}function f(h,u){if(a)return u();if(t>0){const S=i.get(h);if(S&&S.expiresAt>n())return Promise.resolve(S.value);S&&i.delete(h)}const g=o.get(h);if(g)return g;const T=s,M=u().then(S=>(d(h,S,T),S)).finally(()=>{o.get(h)===M&&o.delete(h)});return o.set(h,M),M}return{read:f,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function kl(e,t){return t?e?"server":"local":"legacy"}function xl(e,t){if(e==="local")throw y("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const jl=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],zl=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Ul=/authorization|cookie|pkey|password|secret|token/i,Tc=/authorization|cookie|pkey|token|password|secret/i;function Se(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Hl(e){for(const t of Object.keys(e))if(!zl.has(t))throw new se(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of jl)if(Object.prototype.hasOwnProperty.call(e,t)&&Se(e,t)!==void 0)throw new se(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Se(e,"bodyEncoding")!==void 0&&Se(e,"bodyEncoding")!=="json"&&Se(e,"bodyEncoding")!=="form")throw new se("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Se(e,"failurePresentation")!==void 0&&Se(e,"failurePresentation")!=="none")throw new se("endpoint failurePresentation 必须为 none");if(Se(e,"auth")!==void 0&&Se(e,"auth")!=="none"&&Se(e,"auth")!=="optional"&&Se(e,"auth")!=="required")throw new se("endpoint auth 必须为 none、optional 或 required")}function Gt(e){if(Array.isArray(e))return e.map(Gt);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Ul.test(n)||(r[n]=Gt(i));return r}function ns(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Tc.test(r)||(t[r]=n);return t}function Fl(e){if(!e)return;const t=Object.keys(e).find(r=>Tc.test(r));if(t)throw new se(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Tt 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 is=1440*60*1e3,Vl=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function Bl(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,is):void 0}if(!Vl.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,is):void 0}function Ql(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 Sc(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class St extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Sc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class pr extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Sc(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function Yl(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:Gt(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:ns(o),method:e.method,metadata:{endpointId:e.id},query:Gt(n),timeout:e.timeout,url:r},data:Gt(a.data),headers:ns(a.headers)||{},status:a.status,statusText:a.statusText}}async function Qn(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(Hl(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;Fl(a);const c=async()=>{let h;try{h=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(g){throw g instanceof se?g:new St({endpointId:t.id,cause:g})}if(h.status<200||h.status>=300)throw new Tt({endpointId:t.id,status:h.status,retryAfterMs:Bl(h.headers)});const u=Yl(t,r,i,o,s,a,n,h);if(t.parse)try{return await t.parse(u,r)}catch(g){throw new pr({endpointId:t.id,cause:g})}return u.data},d=n.gate;if(!d)return c();const f=Ql(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...f===void 0?{}:{coalesceKey:f},load:c})}const Gl=new Set(Dt),wo="steam_account",bc=new Set(Dt.filter(e=>e!==wo)),ql=1e3;function Wl(e){const t=new Set,r=Dc({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??Mc))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??kl(e.networkEnabled===!0,c),f=e.requestPolicyEnabled!==!1,h=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 R;try{R=await e.authorizationContext.get(e.operationContext)}catch{throw y("REQUEST_FAILED","读取 Runtime auth context 失败")}if(R.steamAccount!==c||R.userDataMode!==d)throw y("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const O=R.token.trim();if(!O)throw y("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:O}}const g=e.account.onChange(R=>{T(),M("heybox_app_login_change",{isHeyboxAppLoggedIn:!!R})});function T(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function M(R,O){R==="user_info_authorization_change"&&tf(O)&&r.invalidate();for(const P of t)try{P(R,O)}catch{}}function S(){const R=e.identity.get()?.miniProgramId?.trim();if(!R)throw y("INVALID_STATE","当前能力缺少 canonical 小程序身份");return R}function w(){if(o||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function _(){w();let R;try{R=await e.account.getCurrentUserId(e.operationContext)}catch(O){throw cs(O,e.operationContext.signal,"读取小黑盒账号失败")}return typeof R=="string"&&R.trim()?R.trim():void 0}async function A(R,O){const P=await _();if(i!==O||P!==R)throw y("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function v(R){w();try{await e.account.ensureAuthenticated({trustedUserGesture:R,reason:"runtime_auth",signal:e.operationContext.signal})}catch(P){throw cs(P,e.operationContext.signal,"小黑盒登录失败")}const O=await _();if(!O)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return O}async function U(R,O,P=e.operationContext.signal){try{if(P.aborted)throw Bi();return await ef(Qn(e.network,R,O,{...e.operationContext,credentials:"heybox-session",signal:P,...h?{gate:h}:{}}),P)}catch(b){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):b instanceof se?y("REQUEST_UNSUPPORTED",b.message):b instanceof pr?y("INVALID_RESPONSE","授权接口响应不合法"):b instanceof St?y("REQUEST_FAILED","授权请求失败"):b instanceof Tt?f&&(b.status===403||b.status===429)?y("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:b.status,...b.retryAfterMs===void 0?{}:{retryAfterMs:b.retryAfterMs}}):y("REQUEST_FAILED",b.message):Oc(b)?b:y("REQUEST_FAILED","授权请求失败")}}async function L(R,O){await U(_l,{runtimeContext:{miniProgramId:R,...await u()},challenge:O}).catch(()=>{})}function N(R){const O=async()=>{const b=ss(e.operationContext.signal);a=b;try{return await R(b.signal)}finally{a===b&&(a=void 0),b.abort()}},P=s.then(O,O);return s=P.then(()=>{},()=>{}),P}async function l(R,O,P,b,x){if(!P)throw await L(R,O.challenge),y("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await L(R,O.challenge),y("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return N(async j=>{await A(b,x);const z=await p(R,O.displayedScopes,j);await A(b,x);let B;try{B=await e.authPresentation.confirmAuthorization({miniProgramId:R,scopes:O.displayedScopes,...z,signal:j})}catch(G){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await A(b,x),await L(R,O.challenge),$l("REQUEST_FAILED","授权确认界面执行失败",G))}if(await A(b,x),B.status!=="granted")throw await L(R,O.challenge),y("AUTHORIZATION_CANCELLED","用户取消授权");const Q=Zl(B.grantedScopes,O.displayedScopes,c);if(!Q.includes("identity"))throw await L(R,O.challenge),y("AUTHORIZATION_CANCELLED","用户拒绝授权");return Q})}async function p(R,O,P){const b=ss(P),x=setTimeout(()=>b.abort(),ql);try{const j=Xl(e.miniProgramPresentation),[z,B]=await Promise.all([j?Promise.resolve(j):m(R,b.signal),O.includes("profile")?E(b.signal):Promise.resolve(void 0)]);return{...z?{miniProgram:z}:{},...B?{userProfile:B}:{}}}finally{clearTimeout(x),b.abort()}}async function m(R,O){try{const P=e.identity.get()?.version?.trim(),b=await U(Sl,{mini_program_id:R,...P?{miniprogram_version:P}:{}},O),x=mt(b,"小程序公开资料"),j=Nt(x.name),z=Nt(x.icon_url);return j||z?{...j?{name:j}:{},...z?{avatarUrl:z}:{}}:void 0}catch{return}}async function E(R){try{const O=await U(Ac,void 0,R),P=mt(O,"账号基础信息"),b=Nt(P.display_username),x=Nt(P.display_avatar);return b||x?{...b?{nickname:b}:{},...x?{avatar:x}:{}}:void 0}catch{return}}async function I(R,O){if(xl(d,"auth.login"),!c&&R.includes(wo))throw y("INVALID_PARAMS","auth.login 参数不合法");const P=S(),b=await v(O),x=i,j=await U(Cl,{runtimeContext:{miniProgramId:P,...await u()},scopes:R});await A(b,x);const z=mt(j,"小程序登录"),B=as(z,"loginCode"),Q=as(z,"consentChallenge");if(B===Q)throw y("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let G;if(B)G=os(z.loginCode,c);else{const te=Kl(z.consentChallenge,c),X=await l(P,te,O,b,x);await A(b,x);const Z=await U(Rl,{runtimeContext:{miniProgramId:P,...await u()},challenge:te.challenge,selectedScopes:X});if(await A(b,x),G=os(mt(Z,"小程序登录确认"),c),G.scopes.some(q=>!X.includes(q)))throw y("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const te of G.scopes)n.add(te);return r.invalidate(),M("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),M("user_info_authorization_change",ri(n,c)),G}async function D(R,O){const P=i,b=await U(vl,{runtimeContext:{miniProgramId:O,...await u()}});await A(R,P);const x=Jl(mt(b,"用户本地身份"),c);for(const j of c?Dt:bc)n.add(j);return M("user_info_authorization_change",ri(n,c)),x}function C(R){w();const O=S(),P=`${R}\0${O}\0${i}\0${c}`;return r.read(P,()=>D(R,O))}async function F(R){if(!R)throw y("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const O=S(),P=i,b=await _();if(!b)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const x=await U(Ll,{runtimeContext:{miniProgramId:O,...await u()}});await A(b,P),mt(x,"用户授权撤销"),T(),M("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{login:I,getOrCreateLocalIdentity:C,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>ri(n,c),revoke:F,onEvent(R){return t.add(R),()=>t.delete(R)},dispose(){o||(o=!0,T(),r.dispose(),g(),t.clear())}}}function $l(e,t,r){const n=y(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function mt(e,t){if(!H(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(!H(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function os(e,t){if(!H(e))throw y("INVALID_RESPONSE","login code 必须是对象");const r=Dn(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 Kl(e,t){if(!H(e))throw y("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Dn(e.requestedScopes,"challenge requestedScopes",t),n=Dn(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 Jl(e,t){if(!H(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 Zl(e,t,r){const n=Dn(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw y("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Nt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Xl(e){const t=Nt(e?.name),r=Nt(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function ss(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 ef(e,t){return t.aborted?Promise.reject(Bi()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Bi()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Bi(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Dn(e,t,r){const n=r?Gl:bc;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?Dt:Dt.filter(n=>n!==wo);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function as(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function tf(e){return H(e)?Object.values(e).some(t=>t==="denied"):!1}function Oc(e){return H(e)&&typeof e.code=="string"&&typeof e.message=="string"}function cs(e,t,r){return t.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Oc(e)?e:y("REQUEST_FAILED",r)}const rf=new Set(Dt);function nf(e){return{[qr]:async(t,r)=>e.authorization.login(of(t),r.trustedUserGesture)}}function of(e){if(e===void 0)return["identity"];if(!H(e)||Object.keys(e).some(t=>t!=="scopes"))throw ds();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!rf.has(t))||new Set(e.scopes).size!==e.scopes.length)throw ds();return[...e.scopes]}function ds(){return y("INVALID_PARAMS","auth.login 参数不合法")}const sf={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,"排行榜记录删除接口响应异常")}},af={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,"当前排行榜记录接口响应异常")}},cf={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,"排行榜信息接口响应异常")}},df={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,"排行榜列表接口响应异常")}},uf={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 us(e){return e instanceof se?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function ee(e){if(e.aborted)throw kr()}function W(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(kr());let n;try{n=e()}catch(i){return Promise.reject(us(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(kr())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(kr()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(us(d))))})}const lf="default",ff=/^[A-Za-z0-9_-]{1,64}$/,hf=300*1e3,mf=250,gf=3,pf={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 yf{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=If(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(uf,{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=xt("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(df,{miniProgramId:r,...t}),s=kt(o,Ne);if(!ve(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw ne(`${Ne} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw ne(`${Ne} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>ni(a,Ne)),...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=xt("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(af,{miniProgramId:n,...t}),c=kt(a,Qe);if(!ve(c))throw ne(`${Qe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:ni(c.entry,Qe)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(sf,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=kt(i,st);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!ve(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",xt("info"),async()=>{const i=await this.request(cf,{miniProgramId:r,...t}),o=kt(i,Le);if(!ve(o)||typeof o.key!="string"||!ff.test(o.key))throw ne(`${Le} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw ne(`${Le} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw ne(`${Le} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw ne(`${Le} 返回的 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=xt(t,n),d=this.inflight.get(c);if(d)return d.promise;const f=this.accountGeneration,h=o?.generation,u=i().then(g=>(this.assertAccountGeneration(f),o&&s&&o.generation===h&&(r==="list"?s.size>=mf&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+hf,value:g})),g)).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>=gf)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)fs(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){fs(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 W(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw ms(n)?n:hs()}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw Ie("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw Ie("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return xt(t,r??lf)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw Ie("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){this.assertUsable();const n={request:async(i,o)=>(this.assertUsable(),this.options.network.request(i,o))};try{return await W(()=>Qn(n,t,r,{...this.options.operationContext,credentials:"heybox-session",...this.requestGateContext?{gate:this.requestGateContext}:{}}),this.options.operationContext.signal)}catch(i){if(ms(i)||Ft(i,"REQUEST_UNSUPPORTED")||Ft(i,"RATE_LIMITED")||Ft(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof se)throw Ie("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求");if(i instanceof St&&Ft(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Tt){if(this.options.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw Ie("RATE_LIMITED","排行榜请求已被网关限流,请稍后重试",{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw Ie("UNAUTHORIZED","当前用户未登录")}throw i instanceof St||i instanceof Tt?hs():i instanceof pr?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(ee(this.options.operationContext.signal),this.disposed)throw Ie("INVALID_STATE","Cloud capability 已释放")}}function Ef(e){return new yf(e)}function If(e,t){try{return e.onChange(t)}catch(r){if(Ft(r,uc))return()=>{};throw r}}function kt(e,t){if(!ve(e)||typeof e.status!="string")throw ne(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw wf(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(!ve(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(!ve(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 wf(e){if(e.status==="login"||e.status==="relogin")throw Ie("UNAUTHORIZED",Ht(e.msg)||"当前用户未登录");const t=ls(e.result)??ls(e),r=Ht(t?.user_message)||Ht(e.msg)||Ht(t?.developer_message)||"排行榜请求失败";throw t?Ie(Mf(t),r,{status:e.status,sbe:t}):Ie("HEYBOX_API_ERROR",r,{status:e.status})}function ls(e){return ve(e)&&ve(e.sbe)?e.sbe:void 0}function Mf(e){const t=Ht(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 pf[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 fs(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function xt(...e){return JSON.stringify(e)}function ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ht(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Ft(e,t){return ve(e)&&e.code===t}function Ie(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function ne(e){return Ie("INVALID_RESPONSE",e)}function hs(){return Ie("REQUEST_FAILED","排行榜请求失败")}function ms(e){return e instanceof Error&&e.name==="AbortError"}const Nf=/^[A-Za-z0-9_-]{1,64}$/,gs=20,Af=100,ps=2048;function Df(e){const t=Ef(e);return{handlers:{[ke]:async n=>t.submit(Tf(n)),[Ne]:async n=>t.getList(Sf(n)),[Qe]:async n=>t.getCurrentUserEntry(ii(n,Qe)),[st]:async n=>t.deleteCurrentUserEntry(ii(n,st)),[Le]:async n=>t.getInfo(ii(n,Le))},dispose:()=>t.dispose()}}function Tf(e){const t=Mo(e,ke,!1);if(No(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{...Ao(t.key,ke),score:t.score,...t.extra===void 0?{}:{extra:bf(t.extra)}}}function Sf(e){if(e===void 0)return{limit:gs};const t=Mo(e,Ne,!0);No(t,["key","limit","cursor"],Ne);const r=t.limit===void 0?gs:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>Af)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{...Ao(t.key,Ne),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function ii(e,t){if(e===void 0)return{};const r=Mo(e,t,!0);return No(r,["key"],t),Ao(r.key,t)}function Mo(e,t,r){if(e===void 0&&r)return{};if(!_c(e))throw Ce("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function No(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Ce("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Ao(e,t){if(e===void 0)return{};if(typeof e!="string"||!Nf.test(e))throw Ce("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function bf(e){if(!_c(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 _c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ce(e,t){return{code:e,message:t}}const Of=new Set(["stdio","attachments","notifications"]),Lc=new Set(["windows-x64","macos-arm64"]),_f=new Set(["unsigned","valid","invalid","unknown"]),Lf=/^[a-f0-9]{64}$/,vf=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Cf=new Set(cc),Rf=new Set([...cc,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),vc=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 Pf(e){const t=async(n,i,o,s)=>{const a=kf(n);try{_e(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return _e(i.signal),c}catch(c){throw Yi(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(d=>xf(d,i)).catch(d=>{throw Yi(d)});_e(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(_e(o.signal),c.status!=="granted")throw y("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[vn]:(n,i)=>t(n,i,async(o,s)=>Qi(await e.companion.getInfo(o,s),o)),[Cn]:(n,i)=>t(n,i,async(o,s)=>ys(await e.companion.getPreparationStatus(o,s))),[Rn]:(n,i)=>t(n,i,async(o,s)=>{const a=ys(await e.companion.getPreparationStatus(o,s));return _e(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),_e(i.signal),Qi(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(Rc(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[Pn]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[kn]:(n,i)=>t(n,i,async(o,s)=>Es(await e.companion.getActiveSession(o,s),o)),[xn]:(n,i)=>t(n,i,async(o,s)=>{const a=Es(await e.companion.getActiveSession(o,s),o);return _e(i.signal),a||(await r("launch",o,i),_e(i.signal),Pc(await e.companion.launch(o,s),o))}),[jn]:(n,i)=>gt(n,i,e,"write"),[zn]:(n,i)=>gt(n,i,e,"closeStdin"),[Un]:(n,i)=>gt(n,i,e,"terminate"),[Hn]:(n,i)=>gt(n,i,e,"ackOutput"),[Fn]:async(n,i)=>{const o=await gt(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Vn]:(n,i)=>gt(n,i,e,"showNotification")}}function kf(e){if(!H(e)||typeof e.alias!="string"||!Au.test(e.alias))throw y("INVALID_PARAMS","Companion alias 不合法");return e.alias}function _e(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function gt(e,t,r,n){if(!H(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw y("INVALID_PARAMS","Companion Session controller 不合法");try{_e(t.signal);const i=await r.companion[n](jf(e,n),{...r.operationContext,signal:t.signal});return _e(t.signal),i}catch(i){throw Yi(i)}}function De(){throw y("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Cc(e){return!Array.isArray(e)||e.some(t=>!Of.has(t))?De():Object.freeze([...new Set(e)])}function Qi(e,t){return!H(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Lc.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!_f.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?De():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Cc(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function xf(e,t){const r=Qi(e,t);return!H(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!Lf.test(e.sha256)?De():Object.freeze({...r,sha256:e.sha256})}function Rc(e){return H(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}):De():De()}function ys(e){return H(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Rc(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&H(e.error)&&typeof e.error.code=="string"&&Cf.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:vc[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):De():De()}function Pc(e,t){return!H(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Lc.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?De():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Cc(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Es(e,t){return e===void 0?void 0:Pc(e,t)}function jf(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!oc(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 zf(e){return!H(e)||!vf.has(String(e.reason))?De():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):De():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?De():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Uf(e){if(!H(e)||!H(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||!oc(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:zf(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 Yi(e,t){return H(e)&&typeof e.code=="string"&&Rf.has(e.code)?y(e.code,vc[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&H(e)&&e.name==="AbortError"?y(t,"Companion 准备已取消"):y("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Is=5e3,ws=1e4;function ue(e){throw{code:"INVALID_PARAMS",message:e}}function Do(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kc(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&ue(`${r} 不支持字段: ${n.join(", ")}`)}function Hf(e){if(e===void 0)return{intensity:"light",delay:0};if(!Do(e))return ue("device.vibrate 参数必须是对象");kc(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return ue("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Is?ue(`device.vibrate delay 必须是 0-${Is} 的整数毫秒`):{intensity:r,delay:n}}function Ff(e){return Do(e)?(kc(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?ue("device.setClipboard text 必须是非空字符串"):e.text.length>ws?ue(`device.setClipboard text 不能超过 ${ws} 字符`):{text:e.text}):ue("device.setClipboard 参数必须是对象")}function Vf(e){return typeof e=="string"?e.trim()?e:ue("device.executeProtocol 协议字符串不能为空"):Do(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?ue("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(Gi(e,new Set),e):ue("device.executeProtocol 参数必须是协议字符串或协议对象")}function Gi(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||ue("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":ue("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":ue(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&ue("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)Gi(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&ue("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))Gi(i,t);t.delete(r)}function Bf(e){return{[En]:async t=>{ee(e.operationContext.signal),await W(()=>e.presentation.vibrate(Hf(t),e.operationContext),e.operationContext.signal)},[In]:async t=>{ee(e.operationContext.signal),await W(()=>e.presentation.setClipboard(Ff(t),e.operationContext),e.operationContext.signal)},[wn]:async(t,r)=>{const n=at(e.operationContext,r.signal);ee(n.signal);const i=Vf(t);await W(()=>e.protocol.invoke(i,n),n.signal)}}}const Qf=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"]),Yf={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=To(e),r=t&&Qf.has(t)?y(t,Yf[t]??"文件操作失败"):y("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Pe(e){try{return e()}catch(t){throw cr(t)}}function To(e){try{if(!H(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function xc(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):qi,remove:o?s=>e.remove(s):zc,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):qi,stat:s=>e.stat(s)})}function jc(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=>xc(e.file(a),n,{allowRemove:o}),directory:a=>jc(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):qi,remove:s?(a,c)=>e.remove(a,c):zc,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function qi(){return Promise.reject(y("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function zc(){return Promise.reject(y("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Ms=1024;class Gf{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 Tr(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Pe(()=>{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>Ms)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw y("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>Tr(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 As(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Bn(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Wf(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(Pe(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=$f(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:Pe(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Ts(t),Tr(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Pe(()=>{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 Pe(()=>{if(H(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Tr(n.handle,Ns(t.ref,n.handle.name))}if(H(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return As(n.handle,qf(t.ref,n.handle.name))}throw y("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=yr(r),i=this.prepareFile(Pe(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:Ns(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw y("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Pe(()=>{Ts(t);const i=n??t.mode;return Ds(t.mode,i),{handle:xc(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Pe(()=>{Zf(t,i);const o=n??t.mode;return Ds(t.mode,o),{handle:jc(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Ms)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Kf();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(!Jf(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 Ae("files.sandbox");return this.prepareDirectory(Pe(()=>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 Ae("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 Ns(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 qf(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 Tr(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function As(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Ds(e,t){if(t==="readwrite"&&e!=="readwrite")throw y("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Wf(e){return Bn(e)||Uc(),e}function $f(e){return ic(e)||Uc(),e}function Uc(){throw y("INVALID_PARAMS","文件引用不合法")}function Kf(){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 Jf(e){return/^[0-9a-f]{32}$/.test(e)}function Ts(e){if(!H(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 Zf(e,t=!1){if(!H(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 Ss=1e3,Xf=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function eh(e){const t=r=>at(e.operationContext,r.signal);return{files:{[sn]:async(r,n)=>{oi(n);const i=si(e.picker),o=th(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=rh(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=nh(r).suggestedName,s=t(n);if(!i.saveFile)throw Ae("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(bs(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 Ae(rr);await me(()=>o.handle.remove(t(n)))},[dn]:async(r,n)=>{const i=Ee(r);return Os(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!H(o)||o.kind!=="file")throw Ls()})},[nr]:async(r,n)=>{const i=Ee(r),o=_s(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 文本")}},[un]:async(r,n)=>{const i=Ee(r,["content"]);typeof i.content!="string"&&Me("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 _s(o)},[ln]:async(r,n)=>{const i=Ee(r,["content"]),o=e.registry.resolveFile(i.target);pt(o.mode),await me(()=>o.write(oh(i.content),t(n)))},[or]:async(r,n)=>{const i=Ee(r),o=await me(()=>e.registry.resolveFile(i.target).stat(t(n)));return sh(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(bs(i),t(n)))},[sr]:async(r,n)=>{const i=Ee(r,["recursive"]);if(H(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 Ae(sr);await me(()=>o.handle.remove({recursive:i.recursive===void 0?!1:Tn(i.recursive,"recursive")},t(n)))},[hn]:async(r,n)=>{const i=Ee(r);return Os(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!H(o)||o.kind!=="directory")throw Ls()})},[mn]:async(r,n)=>{const i=Ee(r,["limit"]),o=ih(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 th(e){if(e===void 0)return{mode:"read",multiple:!1};H(e)||Me("pickFiles 参数必须是对象"),Yn(e,["mode","accept","multiple"]);const t=Hc(e.mode,"read"),r=e.multiple===void 0?!1:Tn(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)))&&Me("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function rh(e){return e===void 0?{mode:"read"}:(H(e)||Me("pickDirectory 参数必须是对象"),Yn(e,["mode"]),{mode:Hc(e.mode,"read")})}function nh(e){return H(e)||Me("saveFile 参数必须是对象"),Yn(e,["suggestedName"]),{suggestedName:yr(e.suggestedName,"suggestedName")}}function Ee(e,t=[]){return(!H(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Me("文件操作参数必须包含 target"),Yn(e,["target",...t]),e}function bs(e){return{recursive:e.recursive===void 0?!1:Tn(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Tn(e.exclusive,"exclusive")}}function Hc(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&Me("mode 必须是 read 或 readwrite"),e)}function Tn(e,t){return typeof e!="boolean"&&Me(`${t} 必须是布尔值`),e}function ih(e){if(e===void 0)return Ss;if((!Number.isSafeInteger(e)||e<=0)&&Me("limit 必须是正整数"),e>Ss)throw y("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Yn(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&Me(`不支持字段: ${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 Ae("files.external");return e}async function Os(e){try{return await e(),!0}catch(t){if(Xf.has(To(t)??""))return!1;throw cr(t)}}async function me(e){try{return await e()}catch(t){throw cr(t)}}function oh(e){return e instanceof Uint8Array||Me("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Me("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function _s(e){if(!(e instanceof Uint8Array))throw y("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Ls(){return y("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function sh(e){if(!H(e)||e.kind!=="file"||!ah(e.size))throw y("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!ch(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 ah(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ch(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Me(e){throw y("INVALID_PARAMS",e)}const Sr=4294967296;function dh(e){const t=new uh;return t.write(e),t.finish()}class uh{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<Sr?(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=lh(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<Sr)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/Sr),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Sr)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function lh(e){const t=new Uint8Array(fh(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 fh(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 Fc(e){Wi(e);const t=dh(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 Wi(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)Wi(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");Wi(s,t+1,r)}r.delete(e)}const hh=["pc","console","mobile"],mh=["game","wiki"];function Sn(e){throw{code:"INVALID_PARAMS",message:e}}function gh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ge(e,t){return typeof e!="string"||!e.trim()?Sn(t):e.trim()}function vs(e,t,r){return typeof e!="string"||!t.includes(e)?Sn(r):e}function ph(e){const t={target:"game_detail",appId:Ge(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:vs(e.gameType,hh,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=vs(e.page,mh,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Ge(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Ge(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function yh(e){return{target:"user_detail",userId:Ge(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Eh(e){const t={target:"post_detail",linkId:Ge(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Ge(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Ge(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Ih(e){const t={target:"mini_program",miniProgramId:Ge(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function wh(e){return gh(e)?e.target==="game_detail"?ph(e):e.target==="user_detail"?yh(e):e.target==="post_detail"?Eh(e):e.target==="mini_program"?Ih(e):Sn("navigation.openAppPage target 不支持"):Sn("navigation.openAppPage options 必须是对象")}function Mh(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 Nh(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Ah(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 Dh(e){const t=e;return t.target==="game_detail"?Mh(t):t.target==="user_detail"?Nh(t):Ah(t)}const Th="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",Sh="data-hb-sdk-fullscreen-exit",bh=3e3,Oh=2e3,Cs="var(--white-70a,rgba(255,255,255,.7))",Rs="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function _h(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(Sh,""),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 ${Cs}`,`box-shadow:${Rs}`,"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=Th,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let o=!0,s=!1,a=!1,c,d;function f(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function h(){o||(t.style.width=f())}function u(){d?.cancel(),d=void 0}function g(S=Oh){clearTimeout(c),c=setTimeout(()=>{u(),o=!1,t.style.width=f(),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")},S)}function T(){u(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Cs,t.style.boxShadow=Rs,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),g()}async function M(){if(!(s||a)){if(!o){T();return}a=!0,clearTimeout(c),u();try{await e()}catch{}finally{a=!1,s||T()}}}return t.addEventListener("click",M),window.addEventListener("resize",h),document.body.append(t),!r&&t.animate&&(d=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),g(bh),{dispose(){s=!0,clearTimeout(c),u(),t.removeEventListener("click",M),window.removeEventListener("resize",h),t.remove()}}}const Vc=1e4;function Bc(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 W(o,t.signal)}catch(s){throw r??s}},dispose(){clearTimeout(i),e.removeEventListener("abort",n)}}}function Qc(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 br(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function Lh(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??=_h(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",s,{once:!0});function c(u,g){if(t===u){if(t=void 0,clearTimeout(u.timer),e.operationContext.signal.removeEventListener("abort",d),"error"in g)u.controller.abort();else if(r={options:u.options,result:g.result},n=u.options,a(u.options),e.onApplied?.(u.options),g.result.supported&&!ai(i,u.options)){i={...u.options};try{e.onDisplayChange?.({orientation:i.mode,fullscreen:i.hideCapsule,source:u.source})}catch{}}for(const T of u.subscribers)T.dispose(),"error"in g?T.reject(g.error):T.resolve(g.result);u.subscribers.clear()}}function d(){t&&c(t,{error:br()})}function f(u,g){return new Promise((T,M)=>{const S=()=>{u.subscribers.delete(w),w.dispose(),M(br()),u.subscribers.size===0&&c(u,{error:br()})},w={resolve:T,reject:M,dispose:()=>g?.removeEventListener("abort",S)};u.subscribers.add(w),g?.addEventListener("abort",S,{once:!0}),g?.aborted&&S()})}const h={async apply(u,g,T="api"){if(ee(e.operationContext.signal),g?.aborted)throw br();const M=Qc(u),S=t?.options??n,w={mode:M.orientation??S.mode,hideCapsule:M.fullscreen??S.hideCapsule};w.mode==="landscape"&&(w.hideCapsule=!0);const _=e.presentation.applyOrientation;if(!_)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(t&&ai(t.options,w))return f(t,g);if(t&&c(t,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),r&&ai(r.options,w))return r.result;r=void 0;const A={options:w,source:T,controller:new AbortController,subscribers:new Set};t=A;const v=f(A,g);return e.operationContext.signal.addEventListener("abort",d,{once:!0}),g||(A.timer=setTimeout(()=>{c(A,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Vc)),W(()=>_.call(e.presentation,w,{...e.operationContext,signal:A.controller.signal}),A.controller.signal).then(U=>c(A,{result:U??{supported:!0}}),U=>c(A,{error:U})),v},dispose(){e.operationContext.signal.removeEventListener("abort",s),s()}};return h}function Yc(e){throw{code:"INVALID_PARAMS",message:e}}function Ps(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Yc(`${t} 不支持参数`)}function vh(e){return{[Mn]:async t=>{ee(e.operationContext.signal),Ps(t,"navigation.close"),await W(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Nn]:async t=>{ee(e.operationContext.signal),Ps(t,"navigation.reload"),await W(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[An]:async(t,r)=>{const n=at(e.operationContext,r?.signal);ee(n.signal);const i=wh(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Fc(i.extra)}catch{Yc("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=Bc(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}ee(n.signal),await W(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await W(()=>e.presentation.openAppPage(Dh(i),n),n.signal)}}}const Ch=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Rh=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Ph=new Set(["range","if-range","a-im"]),kh=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"]),xh=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Or={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class jh{constructor(t){this.signal=t}phase="initial";transition(t){if(Or[t]<=Or[this.phase])throw y("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Or[this.phase]<Or.committed&&this.signal.aborted)throw qc()}normalizeHostError(t,r){return this.throwIfCancelled(),bo(t,r,this.signal)}}async function zh(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Ae("network.download");const o=at(r.operationContext,t.signal),s=new jh(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Vh(e,i,o)}catch(f){throw s.normalizeHostError(f,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(f){throw s.normalizeHostError(f,"network")}let d=!1;try{s.throwIfCancelled(),s.transition("validate");const f=Qh(c);Yh(c,f);const h=Gh(c.status,f);if(e.maxBytes!==void 0&&h.expectedBytes!==void 0&&h.expectedBytes>e.maxBytes)throw y("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const u=Bh(e,a,f,i);let g=0;const T=Hh(h.expectedBytes,e.maxBytes);di(t,ci(0,h));const M={...o,onProgress(_){!Number.isSafeInteger(_)||_<g||T!==void 0&&_>T||(g=_,di(t,ci(g,h)))}};s.transition("transfer"),d=!0;let S;try{S=await n.files.writeResource(u.hostHandle,c.body,{mode:u.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...h.expectedBytes===void 0?{}:{expectedBytes:h.expectedBytes}},M)}catch(_){throw s.normalizeHostError(_,"transfer")}s.transition("committed"),g=Uh(S,h,g,e.maxBytes),di(t,ci(g,h));const w=i.describeFile(u.handle,u.ref);return s.transition("completed"),w}finally{d||Fh(n.network,c.body)}}function Uh(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 Hh(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Fh(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Vh(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return $i(i.handle.mode),await Xh(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return $i(n.handle.mode),await em(n.handle,r),{kind:"directory",...n}}function Bh(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Wh(e,r),o=n.deriveFile(t,i);return $i(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Qh(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(!H(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()||!Ch.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 Yh(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:Zh(t,Rh)});if((t["content-range"]?.length??0)>0)throw y("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Gh(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(d=>d!=="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=qh(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 qh(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 Wh(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=$h(i);if(o&&xr(o))return o}for(const i of r){const o=Kh(i);if(o&&xr(o))return o}if(e.suggestedName!==void 0)return So(e.suggestedName);const n=Jh(e.url);return n&&xr(n)?n:"download.bin"}function $h(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 Kh(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 Jh(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function So(e){try{yr(e,"suggestedName")}catch{throw y("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!xr(e))throw y("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function xr(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||xh.test(e))}function Zh(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Xh(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Gc()}catch(r){throw bo(r,"file",t.signal)}}async function em(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Gc()}catch(r){throw bo(r,"file",t.signal)}}function $i(e){if(e!=="readwrite")throw y("FILE_ACCESS_DENIED","下载目标只允许读取")}const tm={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 bo(e,t,r){if(r.aborted)return qc();const n=rm(e);if(n&&kh.has(n)){const o=y(n,tm[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 rm(e){return H(e)&&typeof e.code=="string"?e.code:void 0}function Gc(){return y("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function qc(){return y("DOWNLOAD_CANCELLED","下载已取消")}function nm(e){if(!e)return;const t=Object.keys(e).find(r=>Ph.has(r.trim().toLowerCase()));if(t)throw y("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const ks={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function im(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw Ae("network.upload");const o=at(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 d=0,f=!1;const h=u=>{f||o.signal.aborted||!Number.isSafeInteger(u)||u<d||u>c.size||(d=u,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:u,...g}=e,T=await n.upload(a,{...g,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:h});if(f=!0,!Number.isSafeInteger(T.uploadedBytes)||T.uploadedBytes<d||T.uploadedBytes>c.size)throw y("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(T.status>=200&&T.status<300&&T.uploadedBytes!==c.size)throw y("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:T.uploadedBytes,total:c.size,lengthComputable:!0}),T}catch(u){f=!0;const g=To(u);throw g&&ks[g]?y(g,ks[g]):o.signal.aborted?y("UPLOAD_CANCELLED","上传已取消"):g?.startsWith("FILE_")||g?.startsWith("DIRECTORY_")?cr(u):y("UPLOAD_NETWORK_FAILED","上传网络失败")}}const Oo="withCredentials",om=new Set(["url","method","params","data","headers","timeout",Oo]),sm=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Oo]),am=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),xs=3e4,Ki=2*1024*1024,cm=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Wc=/[\u0000-\u0008\u000A-\u001F\u007F]/,dm=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,um="network.request 不支持 multipart/form-data,请使用专用上传能力";function lm(e){const t=fm(e.runtimePermissions),r=Sm(e.allowedHttpOrigins);return{[on]:async(n,i)=>{const o=mm(n,{permission:t,allowedHttpOrigins:r}),s=await im(o,i,e),{uploadedBytes:a,...c}=s;return zs(c)},[nn]:async(n,i)=>{const o=gm(n,{permission:t,allowedHttpOrigins:r});return zh(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[rn]:async(n,i)=>{const o=at(e.operationContext,i?.signal);ee(o.signal);const s=hm(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await W(()=>e.network.request(s,o),o.signal)}catch(c){throw Om(c)?c:_m(c,"REQUEST_UNSUPPORTED")?V("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):V("REQUEST_FAILED","网络请求失败")}return zs(a)}}}function fm(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 hm(e,t){const r=bt(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!om.has(c));if(n.length>0)throw V("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);$c(r,"network.request");const i=_o(r,t,"network.request"),o=ym(r.method),s=r.data;s!==void 0&&wm(s),Nm(i.headers,s);const a=Am(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 mm(e,t){const r=bt(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(f=>!n.has(f)))throw V("INVALID_PARAMS","network.upload 包含不支持的字段");const i=_o(r,t,"network.upload");if(i.official)throw V("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw V("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!Bn(r.from))throw V("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw V("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw V("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw V("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(f=>r[f]!==void 0))throw V("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(f=>f.toLowerCase()==="content-type"))throw V("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=js(r.fieldName),c=r.fields===void 0?void 0:bt(r.fields,"fields 必须是字符串字典");for(const[f,h]of Object.entries(c??{}))if(js(f),typeof h!="string"||f===a)throw V("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw V("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||Wc.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw V("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:a,fields:c,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>Ki)throw V("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:So(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function js(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw V("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function gm(e,t){const r=bt(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!sm.has(c));if(n.length>0)throw V("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);$c(r,"network.download");const i=_o(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw V("INVALID_PARAMS","network.download timeout 必须是有限正数");nm(i.headers);const o=Bn(r.to),s=ic(r.to);if(!o&&!s)throw V("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw V("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw V("INVALID_PARAMS","suggestedName 必须是字符串");a=So(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw V("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw V("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 _o(e,t,r){const n=pm(e.url,t.allowedHttpOrigins,r),i=ol(n);if(i&&!t.permission.useOfficialDomain)throw V("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(il(n.pathname,i))throw V("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...bt(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Em(e.headers,r),timeout:Im(e.timeout,r)}}function pm(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw V("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw V("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw V("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw V("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw V("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function ym(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw V("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!am.has(t))throw V("INVALID_PARAMS","network.request method 不合法");return t}function Em(e,t="network.request"){const r=bt(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!cm.test(s)||typeof o!="string"||Wc.test(o))throw V("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(sl(s))throw V("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function $c(e,t){const r=e[Oo];if(r!==void 0&&typeof r!="boolean")throw V("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function Im(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw V("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>xs)throw V("INVALID_PARAMS",`${t} timeout 不能超过 ${xs}ms`);return e}}function wm(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw V("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Mm(e)>Ki)throw V("INVALID_PARAMS",`network.request data 不能超过 ${Ki} 字节`)}function Mm(e){if(typeof e=="string")return ui(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return ui(e.toString());try{const t=JSON.stringify(e);return t?ui(t):0}catch{throw V("INVALID_PARAMS","network.request data 必须可序列化")}}function Nm(e,t){const r=Kc(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 V("INVALID_PARAMS",um)}function Am(e,t,r){if(t===void 0)return;const n=Kc(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)||Tm(t))?"form":Dm(t)?"json":void 0}function Kc(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function Dm(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function Tm(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Sm(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&&bm(n.hostname)&&t.add(n.origin)}catch{}return t}function bm(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 zs(e){return Object.keys(e.headers).some(Us)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Us(t)))}:e}function Us(e){const t=e.trim().toLowerCase();return dm.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Om(e){return e instanceof Error&&e.name==="AbortError"}function _m(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function bt(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw V("INVALID_PARAMS",t);return e}function ui(e){return new TextEncoder().encode(e).length}function V(e,t){return{code:e,message:t}}function Lm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vm(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 Cm(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=vm(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function Rm(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 Jc(e,t){if(e==null)return{};if(!Lm(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=Cm(e.topicIds),n=Rm(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 Pm(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function km(e){try{if(Pm(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function ae(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()?ae(t):e}function xm(e,t){const r=Ji(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?ae(t):r}catch{return ae(t)}}function jm(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Zc(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return ae(`${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 ae(`${t} 缺少有效的小程序分享地址`)}}function zm(e,t){if(!Er(e))return ae("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return ae("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!jm(r))return ae("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:Zc(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:xm(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Xc(e,t){if(e!==void 0)try{return Fc(e)}catch{return ae(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function ed(e,t){return e.invalidMessage&&await W(()=>km(t.environment),t.operationContext.signal)?ae(e.invalidMessage):e.post}function Hs(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Um(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Hs(t.windowWidth,0),height:Hs(t.windowHeight,0)}}function Zi(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?ae(t):r}function Fs(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?ae(t):r}function Hm(e){return Er(e)?{left:Zi(e.left,"share.screenshot rect.left 必须是非负数字"),top:Zi(e.top,"share.screenshot rect.top 必须是非负数字"),width:Fs(e.width,"share.screenshot rect.width 必须是正数"),height:Fs(e.height,"share.screenshot rect.height 必须是正数")}:ae("share.screenshot rect 必须是对象")}function Fm(e,t){if(e!=null&&!Er(e))return ae("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?ae("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?ae("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?Um(t):Hm(r.rect),...r.delay===void 0?{}:{delay:Zi(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function Vm(e,t){ee(t.operationContext.signal);const r=zm(e,t);let n=Jc(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await ed(n,t);return W(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function Bm(e,t){if(ee(t.operationContext.signal),e!==void 0&&!Er(e))return ae("share.copyLink 参数必须是对象");const r=Xc(e?.extra,"share.copyLink"),n=Zc(t,"share.copyLink",r);return await W(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Qm(e,t,r){ee(t.operationContext.signal);const n=Jc(Er(e)?e.post:void 0,{method:"share.screenshot"}),i=await ed(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=Ym(),{watermarkTheme:a,...c}=r;let d=!1,f,h;try{d=!0,await W(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),f=await t.prepareScreenshot?.(r.rect,t.operationContext.signal,a),h={status:"fulfilled",value:await W(()=>t.presentation.captureAndShare({...c,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(g){h={status:"rejected",error:g}}finally{f?.()}const u=d?await Gm(t.presentation,s,t.operationContext.signal):void 0;if(h.status==="rejected")throw h.error;if(u)throw u;return h.value}function Ym(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function Gm(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await W(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function qm(e){let t=Promise.resolve();return{[Jr]:(r,n)=>Bm(r,e),[Zr]:(r,n)=>Vm(r,e),[Xr]:async(r,n)=>{const i=at(e.operationContext,n.signal);ee(i.signal);const o=Fm(r,e.presentation),s=t.then(()=>Qm(r,{...e,operationContext:i},o));return t=s.then(()=>{},()=>{}),W(()=>s,i.signal)}}}const Wm=128,$m=/^[A-Za-z0-9_-]+$/;function Km(e){const t=Jm(e);let r=Promise.resolve();const n=new Set,i=(s,a)=>{if(n.has(a))return Promise.resolve();const c=r.then(async()=>{const d=Pu(s),f=ku(await e.storage.getRaw(d,e.operationContext));if(f.forEach(h=>n.add(h)),!n.has(a)){if(f.length>=Go)throw xe("STORAGE_QUOTA_EXCEEDED",`storage key 数量超出 ${Go} 个上限`);f.push(a),await e.storage.setRaw(d,JSON.stringify(f),e.operationContext),n.add(a)}});return r=c.catch(()=>{}),c},o={[Xt]:async s=>{ee(e.operationContext.signal);const a=Vs(s,Xt,e.storageLimits?.maxKeyLength),c=await W(()=>e.storage.getRaw(li(t(),a),e.operationContext),e.operationContext.signal);return{data:Bs(c)}},[er]:async s=>{ee(e.operationContext.signal);const a=td(s,"storage.setStorage 参数必须是对象"),c=Vs(a,er,e.storageLimits?.maxKeyLength),d=Zm(a.data,e.storageLimits?.maxValueBytes),f=t();await W(()=>i(f,c),e.operationContext.signal),await W(()=>e.storage.setRaw(li(f,c),d,e.operationContext),e.operationContext.signal)}};return e.storageDiagnostics?{handlers:o,diagnostics:{getSnapshot:async()=>{ee(e.operationContext.signal);let s;try{s=t()}catch{throw xe("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const a=li(s,"");return(await W(()=>e.storageDiagnostics.listRaw(e.operationContext),e.operationContext.signal)).filter(d=>d.key.startsWith(a)).map(d=>{const f=d.value;return{area:d.area,key:d.key.slice(a.length),value:Bs(f),serializedValue:f,bytes:rd(f)}}).sort((d,f)=>d.key.localeCompare(f.key))}}}:{handlers:o}}function Jm(e){let t=!1,r;return()=>{if(!t){const n=e.identity.get()?.miniProgramId.trim();if(n)r=`id_${Qs(n)}`;else{const i=e.anonymousStorageScope?.trim();i&&(r=`anon_${Qs(i)}`)}t=r!==void 0}if(!r)throw xe("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return r}}function li(e,t){return Ru(e,t)}function Vs(e,t,r=Wm){const i=td(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw xe("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!$m.test(i))throw xe("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function Zm(e,t){let r;try{r=JSON.stringify(e)}catch{throw xe("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw xe("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&rd(r)>t)throw xe("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Bs(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function td(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw xe("INVALID_PARAMS",t);return e}function Qs(e){return Cu(e)}function rd(e){return new TextEncoder().encode(e).length}function xe(e,t){return{code:e,message:t}}const Ys=120;function Ve(e){throw{code:"INVALID_PARAMS",message:e}}function Lo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nd(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Ve(`${r} 不支持字段: ${n.join(", ")}`)}function Xm(e){if(!Lo(e))return Ve("ui.showToast 参数必须是对象");if(nd(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>Ys)return Ve(`ui.showToast message 不能超过 ${Ys} 字符`);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 eg(e){return e===void 0?{dismissible:!1}:Lo(e)?(nd(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Ve("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Ve("ui.showLoading 参数必须是对象")}function tg(e){e!==void 0&&(!Lo(e)||Object.keys(e).length)&&Ve("ui.hideLoading 不支持参数")}function rg(e){return{[gn]:async t=>{ee(e.operationContext.signal),await W(()=>e.presentation.showToast(Xm(t),e.operationContext),e.operationContext.signal)},[pn]:async t=>{ee(e.operationContext.signal),await W(()=>e.presentation.showLoading(eg(t),e.operationContext),e.operationContext.signal)},[yn]:async t=>{ee(e.operationContext.signal),tg(t),await W(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const ng={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ye(e,"当前用户首页资料接口响应异常")}},ig=3e4;function og(e,t,r={}){const n=r.ttlMs??ig,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function d(){let h;try{h=await Qn(e,ng,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 pr?y("INVALID_RESPONSE","user home_v2 响应不合法"):u instanceof St?y("REQUEST_FAILED","user home_v2 请求失败"):u instanceof Tt?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):ag(u)?u:y("REQUEST_FAILED","user home_v2 请求失败")}return sg(h,"user home_v2")}function f(h){const u=Date.now();if(a?.userId===h&&a.expiresAt>u)return Promise.resolve(a.value);if(c?.userId===h&&c.generation===s)return c.promise;const g=s,T=d().then(M=>(s===g&&(a={userId:h,value:M,expiresAt:Date.now()+n}),M)).finally(()=>{c?.promise===T&&(c=void 0)});return c={userId:h,generation:g,promise:T},T}return{get:f,clear(){s+=1,a=void 0,c=void 0}}}function sg(e,t){if(!H(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(!H(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function ag(e){return H(e)&&typeof e.code=="string"&&typeof e.message=="string"}const cg={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 dg(e,t=Vi){const r=cl({version:"1",validate:lg}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):Vi,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 Gs(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 ug(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 lg(e){if(!H(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 Xe();for(const t of e.gameList){if(!H(t)||!Xi(t.appid)||!Xi(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Xe();for(const r of["image","icon"])qs(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 Xe();if(t.price!==void 0){if(!H(t.price))throw Xe();for(const r of["current","initial","deadlineDate"])qs(t.price,r);for(const r of["discount","lowestPrice","deadlineTimestamp"])fi(t.price,r)}}return e}function Xi(e){return typeof e=="number"&&Number.isFinite(e)}function fi(e,t){if(e[t]!==void 0&&!Xi(e[t]))throw Xe()}function qs(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Xe()}function Xe(){return y("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const id=20,fg=100,hg=128,od=0,sd="weeks",mg=100,gg=new Set(["weeks","all","achieved"]);function pg(){return{nickname:"",avatar:""}}function yg(e){const t=og(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??hc(),i=dg(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(l,p){const m=JSON.stringify([l,p]);return(!o||o.key!==m)&&(o={key:m,scope:n.createScope(p,n.createScope(l))}),o.scope}function d(){const l=o;o=void 0,l&&n.invalidateScope(l.scope).catch(()=>{}),s.clear()}const f=Dc({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??Nc))}),h=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let u=0,g=!1;const T=e.account.onChange(()=>{u+=1,t.clear(),f.invalidate(),d()}),M=e.authorization.onEvent((l,p)=>{l==="user_info_authorization_change"&&Object.values(p).some(m=>m==="denied")&&(u+=1,t.clear(),f.invalidate(),d(),a=a.then(async()=>{if(g)return;const m=await e.account.getCurrentUserId(e.operationContext);typeof m=="string"&&m.trim()&&await n.invalidateScope(c(w(),m.trim()))}).catch(()=>{}))});function S(){if(g||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function w(){const l=e.identity.get()?.miniProgramId?.trim();if(!l)throw y("INVALID_STATE","用户能力缺少 canonical 小程序身份");return l}async function _(){S(),await a,S();let l;try{l=await e.account.getCurrentUserId(e.operationContext)}catch(p){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):$s(p)?p:y("REQUEST_FAILED","读取小黑盒账号失败")}return typeof l=="string"&&l.trim()?l.trim():void 0}async function A(l,p){const m=await _();if(u!==p||m!==l)throw y("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function v(l,p,m=e.operationContext.signal){try{return await Qn(e.network,l,p,{...e.operationContext,signal:m,credentials:"heybox-session",...h?{gate:h}:{}})}catch(E){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):E instanceof se?y("REQUEST_UNSUPPORTED",E.message):E instanceof pr?y("INVALID_RESPONSE","用户接口响应不合法"):E instanceof St?y("REQUEST_FAILED","用户请求失败"):E instanceof Tt?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):$s(E)?E:y("REQUEST_FAILED","用户请求失败")}}async function U(){w();const l=u,p=await _();if(!p)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[m,E]=await Promise.all([e.authorization.getOrCreateLocalIdentity(p),L(p).catch(()=>pg())]);return await A(p,l),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:m.appUserId,profile:E,...m.steamId?{steam_id:m.steamId}:{}}}}function L(l){return f.read(l,()=>v(Ac,void 0).then(p=>{const m=Ws(p,"账号基础信息");if(m.display_username!==void 0&&typeof m.display_username!="string")throw y("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(m.display_avatar!==void 0&&typeof m.display_avatar!="string")throw y("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:m.display_username??"",avatar:m.display_avatar??""}}))}async function N(l){const p=Eg(l),m=w(),E=u,I=await _();if(!I)return d(),{isLogin:!1,isBound:!1,data:null};const D=await t.get(I);await A(I,E);const C=vo(D.steam_id_info);if(Object.keys(C).length===0)return await n.invalidateScope(c(m,I)).catch(()=>{}),await A(I,E),s.delete(JSON.stringify([m,I])),{isLogin:!0,isBound:!1,data:null};const F=JSON.stringify([m,I]),R=c(m,I),O=Gs({...p,steamId:void 0},C),P=ad(C.personal_infomation_open??C.personal_information_open),b=JSON.stringify([O??null,P??null]),x=s.get(F);x&&x.identity!==b&&(await n.invalidateScope(R).catch(()=>{}),await A(I,E));const j={identity:b,scope:n.createScope(b,R)};s.set(F,j);const z=Gs(p,C),B=z?i.persistent:i.unresolved,Q=n.createScope(z??"unresolved",j.scope),G=async()=>{if(await A(I,E),w()!==m||s.get(F)?.identity!==b)throw y("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},te=await B.read({scope:Q,key:ug({miniProgramId:m,userId:I,effectiveSteamId:z,personalInformationOpen:P,query:p}),signal:e.operationContext.signal,load:async X=>{const Z=await v(cg,{userId:I,...p,personalInformationOpen:P},X);return await G(),Ag(Ws(Z,"Steam 游戏库"),p)}}).catch(async X=>{throw await G(),X});return await G(),{isLogin:!0,isBound:!0,data:te}}return{getInfo:U,getSteamGameList:N,async invalidateSteamGameListCache(){const l=w(),p=u,m=await _();if(!m)return;const E=c(l,m);await Promise.all([i.persistent.invalidateScope(E),i.unresolved.invalidateScope(E)]),t.clear(),s.delete(JSON.stringify([l,m])),await A(m,p)},dispose(){g||(g=!0,u+=1,T(),M(),t.clear(),f.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function Eg(e){if(e==null)return{limit:id,offset:od,sort:sd,includeHidden:!1};if(!H(e))throw Be("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Be(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Ig(e.limit),offset:wg(e.offset),sort:Mg(e.sort),includeHidden:Ng(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>hg)throw Be("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Be("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,mg))}return r}function Ig(e){if(e===void 0)return id;if(!Number.isInteger(e)||Number(e)<1)throw Be("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),fg)}function wg(e){if(e===void 0)return od;if(!Number.isInteger(e)||Number(e)<0)throw Be("user.getSteamGameList offset 必须是非负整数");return Number(e)}function Mg(e){if(e===void 0)return sd;if(typeof e!="string"||!gg.has(e))throw Be("user.getSteamGameList sort 不支持");return e}function Ng(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Be("user.getSteamGameList includeHidden 必须是 boolean");return e}function Ag(e,t){if(!Array.isArray(e.game_list))throw y("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(Dg).filter(a=>a!==void 0),n=bn(e.total),i=t.offset+r.length,o={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(o.total=n,o.hasMore=i<n);const s=ad(e.is_me);return s!==void 0&&(o.isMe=s),o}function Dg(e){const t=vo(e),r=bn(t.appid),n=bn(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};qt(o,"image",t.image),qt(o,"icon",t.appicon??t.icon),Wt(o,"playtimeForever",t.playtime_forever),Wt(o,"playtime2Weeks",t.playtime_2weeks);const s=Sg(t.external_tags??t.tags);s.length&&(o.tags=s);const a=Tg(t.price);return a&&(o.price=a),o}function Tg(e){const t=vo(e),r={};return qt(r,"current",t.current),qt(r,"initial",t.initial),Wt(r,"discount",t.discount),Wt(r,"lowestPrice",t.lowest_price),qt(r,"deadlineDate",t.deadline_date),Wt(r,"deadlineTimestamp",t.deadline_timestamp),Object.keys(r).length?r:void 0}function Ws(e,t){if(!H(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(!H(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function vo(e){return H(e)?e:{}}function Co(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Sg(e){return Array.isArray(e)?e.map(Co).filter(Boolean):[]}function bn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function ad(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function qt(e,t,r){const n=Co(r);n&&Object.assign(e,{[t]:n})}function Wt(e,t,r){const n=bn(r);n!==void 0&&Object.assign(e,{[t]:n})}function Be(e){return y("INVALID_PARAMS",e)}function $s(e){return H(e)&&typeof e.code=="string"&&typeof e.message=="string"}function bg(e){return{[Wr]:async t=>(Ks(t,"user.getInfo"),e.user.getInfo()),[$r]:async(t,r)=>{Ks(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Kr]:async t=>e.user.getSteamGameList(t)}}function Ks(e,t){if(e!==void 0)throw y("INVALID_PARAMS",`${t} 不接收入参`)}function Js(e){throw{code:"INVALID_PARAMS",message:e}}function jt(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function cd(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function _r(e,t,r){return Math.min(cd(e,t),r)}async function Og(e){try{return cd(await e.getNavigationBarHeight(),0)}catch{return 0}}function _g(e,t,r,n){const i=_r(e.safeArea?.left,0,t),o=Math.max(i,_r(e.safeArea?.right,t,t)),s=_r(e.safeArea?.top,n,r),a=Math.max(s,_r(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Zs(e){const t=e.getViewportMetrics(),r=jt(t.windowWidth,0),n=jt(t.windowHeight,0),i=await Og(e);return{pixelRatio:jt(t.pixelRatio,1),screenWidth:jt(t.screenWidth,r),screenHeight:jt(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:_g(t,r,n,i),screenTop:i}}function Lg(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 h=++i;Zs(r.presentation).then(u=>{if(n||r.operationContext.signal.aborted||h!==i)return;const g=JSON.stringify(u);g!==o&&(o=g,r.onViewportChange?.(u))}).catch(()=>{})},c=Lh({...r,onApplied:a}),d=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?d():(s=r.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[ot]:async(h,u)=>c.apply(h,u?.signal),[en]:async()=>(ee(r.operationContext.signal),Zs(r.presentation)),[tn]:async h=>{if(ee(r.operationContext.signal),typeof h!="object"||h===null||Array.isArray(h))return Js("viewport.setNavigationBarStyle 参数必须是对象");const u=h.foregroundStyle;if(u!=="light"&&u!=="dark")return Js("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await W(()=>r.presentation.setNavigationBarStyle(u,e.operationContext),r.operationContext.signal)}},applyOrientation:(h,u)=>c.apply({orientation:h.mode,fullscreen:h.hideCapsule},u),notifyChange:()=>{o=void 0,a()},dispose:d}}const vg=new Map(Ye.map(e=>[e.method,e]));function Vt(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function Cg(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 Rg(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=f=>{a||(a=!0,n.removeEventListener("abort",d),f())},d=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",d,{once:!0}),i.then(f=>c(()=>o({status:"handled",value:f})),f=>c(()=>s(f)))})}function Pg(e){const t=Cg(e.runtimePermissions),r=Je(e.runtimePermissions);let n=0,i=0,o=0;return{async dispatch(s,a,c){const d=e.now??kg,f=e.onTrace?d():0,h=e.onTrace?`cap_${++n}`:"",u=s===ot?++i:void 0;let g;try{if(e.terminalSignal.aborted)throw Vt("RUNTIME_DESTROYED","小程序 Runtime 已终止");ju(s,e.effectiveCapabilities);const T=vg.get(s);if(!T)throw new Error(`Capability method ${s} 缺少 protocol metadata`);const M=t(T),S=!M.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(s,a)===!0;if(!M.allowed&&!S)throw Vt(M.code,M.message,M.data);const w=e.handlers[s];if(!w)throw new Error(`Capability method ${s} 缺少 handler`);u!==void 0&&(g=Bc(c.signal));const _=g?{...c,signal:g.signal}:c,A=async()=>{for(const U of e.policies??[]){const L=await U.evaluate({method:s,payload:a,capability:T});if(e.terminalSignal.aborted||g?.signal.aborted)throw ta();if(!L.allowed)throw Vt(L.code,L.message,L.data)}if(e.terminalSignal.aborted||g?.signal.aborted)throw ta();if(u!==void 0){if(Qc(a),u<o)throw Vt("ORIENTATION_SUPERSEDED","方向设置已被后续设置替换");o=u}return w(a,_)},v=await Rg(()=>g?g.run(A):A(),void 0,c,e.terminalSignal);return Xs(e.onTrace,ea(h,s,a,f,v),d),v}catch(T){throw Xs(e.onTrace,ea(h,s,a,f,{status:"error",error:T}),d),T}finally{g?.dispose()}}}}function kg(){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 ea(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:xg(i.error)}:{},...jg(t,r,i)}}function xg(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function jg(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"&&dd(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 dd(e){return typeof e=="object"&&e!==null}function ta(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function zg(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=Al(e.requestPolicy);let n;if(e.files)try{n=hl(e.files,t)}catch{}const i=hc({store:n}),o=e.onRequestPolicyReport??(r.debugReport?Ug:void 0),s=r.enabled?Il({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Gf(e.files,e.miniProgramDetail),c=eh({registry:a,picker:e.picker,operationContext:t}),d=Wl({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 f,h,u,g=()=>{},T=()=>{};try{f=Lg({operationContext:t,presentation:e.hostPresentation,onDisplayChange:L=>e.eventSink.postEvent("display_change",L),onViewportChange:L=>e.eventSink.postEvent("viewport_change",L)}),h=yg({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:d,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:s,requestPolicyEnabled:r.enabled}),g=d.onEvent((L,N)=>e.eventSink.postEvent(L,N)),T=e.hostCompanion?.onSessionEvent?.(L=>{const N=Uf(L);!e.terminalSignal.aborted&&N&&e.eventSink.postEvent(N.type,N.payload)})??(()=>{}),u=Df({account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const M=Km({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),S=[{name:"auth",handlers:nf({authorization:d})},{name:"user",handlers:bg({user:h,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode})},{name:"share",handlers:qm({prepareScreenshot:e.prepareScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:f.handlers},{name:"storage",handlers:M.handlers},{name:"network",handlers:lm({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"workspaceCards",handlers:{[Gr]:async()=>{throw Vt("CAPABILITY_UNAVAILABLE","当前 Runtime 不支持工作区卡片刷新")}}},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"ui",handlers:rg({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Bf({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:vh({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:L=>f.applyOrientation({mode:"portrait",hideCapsule:!1},L)}:{}})},{name:"cloud",handlers:u.handlers},{name:"companion",handlers:Pf({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],w=Hg(S);let _=!1;const A=()=>{_||(_=!0,e.terminalSignal.removeEventListener("abort",A),f?.dispose(),u?.dispose(),g(),T(),h?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?A():e.terminalSignal.addEventListener("abort",A,{once:!0});const v=new Set(["file.readText","file.readBytes","file.stat"]);return{modules:S,handlers:w,allowsCompanionAttachmentAccess:(L,N)=>v.has(L)&&dd(N)&&a.isCompanionAttachmentRef(N.target),applyOrientation:f.applyOrientation,notifyViewportChange:f.notifyChange,...M.diagnostics?{storageDiagnostics:M.diagnostics}:{},dispose:A}}catch(M){throw f?.dispose(),u?.dispose(),g(),T(),h?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),M}}function Ug(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Hg(e){const t=new Map(Ye.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[o,s]of Object.entries(i.handlers)){const a=o,c=t.get(a);if(!c)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${a}`);if(c!==i.name)throw new Error(`Capability method ${a} 应由 ${c} 拥有,不能注册到 ${i.name}`);if(r.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);r.set(a,s)}const n=Ye.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Ye.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Fg="heybox-mini-dev:";function ra(e){try{return Vg(new URL(e))}catch{return!1}}function Vg(e){return e.protocol===Fg}function Bg(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Qg(e)}function Qg(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 Yg=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Gg(e,t){const r=[],n=qg(e.environmentInfo,r),i=jr(n?.appVersion,"host.appVersion",r),o=$g(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:Wg(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:jr(t.miniProgramId),version:jr(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function qg(e,t){if(e!=null){if(ud(e))return e;t.push("environmentInfo")}}function Wg(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function $g(e,t){if(e==null)return{name:"unknown",version:null};if(!ud(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=Yg.has(e.name)?e.name:"unknown";return r==="unknown"&&e.name!==void 0&&e.name!==null&&e.name!=="unknown"&&t.push("operatingSystem.name"),{name:r,version:jr(e.version,"operatingSystem.version",t)}}function jr(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function ud(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Kg="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",Jg="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",Zg="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",Xg="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function ep(e,t,r,n,i="dark"){ee(n);const o=e.defaultView;if(!o||!e.body)throw new Error("截图水印缺少可用的展示窗口");const s=e.createElement("div"),a=i==="light",c=a?"black":"white";s.dataset.miniProgramScreenshotWatermark="",s.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);s.style.cssText=`position:fixed;left:${r.left}px;top:${r.top+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const f=e.createElement("div");f.style.cssText=`display:flex;flex-direction:column;align-items:center;width:${r.width/d}px;height:57px;transform:scale(${d});transform-origin:top left;font-family:"PingFang SC",sans-serif;`;const h=e.createElement("div");h.style.cssText="display:flex;align-items:center;max-width:calc(100% - 24px);height:22px;flex-shrink:0;";const u=e.createElement("img");u.src=a?Zg:Kg,u.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const g=e.createElement("div");g.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${c};border-radius:11px;padding:0 7px 0 6px;`;const T=e.createElement("img");T.src=a?Xg:Jg,T.style.cssText="width:12px;height:12px;flex-shrink:0;";const M=e.createElement("span");M.textContent=t?.trim()||"小程序工坊",M.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const S=e.createElement("div");S.textContent="小黑盒工坊小程序",S.style.cssText=`margin-top:6px;color:${a?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,g.append(T,M),h.append(u,g),f.append(h,S),s.append(f),e.body.append(s);const w=()=>{s.remove(),n.removeEventListener("abort",w)};n.addEventListener("abort",w,{once:!0});try{return await W(()=>Promise.all([u.decode(),T.decode()]),n),await W(()=>new Promise(_=>{let A=o.requestAnimationFrame(()=>{A=o.requestAnimationFrame(()=>{n.removeEventListener("abort",v),_()})});const v=()=>o.cancelAnimationFrame(A);n.addEventListener("abort",v,{once:!0})}),n),w}catch(_){throw w(),_}}const tp=1,ld="allow-scripts allow-same-origin",rp="",np="no-referrer";function ip(e=ld){return!e.split(/\s+/).includes("allow-same-origin")}function na(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const op=new Set(["javascript:","data:","blob:","file:"]),ia="xiaoheihe.cn";function sp(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(op.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!lp(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function ap(e,t){const r=new URL(e);return r.searchParams.set(cu,t),r.toString()}function cp(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=dp(r)??up(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function dp(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function up(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function oa(e){const t=new URL(e);return Ro(t)?"loopback":Po(t)?"lan":"production"}function lp(e,t,r){return fp(e)||Ro(e)||Po(e)&&mp(t,r)}function fp(e){return e.protocol==="https:"&&yp(e.hostname)}function Ro(e){return e.protocol==="http:"&&hp(e.hostname)}function hp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Po(e){return e.protocol==="http:"&&gp(e.hostname)}function mp(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Ro(r)||Po(r)}catch{return!1}}function gp(e){const t=pp(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function pp(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 yp(e){return e===ia||e.endsWith(`.${ia}`)}const Ep=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"]),Ip=new Set(["url","inline","eval","unknown"]),wp=/^\/(?:\:segment(?:\/\:segment)*)?$/,Mp=/^[a-f0-9]{64}$/,Np=255,Ap=160,Dp=256;function Tp(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!Ep.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>Dp||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Ip.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=Sp(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>Ap||!wp.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Mp.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 Sp(e){if(e!==void 0&&!(typeof e!="string"||e.length>Np))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const bp=/^(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 Op(e){if(!e?.minimumSdkVersion)throw $("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=tt(e.minimumSdkVersion),r=e.sdkVersion?tt(e.sdkVersion):void 0;if(!t)throw $("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw $("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=tt("0.6.0");if(!r){if(zr(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw $("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0)throw $("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(zr(r,t)<0)throw $("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:zr(r,tt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function _p(e,t){if(typeof t!="string"||!tt(t))throw $("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw $("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function fd(e,t){const r=tt(e),n=tt(t);if(!(!r||!n))return zr(r,n)}function tt(e){const t=bp.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(r=>/^\d+$/.test(r)?Number(r):r)??[]}}function zr(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],o=t.prerelease[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const Gn=["android","ios","ohos","windows","macos","linux"],Lp="0.9.0",vp=Object.freeze(["android","ios","ohos","windows","macos"]),hd="该小程序暂不支持当前平台",Cp="PLATFORM_UNSUPPORTED";function Rp(e){return typeof e=="string"&&Gn.includes(e)}function Pp(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 kp(e){const t=e.manifest;if(!Hp(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=aa(e.sdkVersion)??aa(t.sdkVersion);return zp(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:jp()}const r=md(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function xp(e){const t=Pp(e.operatingSystemName);if(!t)return It("host_operating_system_unknown");const r=e.platformAccess;if(!r)return It("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Gn,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=kp({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?It("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):sa(t,s)}if(r.effectivePlatforms===void 0)return It("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=md(r.effectivePlatforms);if("reason"in n)return It("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=Up(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return sa(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function sa(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:It("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function It(e,t={}){return{status:"denied",reason:e,message:hd,...t}}function jp(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:vp,platformsDeclared:!1,policy:"legacy_mobile_default"}}function md(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(!Rp(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Gn.filter(r=>t.has(r)))}}function zp(e){if(typeof e!="string"||!e.trim())return!1;const t=fd(e.trim(),Lp);return t!==void 0&&t>=0}function aa(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Up(e){return e==="explicit"||e==="legacy_mobile_default"}function Hp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Fp=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 Vp(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:Bp(i.pathname),sanitizedPathnameHash:Qp(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function Bp(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function Qp(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 S=0;S<16;S+=1)o[S]=s.getUint32(a+S*4,!1);for(let S=16;S<64;S+=1){const w=o[S-15],_=o[S-2],A=be(w,7)^be(w,18)^w>>>3,v=be(_,17)^be(_,19)^_>>>10;o[S]=o[S-16]+A+o[S-7]+v>>>0}let[c,d,f,h,u,g,T,M]=i;for(let S=0;S<64;S+=1){const w=M+(be(u,6)^be(u,11)^be(u,25))+(u&g^~u&T)+Fp[S]+o[S]>>>0,_=(be(c,2)^be(c,13)^be(c,22))+(c&d^c&f^d&f);M=T,T=g,g=u,u=h+w>>>0,h=f,f=d,d=c,c=w+_>>>0}[c,d,f,h,u,g,T,M].forEach((S,w)=>{i[w]=i[w]+S>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function be(e,t){return e>>>t|e<<32-t}const Yp=1e4,hi=2e3,Gp=2,qp="open-with-native-credential-policy",gd="安全提示",pd="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class Wp{nonce=na();runtimeId=na();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=fc(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??Yp,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??$("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??$("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(ny(),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=$("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=Op(t.sdkVersionPolicy);const r=Gg(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=xp({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw sy(this.platformGateDecision);if(this.miniProgramDetail=ay(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),Zp(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(ey(n)),this.launchUrl=n,this.miniProgramSrc=ap(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=Io(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,ze(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&(n!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(n!=="display_change"||this.effectiveCapabilities[ot])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=zg({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,prepareScreenshot:(n,i,o)=>{const s=this.sdkVersionDecision?.sdkVersion;return!s||(fd(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):ep(this.iframe.ownerDocument,this.miniProgramPresentation?.name,n,i,o)},miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins,requestPolicy:this.options.requestPolicy,...this.options.onRequestPolicyReport?{onRequestPolicyReport:this.options.onRequestPolicyReport}:{}});const r=Pg({handlers:this.capabilityGraph.handlers,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:f})=>{const h={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...f?{network:f}:{}};ze(this.options.onCapabilityTrace,h)}}:{}});this.bridgeServer=new _u({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($("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 Jp(t)?t:yd($("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 sp(t,r,{allowPrivateNetwork:ra(r)||ca(r)||await this.isDevRuntime()})}catch(r){throw $("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??ry)({message:pd,title:gd,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(oa(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!ra(r)&&!ca(r)}async closeAfterDevLaunchCancellation(){const t=$("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{da(),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(()=>da())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",rp),this.iframe.setAttribute("referrerpolicy",np),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(),ze(this.options.onReady,t)}completeCompatibilityLaunch(){if(this.stateValue!=="starting"||this.isInactive()||this.readyContext)return;this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:"bridge_ready"}),this.setState("ready"),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),ze(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{_p(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($("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>=Gp)){this.failRuntime($("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Mr,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:Mr})}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(Mr,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Mr})}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($("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===uu){this.handleCspViolation(t.payload);return}if(t.method!==du)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime($("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!cp(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime($("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=Tp(t,this.sdkVersionDecision?.sdkVersion);r&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:r.timestamp,sdkVersion:r.sdkVersion,origin:r.origin,sanitizedPathname:r.sanitizedPathname,sanitizedPathnameHash:r.sanitizedPathnameHash,effectiveDirective:r.effectiveDirective,violatedDirective:r.violatedDirective,blockedResourceType:r.blockedResourceType})}emitSecurityViolation(t){ze(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=Vp(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($("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:tp,launchUrlType:oa(t),networkPolicy:qp})}failRuntime(t){const r=$p(t);return this.isInactive()||(this.terminalError=r,this.terminalController.abort(r),this.postBridgeError(r),this.disposeRuntimeResources(),this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),this.setState("failed"),this.teardownIframe(r),ze(this.options.onError,Kp(r)),this.rejectReady?.(r)),r}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0,this.clearHandshakeTimeout(),this.clearHeartbeat(),this.clearUnexpectedDocumentLoadFailure(),this.clearDocumentRevalidation(),this.destroyBridgeServer(),this.capabilityGraph?.dispose(),this.capabilityGraph=void 0,this.clearLifecycleDisposer(),this.removeIframeListeners();try{this.options.dispose?.()}catch{}}}teardownIframe(t){if(!this.iframeTornDown){this.iframeTornDown=!0;try{this.options.teardownIframe?this.options.teardownIframe(this.iframe,t):this.iframe.remove()}catch{}}}setStatus(t){this.status!==t&&(this.status=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:t}))}setState(t){this.stateValue!==t&&(this.stateValue=t,ze(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){ze(this.options.onTrace,{...t,runtimeId:this.runtimeId,...this.identity})}createLaunchContext(){return{launchUrl:this.launchUrl,src:this.miniProgramSrc,sdkVersion:this.sdkVersionDecision?.sdkVersion,heartbeatEnabled:!!this.sdkVersionDecision?.heartbeatEnabled,...this.identity}}createReadyContext(){return this.readyContext??this.createLaunchContext()}}function $p(e){const t=Io(e);return On(e)&&"cause"in e&&yd(t,e.cause),t}function yd(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function Kp(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function Jp(e){return On(e)&&typeof e.code=="string"&&typeof e.message=="string"}function On(e){return!!e&&typeof e=="object"}function ze(e,t){try{e?.(t)}catch{}}function Zp(e,t,r){try{e?.(t,r)}catch{}}function ca(e){try{const t=new URL(e);return t.protocol==="http:"&&Bg(t.hostname)}catch{return!1}}function Xp(e){try{return new URL(e).origin}catch{return}}function ey(e){return ip()?"*":Xp(e)}function ty(e){return`${gd}
2
2
 
3
- ${gd}
3
+ ${pd}
4
4
 
5
- URL: ${e}`}function ry(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(ty(e.url))}function da(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function ny(){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:ec,knownMethodCount:Ye.length,supportsFileCreate:Ye.some(i=>i.method===tr),system:iy(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:yt(e?.hardwareConcurrency),maxTouchPoints:yt(e?.maxTouchPoints),screen:{width:yt(t?.width),height:yt(t?.height)},viewport:{width:yt(r?.innerWidth),height:yt(r?.innerHeight),devicePixelRatio:oy(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function iy(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 yt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function oy(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function sy(e){return $(Cp,fd,{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 ay(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 cy(e){if(!On(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!On(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 Wp(e)}const dy=/^(?: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,uy=new Set(["origin","referer","user-agent"]);function ly(e,t){return Uu({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=fy(r),a=await e.authenticatedRequest(s,o);return gy(a)})}).network}function fy(e){const t=hy(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function hy(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!my(t)))}function my(e){const t=e.trim().toLowerCase();return uy.has(t)}function gy(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:py(e.headers)??{}}}function py(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!yy(t)))}function yy(e){const t=e.trim().toLowerCase();return dy.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Ey(e,t,r){const n=Ay(e.presentation,t);return{account:My(e,t,r),network:ly(e,t),...e.storage===void 0?{}:{storage:Ny(e,t)},...e.storage===void 0?{}:Iy(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function Iy(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 wy(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 My(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 Ny(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 Ay(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)=>Ju(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 Dy(){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 Lr(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(f=>f.aborted);if(i)throw Lr(i.reason);const o=new AbortController;let s;const a=new Promise((f,h)=>{s=h}),c=n.map(f=>{const h=()=>{o.signal.aborted||o.abort(f.reason),s(Lr(f.reason))};return f.addEventListener("abort",h,{once:!0}),{listener:h,source:f}});let d;try{d=Promise.resolve(r(o.signal))}catch(f){d=Promise.reject(f)}try{const f=await Promise.race([d,a]),h=n.find(u=>u.aborted);if(h)throw Lr(h.reason);return f}finally{for(const{listener:f,source:h}of c)h.removeEventListener("abort",f)}}}}function Lr(e){return new DOMException("Web Host operation aborted","AbortError")}async function Ty(e){const t=Dy(),r=new Set;let n=!1;const i=h=>{if(n||t.signal.aborted)return mi(h),()=>{};let u=!0;const g=()=>{u&&(u=!1,r.delete(g),mi(h))};return r.add(g),g},o=()=>s(e.signal.reason),s=h=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(h);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=Ey(e,t,i),c=fc(a,{hostCapabilities:e.hostCapabilities}),d=wy(e,t);let f;return{platform:"web",ports:a,environment:d,resolveLaunch:()=>(f??=t.run(void 0,async h=>e.resolveLaunch(h)),f),...e.authPresentation===void 0?{}:{authPresentation:Sy(e.authPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function mi(e){try{e()}catch{}}function Sy(e,t){return{confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var Et={},gi,ua;function by(){return ua||(ua=1,gi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),gi}var pi={},Ue={},la;function ct(){if(la)return Ue;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 Ue.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},Ue.getSymbolTotalCodewords=function(n){return t[n]},Ue.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Ue.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Ue.isKanjiModeEnabled=function(){return typeof e<"u"},Ue.toSJIS=function(n){return e(n)},Ue}var yi={},fa;function ko(){return fa||(fa=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,ha;function Oy(){if(ha)return Ei;ha=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 Ii,ma;function _y(){if(ma)return Ii;ma=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]},Ii=e,Ii}var wi={},ga;function Ly(){return ga||(ga=1,(function(e){const t=ct().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}})(wi)),wi}var Mi={},pa;function vy(){if(pa)return Mi;pa=1;const e=ct().getSymbolSize,t=7;return Mi.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},Mi}var Ni={},ya;function Cy(){return ya||(ya=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,d=null,f=null;for(let h=0;h<o;h++){a=c=0,d=f=null;for(let u=0;u<o;u++){let g=i.get(h,u);g===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=g,a=1),g=i.get(u,h),g===f?c++:(c>=5&&(s+=t.N1+(c-5)),f=g,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const d=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(d===4||d===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let d=0;d<o;d++){a=c=0;for(let f=0;f<o;f++)a=a<<1&2047|i.get(d,f),f>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(f,d),f>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let d=0;d<s;d++){o(d),e.applyMask(d,i);const f=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(d,i),f<c&&(c=f,a=d)}return a}})(Ni)),Ni}var vr={},Ea;function yd(){if(Ea)return vr;Ea=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 vr.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}},vr.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}},vr}var Ai={},zt={},Ia;function Ry(){if(Ia)return zt;Ia=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]})(),zt.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},zt.exp=function(n){return e[n]},zt.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},zt}var wa;function Py(){return wa||(wa=1,(function(e){const t=Ry();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}})(Ai)),Ai}var Di,Ma;function ky(){if(Ma)return Di;Ma=1;const e=Py();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},Di=t,Di}var Ti={},Si={},bi={},Na;function Ed(){return Na||(Na=1,bi.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),bi}var Oe={},Aa;function Id(){if(Aa)return Oe;Aa=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
- ]))+`;Oe.KANJI=new RegExp(r,"g"),Oe.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Oe.BYTE=new RegExp(n,"g"),Oe.NUMERIC=new RegExp(e,"g"),Oe.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Oe.testKanji=function(c){return i.test(c)},Oe.testNumeric=function(c){return o.test(c)},Oe.testAlphanumeric=function(c){return s.test(c)},Oe}var Da;function dt(){return Da||(Da=1,(function(e){const t=Ed(),r=Id();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}}})(Si)),Si}var Ta;function xy(){return Ta||(Ta=1,(function(e){const t=ct(),r=yd(),n=ko(),i=dt(),o=Ed(),s=7973,a=t.getBCHDigit(s);function c(u,g,T){for(let M=1;M<=40;M++)if(g<=e.getCapacity(M,T,u))return M}function d(u,g){return i.getCharCountIndicator(u,g)+4}function f(u,g){let T=0;return u.forEach(function(M){const S=d(M.mode,g);T+=S+M.getBitsLength()}),T}function h(u,g){for(let T=1;T<=40;T++)if(f(u,T)<=e.getCapacity(T,g,i.MIXED))return T}e.from=function(g,T){return o.isValid(g)?parseInt(g,10):T},e.getCapacity=function(g,T,M){if(!o.isValid(g))throw new Error("Invalid QR Code version");typeof M>"u"&&(M=i.BYTE);const S=t.getSymbolTotalCodewords(g),w=r.getTotalCodewordsCount(g,T),_=(S-w)*8;if(M===i.MIXED)return _;const A=_-d(M,g);switch(M){case i.NUMERIC:return Math.floor(A/10*3);case i.ALPHANUMERIC:return Math.floor(A/11*2);case i.KANJI:return Math.floor(A/13);case i.BYTE:default:return Math.floor(A/8)}},e.getBestVersionForData=function(g,T){let M;const S=n.from(T,n.M);if(Array.isArray(g)){if(g.length>1)return h(g,S);if(g.length===0)return 1;M=g[0]}else M=g;return c(M.mode,M.getLength(),S)},e.getEncodedBits=function(g){if(!o.isValid(g)||g<7)throw new Error("Invalid QR Code version");let T=g<<12;for(;t.getBCHDigit(T)-a>=0;)T^=s<<t.getBCHDigit(T)-a;return g<<12|T}})(Ti)),Ti}var Oi={},Sa;function jy(){if(Sa)return Oi;Sa=1;const e=ct(),t=1335,r=21522,n=e.getBCHDigit(t);return Oi.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},Oi}var _i={},Li,ba;function zy(){if(ba)return Li;ba=1;const e=dt();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))},Li=t,Li}var vi,Oa;function Uy(){if(Oa)return vi;Oa=1;const e=dt(),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)},vi=r,vi}var Ci,_a;function Hy(){if(_a)return Ci;_a=1;const e=dt();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 Ri,La;function Fy(){if(La)return Ri;La=1;const e=dt(),t=ct();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)}},Ri=r,Ri}var Pi={exports:{}},va;function Vy(){return va||(va=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,d,f,h,u,g,T,M,S;!a.empty();){c=a.pop(),d=c.value,h=c.cost,u=r[d]||{};for(f in u)u.hasOwnProperty(f)&&(g=u[f],T=h+g,M=s[f],S=typeof s[f]>"u",(S||M>T)&&(s[f]=T,a.push(f,T),o[f]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var w=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(w)}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})(Pi)),Pi.exports}var Ca;function By(){return Ca||(Ca=1,(function(e){const t=dt(),r=zy(),n=Uy(),i=Hy(),o=Fy(),s=Id(),a=ct(),c=Vy();function d(w){return unescape(encodeURIComponent(w)).length}function f(w,_,A){const v=[];let U;for(;(U=w.exec(A))!==null;)v.push({data:U[0],index:U.index,mode:_,length:U[0].length});return v}function h(w){const _=f(s.NUMERIC,t.NUMERIC,w),A=f(s.ALPHANUMERIC,t.ALPHANUMERIC,w);let v,U;return a.isKanjiModeEnabled()?(v=f(s.BYTE,t.BYTE,w),U=f(s.KANJI,t.KANJI,w)):(v=f(s.BYTE_KANJI,t.BYTE,w),U=[]),_.concat(A,v,U).sort(function(N,l){return N.index-l.index}).map(function(N){return{data:N.data,mode:N.mode,length:N.length}})}function u(w,_){switch(_){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return o.getBitsLength(w);case t.BYTE:return i.getBitsLength(w)}}function g(w){return w.reduce(function(_,A){const v=_.length-1>=0?_[_.length-1]:null;return v&&v.mode===A.mode?(_[_.length-1].data+=A.data,_):(_.push(A),_)},[])}function T(w){const _=[];for(let A=0;A<w.length;A++){const v=w[A];switch(v.mode){case t.NUMERIC:_.push([v,{data:v.data,mode:t.ALPHANUMERIC,length:v.length},{data:v.data,mode:t.BYTE,length:v.length}]);break;case t.ALPHANUMERIC:_.push([v,{data:v.data,mode:t.BYTE,length:v.length}]);break;case t.KANJI:_.push([v,{data:v.data,mode:t.BYTE,length:d(v.data)}]);break;case t.BYTE:_.push([{data:v.data,mode:t.BYTE,length:d(v.data)}])}}return _}function M(w,_){const A={},v={start:{}};let U=["start"];for(let L=0;L<w.length;L++){const N=w[L],l=[];for(let p=0;p<N.length;p++){const m=N[p],E=""+L+p;l.push(E),A[E]={node:m,lastCount:0},v[E]={};for(let I=0;I<U.length;I++){const D=U[I];A[D]&&A[D].node.mode===m.mode?(v[D][E]=u(A[D].lastCount+m.length,m.mode)-u(A[D].lastCount,m.mode),A[D].lastCount+=m.length):(A[D]&&(A[D].lastCount=m.length),v[D][E]=u(m.length,m.mode)+4+t.getCharCountIndicator(m.mode,_))}}U=l}for(let L=0;L<U.length;L++)v[U[L]].end=0;return{map:v,table:A}}function S(w,_){let A;const v=t.getBestModeForData(w);if(A=t.from(_,v),A!==t.BYTE&&A.bit<v.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(A)+`.
8
- Suggested mode is: `+t.toString(v));switch(A===t.KANJI&&!a.isKanjiModeEnabled()&&(A=t.BYTE),A){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new o(w);case t.BYTE:return new i(w)}}e.fromArray=function(_){return _.reduce(function(A,v){return typeof v=="string"?A.push(S(v,null)):v.data&&A.push(S(v.data,v.mode)),A},[])},e.fromString=function(_,A){const v=h(_,a.isKanjiModeEnabled()),U=T(v),L=M(U,A),N=c.find_path(L.map,"start","end"),l=[];for(let p=1;p<N.length-1;p++)l.push(L.table[N[p]].node);return e.fromArray(g(l))},e.rawSplit=function(_){return e.fromArray(h(_,a.isKanjiModeEnabled()))}})(_i)),_i}var Ra;function Qy(){if(Ra)return pi;Ra=1;const e=ct(),t=ko(),r=Oy(),n=_y(),i=Ly(),o=vy(),s=Cy(),a=yd(),c=ky(),d=xy(),f=jy(),h=dt(),u=By();function g(L,N){const l=L.size,p=o.getPositions(N);for(let m=0;m<p.length;m++){const E=p[m][0],I=p[m][1];for(let D=-1;D<=7;D++)if(!(E+D<=-1||l<=E+D))for(let C=-1;C<=7;C++)I+C<=-1||l<=I+C||(D>=0&&D<=6&&(C===0||C===6)||C>=0&&C<=6&&(D===0||D===6)||D>=2&&D<=4&&C>=2&&C<=4?L.set(E+D,I+C,!0,!0):L.set(E+D,I+C,!1,!0))}}function T(L){const N=L.size;for(let l=8;l<N-8;l++){const p=l%2===0;L.set(l,6,p,!0),L.set(6,l,p,!0)}}function M(L,N){const l=i.getPositions(N);for(let p=0;p<l.length;p++){const m=l[p][0],E=l[p][1];for(let I=-2;I<=2;I++)for(let D=-2;D<=2;D++)I===-2||I===2||D===-2||D===2||I===0&&D===0?L.set(m+I,E+D,!0,!0):L.set(m+I,E+D,!1,!0)}}function S(L,N){const l=L.size,p=d.getEncodedBits(N);let m,E,I;for(let D=0;D<18;D++)m=Math.floor(D/3),E=D%3+l-8-3,I=(p>>D&1)===1,L.set(m,E,I,!0),L.set(E,m,I,!0)}function w(L,N,l){const p=L.size,m=f.getEncodedBits(N,l);let E,I;for(E=0;E<15;E++)I=(m>>E&1)===1,E<6?L.set(E,8,I,!0):E<8?L.set(E+1,8,I,!0):L.set(p-15+E,8,I,!0),E<8?L.set(8,p-E-1,I,!0):E<9?L.set(8,15-E-1+1,I,!0):L.set(8,15-E-1,I,!0);L.set(p-8,8,1,!0)}function _(L,N){const l=L.size;let p=-1,m=l-1,E=7,I=0;for(let D=l-1;D>0;D-=2)for(D===6&&D--;;){for(let C=0;C<2;C++)if(!L.isReserved(m,D-C)){let F=!1;I<N.length&&(F=(N[I]>>>E&1)===1),L.set(m,D-C,F),E--,E===-1&&(I++,E=7)}if(m+=p,m<0||l<=m){m-=p,p=-p;break}}}function A(L,N,l){const p=new r;l.forEach(function(C){p.put(C.mode.bit,4),p.put(C.getLength(),h.getCharCountIndicator(C.mode,L)),C.write(p)});const m=e.getSymbolTotalCodewords(L),E=a.getTotalCodewordsCount(L,N),I=(m-E)*8;for(p.getLengthInBits()+4<=I&&p.put(0,4);p.getLengthInBits()%8!==0;)p.putBit(0);const D=(I-p.getLengthInBits())/8;for(let C=0;C<D;C++)p.put(C%2?17:236,8);return v(p,L,N)}function v(L,N,l){const p=e.getSymbolTotalCodewords(N),m=a.getTotalCodewordsCount(N,l),E=p-m,I=a.getBlocksCount(N,l),D=p%I,C=I-D,F=Math.floor(p/I),R=Math.floor(E/I),O=R+1,P=F-R,b=new c(P);let x=0;const j=new Array(I),z=new Array(I);let B=0;const Q=new Uint8Array(L.buffer);for(let q=0;q<I;q++){const he=q<C?R:O;j[q]=Q.slice(x,x+he),z[q]=b.encode(j[q]),x+=he,B=Math.max(B,he)}const G=new Uint8Array(p);let te=0,X,Z;for(X=0;X<B;X++)for(Z=0;Z<I;Z++)X<j[Z].length&&(G[te++]=j[Z][X]);for(X=0;X<P;X++)for(Z=0;Z<I;Z++)G[te++]=z[Z][X];return G}function U(L,N,l,p){let m;if(Array.isArray(L))m=u.fromArray(L);else if(typeof L=="string"){let F=N;if(!F){const R=u.rawSplit(L);F=d.getBestVersionForData(R,l)}m=u.fromString(L,F||40)}else throw new Error("Invalid data");const E=d.getBestVersionForData(m,l);if(!E)throw new Error("The amount of data is too big to be stored in a QR Code");if(!N)N=E;else if(N<E)throw new Error(`
5
+ URL: ${e}`}function ry(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(ty(e.url))}function da(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function ny(){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:ec,knownMethodCount:Ye.length,supportsFileCreate:Ye.some(i=>i.method===tr),system:iy(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:yt(e?.hardwareConcurrency),maxTouchPoints:yt(e?.maxTouchPoints),screen:{width:yt(t?.width),height:yt(t?.height)},viewport:{width:yt(r?.innerWidth),height:yt(r?.innerHeight),devicePixelRatio:oy(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function iy(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 yt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function oy(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function sy(e){return $(Cp,hd,{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 ay(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 cy(e){if(!On(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!On(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 Wp(e)}const dy=/^(?: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,uy=new Set(["origin","referer","user-agent"]);function ly(e,t){return Hu({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=fy(r),a=await e.authenticatedRequest(s,o);return gy(a)})}).network}function fy(e){const t=hy(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function hy(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!my(t)))}function my(e){const t=e.trim().toLowerCase();return uy.has(t)}function gy(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:py(e.headers)??{}}}function py(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!yy(t)))}function yy(e){const t=e.trim().toLowerCase();return dy.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Ey(e,t,r){const n=Ay(e.presentation,t);return{account:My(e,t,r),network:ly(e,t),...e.storage===void 0?{}:{storage:Ny(e,t)},...e.storage===void 0?{}:Iy(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function Iy(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 wy(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 My(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 Ny(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 Ay(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)=>Zu(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 Dy(){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 Lr(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(f=>f.aborted);if(i)throw Lr(i.reason);const o=new AbortController;let s;const a=new Promise((f,h)=>{s=h}),c=n.map(f=>{const h=()=>{o.signal.aborted||o.abort(f.reason),s(Lr(f.reason))};return f.addEventListener("abort",h,{once:!0}),{listener:h,source:f}});let d;try{d=Promise.resolve(r(o.signal))}catch(f){d=Promise.reject(f)}try{const f=await Promise.race([d,a]),h=n.find(u=>u.aborted);if(h)throw Lr(h.reason);return f}finally{for(const{listener:f,source:h}of c)h.removeEventListener("abort",f)}}}}function Lr(e){return new DOMException("Web Host operation aborted","AbortError")}async function Ty(e){const t=Dy(),r=new Set;let n=!1;const i=h=>{if(n||t.signal.aborted)return mi(h),()=>{};let u=!0;const g=()=>{u&&(u=!1,r.delete(g),mi(h))};return r.add(g),g},o=()=>s(e.signal.reason),s=h=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(h);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=Ey(e,t,i),c=fc(a,{hostCapabilities:e.hostCapabilities}),d=wy(e,t);let f;return{platform:"web",ports:a,environment:d,resolveLaunch:()=>(f??=t.run(void 0,async h=>e.resolveLaunch(h)),f),...e.authPresentation===void 0?{}:{authPresentation:Sy(e.authPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function mi(e){try{e()}catch{}}function Sy(e,t){return{confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var Et={},gi,ua;function by(){return ua||(ua=1,gi=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),gi}var pi={},Ue={},la;function ct(){if(la)return Ue;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 Ue.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},Ue.getSymbolTotalCodewords=function(n){return t[n]},Ue.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Ue.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Ue.isKanjiModeEnabled=function(){return typeof e<"u"},Ue.toSJIS=function(n){return e(n)},Ue}var yi={},fa;function ko(){return fa||(fa=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,ha;function Oy(){if(ha)return Ei;ha=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 Ii,ma;function _y(){if(ma)return Ii;ma=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]},Ii=e,Ii}var wi={},ga;function Ly(){return ga||(ga=1,(function(e){const t=ct().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}})(wi)),wi}var Mi={},pa;function vy(){if(pa)return Mi;pa=1;const e=ct().getSymbolSize,t=7;return Mi.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},Mi}var Ni={},ya;function Cy(){return ya||(ya=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,d=null,f=null;for(let h=0;h<o;h++){a=c=0,d=f=null;for(let u=0;u<o;u++){let g=i.get(h,u);g===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=g,a=1),g=i.get(u,h),g===f?c++:(c>=5&&(s+=t.N1+(c-5)),f=g,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const d=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(d===4||d===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let d=0;d<o;d++){a=c=0;for(let f=0;f<o;f++)a=a<<1&2047|i.get(d,f),f>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(f,d),f>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let d=0;d<s;d++){o(d),e.applyMask(d,i);const f=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(d,i),f<c&&(c=f,a=d)}return a}})(Ni)),Ni}var vr={},Ea;function Ed(){if(Ea)return vr;Ea=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 vr.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}},vr.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}},vr}var Ai={},zt={},Ia;function Ry(){if(Ia)return zt;Ia=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]})(),zt.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},zt.exp=function(n){return e[n]},zt.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},zt}var wa;function Py(){return wa||(wa=1,(function(e){const t=Ry();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}})(Ai)),Ai}var Di,Ma;function ky(){if(Ma)return Di;Ma=1;const e=Py();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},Di=t,Di}var Ti={},Si={},bi={},Na;function Id(){return Na||(Na=1,bi.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),bi}var Oe={},Aa;function wd(){if(Aa)return Oe;Aa=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
+ ]))+`;Oe.KANJI=new RegExp(r,"g"),Oe.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Oe.BYTE=new RegExp(n,"g"),Oe.NUMERIC=new RegExp(e,"g"),Oe.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Oe.testKanji=function(c){return i.test(c)},Oe.testNumeric=function(c){return o.test(c)},Oe.testAlphanumeric=function(c){return s.test(c)},Oe}var Da;function dt(){return Da||(Da=1,(function(e){const t=Id(),r=wd();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}}})(Si)),Si}var Ta;function xy(){return Ta||(Ta=1,(function(e){const t=ct(),r=Ed(),n=ko(),i=dt(),o=Id(),s=7973,a=t.getBCHDigit(s);function c(u,g,T){for(let M=1;M<=40;M++)if(g<=e.getCapacity(M,T,u))return M}function d(u,g){return i.getCharCountIndicator(u,g)+4}function f(u,g){let T=0;return u.forEach(function(M){const S=d(M.mode,g);T+=S+M.getBitsLength()}),T}function h(u,g){for(let T=1;T<=40;T++)if(f(u,T)<=e.getCapacity(T,g,i.MIXED))return T}e.from=function(g,T){return o.isValid(g)?parseInt(g,10):T},e.getCapacity=function(g,T,M){if(!o.isValid(g))throw new Error("Invalid QR Code version");typeof M>"u"&&(M=i.BYTE);const S=t.getSymbolTotalCodewords(g),w=r.getTotalCodewordsCount(g,T),_=(S-w)*8;if(M===i.MIXED)return _;const A=_-d(M,g);switch(M){case i.NUMERIC:return Math.floor(A/10*3);case i.ALPHANUMERIC:return Math.floor(A/11*2);case i.KANJI:return Math.floor(A/13);case i.BYTE:default:return Math.floor(A/8)}},e.getBestVersionForData=function(g,T){let M;const S=n.from(T,n.M);if(Array.isArray(g)){if(g.length>1)return h(g,S);if(g.length===0)return 1;M=g[0]}else M=g;return c(M.mode,M.getLength(),S)},e.getEncodedBits=function(g){if(!o.isValid(g)||g<7)throw new Error("Invalid QR Code version");let T=g<<12;for(;t.getBCHDigit(T)-a>=0;)T^=s<<t.getBCHDigit(T)-a;return g<<12|T}})(Ti)),Ti}var Oi={},Sa;function jy(){if(Sa)return Oi;Sa=1;const e=ct(),t=1335,r=21522,n=e.getBCHDigit(t);return Oi.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},Oi}var _i={},Li,ba;function zy(){if(ba)return Li;ba=1;const e=dt();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))},Li=t,Li}var vi,Oa;function Uy(){if(Oa)return vi;Oa=1;const e=dt(),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)},vi=r,vi}var Ci,_a;function Hy(){if(_a)return Ci;_a=1;const e=dt();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 Ri,La;function Fy(){if(La)return Ri;La=1;const e=dt(),t=ct();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)}},Ri=r,Ri}var Pi={exports:{}},va;function Vy(){return va||(va=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,d,f,h,u,g,T,M,S;!a.empty();){c=a.pop(),d=c.value,h=c.cost,u=r[d]||{};for(f in u)u.hasOwnProperty(f)&&(g=u[f],T=h+g,M=s[f],S=typeof s[f]>"u",(S||M>T)&&(s[f]=T,a.push(f,T),o[f]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var w=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(w)}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})(Pi)),Pi.exports}var Ca;function By(){return Ca||(Ca=1,(function(e){const t=dt(),r=zy(),n=Uy(),i=Hy(),o=Fy(),s=wd(),a=ct(),c=Vy();function d(w){return unescape(encodeURIComponent(w)).length}function f(w,_,A){const v=[];let U;for(;(U=w.exec(A))!==null;)v.push({data:U[0],index:U.index,mode:_,length:U[0].length});return v}function h(w){const _=f(s.NUMERIC,t.NUMERIC,w),A=f(s.ALPHANUMERIC,t.ALPHANUMERIC,w);let v,U;return a.isKanjiModeEnabled()?(v=f(s.BYTE,t.BYTE,w),U=f(s.KANJI,t.KANJI,w)):(v=f(s.BYTE_KANJI,t.BYTE,w),U=[]),_.concat(A,v,U).sort(function(N,l){return N.index-l.index}).map(function(N){return{data:N.data,mode:N.mode,length:N.length}})}function u(w,_){switch(_){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return o.getBitsLength(w);case t.BYTE:return i.getBitsLength(w)}}function g(w){return w.reduce(function(_,A){const v=_.length-1>=0?_[_.length-1]:null;return v&&v.mode===A.mode?(_[_.length-1].data+=A.data,_):(_.push(A),_)},[])}function T(w){const _=[];for(let A=0;A<w.length;A++){const v=w[A];switch(v.mode){case t.NUMERIC:_.push([v,{data:v.data,mode:t.ALPHANUMERIC,length:v.length},{data:v.data,mode:t.BYTE,length:v.length}]);break;case t.ALPHANUMERIC:_.push([v,{data:v.data,mode:t.BYTE,length:v.length}]);break;case t.KANJI:_.push([v,{data:v.data,mode:t.BYTE,length:d(v.data)}]);break;case t.BYTE:_.push([{data:v.data,mode:t.BYTE,length:d(v.data)}])}}return _}function M(w,_){const A={},v={start:{}};let U=["start"];for(let L=0;L<w.length;L++){const N=w[L],l=[];for(let p=0;p<N.length;p++){const m=N[p],E=""+L+p;l.push(E),A[E]={node:m,lastCount:0},v[E]={};for(let I=0;I<U.length;I++){const D=U[I];A[D]&&A[D].node.mode===m.mode?(v[D][E]=u(A[D].lastCount+m.length,m.mode)-u(A[D].lastCount,m.mode),A[D].lastCount+=m.length):(A[D]&&(A[D].lastCount=m.length),v[D][E]=u(m.length,m.mode)+4+t.getCharCountIndicator(m.mode,_))}}U=l}for(let L=0;L<U.length;L++)v[U[L]].end=0;return{map:v,table:A}}function S(w,_){let A;const v=t.getBestModeForData(w);if(A=t.from(_,v),A!==t.BYTE&&A.bit<v.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(A)+`.
8
+ Suggested mode is: `+t.toString(v));switch(A===t.KANJI&&!a.isKanjiModeEnabled()&&(A=t.BYTE),A){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new o(w);case t.BYTE:return new i(w)}}e.fromArray=function(_){return _.reduce(function(A,v){return typeof v=="string"?A.push(S(v,null)):v.data&&A.push(S(v.data,v.mode)),A},[])},e.fromString=function(_,A){const v=h(_,a.isKanjiModeEnabled()),U=T(v),L=M(U,A),N=c.find_path(L.map,"start","end"),l=[];for(let p=1;p<N.length-1;p++)l.push(L.table[N[p]].node);return e.fromArray(g(l))},e.rawSplit=function(_){return e.fromArray(h(_,a.isKanjiModeEnabled()))}})(_i)),_i}var Ra;function Qy(){if(Ra)return pi;Ra=1;const e=ct(),t=ko(),r=Oy(),n=_y(),i=Ly(),o=vy(),s=Cy(),a=Ed(),c=ky(),d=xy(),f=jy(),h=dt(),u=By();function g(L,N){const l=L.size,p=o.getPositions(N);for(let m=0;m<p.length;m++){const E=p[m][0],I=p[m][1];for(let D=-1;D<=7;D++)if(!(E+D<=-1||l<=E+D))for(let C=-1;C<=7;C++)I+C<=-1||l<=I+C||(D>=0&&D<=6&&(C===0||C===6)||C>=0&&C<=6&&(D===0||D===6)||D>=2&&D<=4&&C>=2&&C<=4?L.set(E+D,I+C,!0,!0):L.set(E+D,I+C,!1,!0))}}function T(L){const N=L.size;for(let l=8;l<N-8;l++){const p=l%2===0;L.set(l,6,p,!0),L.set(6,l,p,!0)}}function M(L,N){const l=i.getPositions(N);for(let p=0;p<l.length;p++){const m=l[p][0],E=l[p][1];for(let I=-2;I<=2;I++)for(let D=-2;D<=2;D++)I===-2||I===2||D===-2||D===2||I===0&&D===0?L.set(m+I,E+D,!0,!0):L.set(m+I,E+D,!1,!0)}}function S(L,N){const l=L.size,p=d.getEncodedBits(N);let m,E,I;for(let D=0;D<18;D++)m=Math.floor(D/3),E=D%3+l-8-3,I=(p>>D&1)===1,L.set(m,E,I,!0),L.set(E,m,I,!0)}function w(L,N,l){const p=L.size,m=f.getEncodedBits(N,l);let E,I;for(E=0;E<15;E++)I=(m>>E&1)===1,E<6?L.set(E,8,I,!0):E<8?L.set(E+1,8,I,!0):L.set(p-15+E,8,I,!0),E<8?L.set(8,p-E-1,I,!0):E<9?L.set(8,15-E-1+1,I,!0):L.set(8,15-E-1,I,!0);L.set(p-8,8,1,!0)}function _(L,N){const l=L.size;let p=-1,m=l-1,E=7,I=0;for(let D=l-1;D>0;D-=2)for(D===6&&D--;;){for(let C=0;C<2;C++)if(!L.isReserved(m,D-C)){let F=!1;I<N.length&&(F=(N[I]>>>E&1)===1),L.set(m,D-C,F),E--,E===-1&&(I++,E=7)}if(m+=p,m<0||l<=m){m-=p,p=-p;break}}}function A(L,N,l){const p=new r;l.forEach(function(C){p.put(C.mode.bit,4),p.put(C.getLength(),h.getCharCountIndicator(C.mode,L)),C.write(p)});const m=e.getSymbolTotalCodewords(L),E=a.getTotalCodewordsCount(L,N),I=(m-E)*8;for(p.getLengthInBits()+4<=I&&p.put(0,4);p.getLengthInBits()%8!==0;)p.putBit(0);const D=(I-p.getLengthInBits())/8;for(let C=0;C<D;C++)p.put(C%2?17:236,8);return v(p,L,N)}function v(L,N,l){const p=e.getSymbolTotalCodewords(N),m=a.getTotalCodewordsCount(N,l),E=p-m,I=a.getBlocksCount(N,l),D=p%I,C=I-D,F=Math.floor(p/I),R=Math.floor(E/I),O=R+1,P=F-R,b=new c(P);let x=0;const j=new Array(I),z=new Array(I);let B=0;const Q=new Uint8Array(L.buffer);for(let q=0;q<I;q++){const he=q<C?R:O;j[q]=Q.slice(x,x+he),z[q]=b.encode(j[q]),x+=he,B=Math.max(B,he)}const G=new Uint8Array(p);let te=0,X,Z;for(X=0;X<B;X++)for(Z=0;Z<I;Z++)X<j[Z].length&&(G[te++]=j[Z][X]);for(X=0;X<P;X++)for(Z=0;Z<I;Z++)G[te++]=z[Z][X];return G}function U(L,N,l,p){let m;if(Array.isArray(L))m=u.fromArray(L);else if(typeof L=="string"){let F=N;if(!F){const R=u.rawSplit(L);F=d.getBestVersionForData(R,l)}m=u.fromString(L,F||40)}else throw new Error("Invalid data");const E=d.getBestVersionForData(m,l);if(!E)throw new Error("The amount of data is too big to be stored in a QR Code");if(!N)N=E;else if(N<E)throw new Error(`
9
9
  The chosen QR Code version cannot contain this amount of data.
10
10
  Minimum version required to store current data is: `+E+`.
11
- `);const I=A(N,l,m),D=e.getSymbolSize(N),C=new n(D);return g(C,N),T(C),M(C,N),w(C,l,0),N>=7&&S(C,N),_(C,I),isNaN(p)&&(p=s.getBestMask(C,w.bind(null,C,l))),s.applyMask(p,C),w(C,l,p),{modules:C,version:N,errorCorrectionLevel:l,maskPattern:p,segments:m}}return pi.create=function(N,l){if(typeof N>"u"||N==="")throw new Error("No input text");let p=t.M,m,E;return typeof l<"u"&&(p=t.from(l.errorCorrectionLevel,t.M),m=d.from(l.version),E=s.from(l.maskPattern),l.toSJISFunc&&e.setToSJISFunction(l.toSJISFunc)),U(N,m,p,E)},pi}var ki={},xi={},Pa;function wd(){return Pa||(Pa=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),d=Math.floor((s+o.margin*2)*c),f=o.margin*c,h=[o.color.light,o.color.dark];for(let u=0;u<d;u++)for(let g=0;g<d;g++){let T=(u*d+g)*4,M=o.color.light;if(u>=f&&g>=f&&u<d-f&&g<d-f){const S=Math.floor((u-f)/c),w=Math.floor((g-f)/c);M=h[a[S*s+w]?1:0]}n[T++]=M.r,n[T++]=M.g,n[T++]=M.b,n[T]=M.a}}})(xi)),xi}var ka;function Yy(){return ka||(ka=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,d=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(d=n()),c=t.getOptions(c);const f=t.getImageWidth(o.modules.size,c),h=d.getContext("2d"),u=h.createImageData(f,f);return t.qrToImageData(u.data,o,c),r(h,d,f),h.putImageData(u,0,0),d},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const d=e.render(o,s,c),f=c.type||"image/png",h=c.rendererOpts||{};return d.toDataURL(f,h.quality)}})(ki)),ki}var ji={},xa;function Gy(){if(xa)return ji;xa=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,d=!1,f=0;for(let h=0;h<i.length;h++){const u=Math.floor(h%o),g=Math.floor(h/o);!u&&!d&&(d=!0),i[h]?(f++,h>0&&u>0&&i[h-1]||(a+=d?r("M",u+s,.5+g+s):r("m",c,0),c=0,d=!1),u+1<o&&i[h+1]||(a+=r("h",f),f=0)):c++}return a}return ji.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,f=o.modules.data,h=d+c.margin*2,u=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",g="<path "+t(c.color.dark,"stroke")+' d="'+n(f,d,c.margin)+'"/>',T='viewBox="0 0 '+h+" "+h+'"',S='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+T+' shape-rendering="crispEdges">'+u+g+`</svg>
12
- `;return typeof a=="function"&&a(null,S),S},ji}var ja;function qy(){if(ja)return Et;ja=1;const e=by(),t=Qy(),r=Yy(),n=Gy();function i(o,s,a,c,d){const f=[].slice.call(arguments,1),h=f.length,u=typeof f[h-1]=="function";if(!u&&!e())throw new Error("Callback required as last argument");if(u){if(h<2)throw new Error("Too few arguments provided");h===2?(d=a,a=s,s=c=void 0):h===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(a=s,s=c=void 0):h===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(g,T){try{const M=t.create(a,c);g(o(M,s,c))}catch(M){T(M)}})}try{const g=t.create(a,c);d(null,o(g,s,c))}catch(g){d(g)}}return Et.create=t.create,Et.toCanvas=i.bind(null,r.render),Et.toDataURL=i.bind(null,r.renderToDataURL),Et.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),Et}var Wy=qy();const $y="/__hb_sdk__/dev-context";function _n(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=sc(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:Mu({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 Ky(e){if(!eo(e)||!za(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!eo(t)||!za(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const Jy={networkRequest:{status:"disabled",useOfficialDomain:!1}};function qn(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}}:eE()}function Zy(e,t,r){return r?.localDevGrant?Eo({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:Md(e,t,t.networkRequest.useOfficialDomain)}function Xy(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=qn({...e,localDevGrant:void 0});return Md(e.runtimePermissions,t,!1)}function eE(){return{networkRequest:{...Jy.networkRequest}}}function Md(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 za(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function tE(e){let t,r=!1,n=!1,i;return{invalidate(a){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(a,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=o().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function o(){let a={ok:!0};for(;r&&!n;){r=!1;const c=new AbortController;t=c;let d;try{d=await e.fetch(c.signal)}catch(h){a={ok:!1},!n&&!c.signal.aborted&&s(h);continue}finally{t===c&&(t=void 0)}if(n)return{ok:!1};let f;try{f=e.apply(d)}catch(h){a={ok:!1},n||s(h);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(f))try{await e.onChanged(f)}catch(h){a={ok:!1},n||s(h)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function rE(e){return tE({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 nE(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 iE={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};function oE(e){return new Promise((t,r)=>{if(e.signal.aborted){r(e.signal.reason);return}const n=document.createElement("div");n.className="hb-sdk-auth-dialog",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.innerHTML=`
11
+ `);const I=A(N,l,m),D=e.getSymbolSize(N),C=new n(D);return g(C,N),T(C),M(C,N),w(C,l,0),N>=7&&S(C,N),_(C,I),isNaN(p)&&(p=s.getBestMask(C,w.bind(null,C,l))),s.applyMask(p,C),w(C,l,p),{modules:C,version:N,errorCorrectionLevel:l,maskPattern:p,segments:m}}return pi.create=function(N,l){if(typeof N>"u"||N==="")throw new Error("No input text");let p=t.M,m,E;return typeof l<"u"&&(p=t.from(l.errorCorrectionLevel,t.M),m=d.from(l.version),E=s.from(l.maskPattern),l.toSJISFunc&&e.setToSJISFunction(l.toSJISFunc)),U(N,m,p,E)},pi}var ki={},xi={},Pa;function Md(){return Pa||(Pa=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),d=Math.floor((s+o.margin*2)*c),f=o.margin*c,h=[o.color.light,o.color.dark];for(let u=0;u<d;u++)for(let g=0;g<d;g++){let T=(u*d+g)*4,M=o.color.light;if(u>=f&&g>=f&&u<d-f&&g<d-f){const S=Math.floor((u-f)/c),w=Math.floor((g-f)/c);M=h[a[S*s+w]?1:0]}n[T++]=M.r,n[T++]=M.g,n[T++]=M.b,n[T]=M.a}}})(xi)),xi}var ka;function Yy(){return ka||(ka=1,(function(e){const t=Md();function r(i,o,s){i.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=s,o.width=s,o.style.height=s+"px",o.style.width=s+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(o,s,a){let c=a,d=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(d=n()),c=t.getOptions(c);const f=t.getImageWidth(o.modules.size,c),h=d.getContext("2d"),u=h.createImageData(f,f);return t.qrToImageData(u.data,o,c),r(h,d,f),h.putImageData(u,0,0),d},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const d=e.render(o,s,c),f=c.type||"image/png",h=c.rendererOpts||{};return d.toDataURL(f,h.quality)}})(ki)),ki}var ji={},xa;function Gy(){if(xa)return ji;xa=1;const e=Md();function t(i,o){const s=i.a/255,a=o+'="'+i.hex+'"';return s<1?a+" "+o+'-opacity="'+s.toFixed(2).slice(1)+'"':a}function r(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function n(i,o,s){let a="",c=0,d=!1,f=0;for(let h=0;h<i.length;h++){const u=Math.floor(h%o),g=Math.floor(h/o);!u&&!d&&(d=!0),i[h]?(f++,h>0&&u>0&&i[h-1]||(a+=d?r("M",u+s,.5+g+s):r("m",c,0),c=0,d=!1),u+1<o&&i[h+1]||(a+=r("h",f),f=0)):c++}return a}return ji.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,f=o.modules.data,h=d+c.margin*2,u=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",g="<path "+t(c.color.dark,"stroke")+' d="'+n(f,d,c.margin)+'"/>',T='viewBox="0 0 '+h+" "+h+'"',S='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+T+' shape-rendering="crispEdges">'+u+g+`</svg>
12
+ `;return typeof a=="function"&&a(null,S),S},ji}var ja;function qy(){if(ja)return Et;ja=1;const e=by(),t=Qy(),r=Yy(),n=Gy();function i(o,s,a,c,d){const f=[].slice.call(arguments,1),h=f.length,u=typeof f[h-1]=="function";if(!u&&!e())throw new Error("Callback required as last argument");if(u){if(h<2)throw new Error("Too few arguments provided");h===2?(d=a,a=s,s=c=void 0):h===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(h<1)throw new Error("Too few arguments provided");return h===1?(a=s,s=c=void 0):h===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(g,T){try{const M=t.create(a,c);g(o(M,s,c))}catch(M){T(M)}})}try{const g=t.create(a,c);d(null,o(g,s,c))}catch(g){d(g)}}return Et.create=t.create,Et.toCanvas=i.bind(null,r.render),Et.toDataURL=i.bind(null,r.renderToDataURL),Et.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),Et}var Wy=qy();const $y="/__hb_sdk__/dev-context";function _n(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=sc(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:Nu({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 Ky(e){if(!eo(e)||!za(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!eo(t)||!za(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const Jy={networkRequest:{status:"disabled",useOfficialDomain:!1}};function qn(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}}:eE()}function Zy(e,t,r){return r?.localDevGrant?Eo({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:Nd(e,t,t.networkRequest.useOfficialDomain)}function Xy(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=qn({...e,localDevGrant:void 0});return Nd(e.runtimePermissions,t,!1)}function eE(){return{networkRequest:{...Jy.networkRequest}}}function Nd(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 za(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function tE(e){let t,r=!1,n=!1,i;return{invalidate(a){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(a,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=o().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function o(){let a={ok:!0};for(;r&&!n;){r=!1;const c=new AbortController;t=c;let d;try{d=await e.fetch(c.signal)}catch(h){a={ok:!1},!n&&!c.signal.aborted&&s(h);continue}finally{t===c&&(t=void 0)}if(n)return{ok:!1};let f;try{f=e.apply(d)}catch(h){a={ok:!1},n||s(h);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(f))try{await e.onChanged(f)}catch(h){a={ok:!1},n||s(h)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function rE(e){return tE({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 nE(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 iE={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};function oE(e){return new Promise((t,r)=>{if(e.signal.aborted){r(e.signal.reason);return}const n=document.createElement("div");n.className="hb-sdk-auth-dialog",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.innerHTML=`
13
13
  <div class="hb-sdk-auth-dialog__panel">
14
14
  <h2>授权请求</h2>
15
15
  <p class="hb-sdk-auth-dialog__app">${zi(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
@@ -89,14 +89,14 @@ Minimum version required to store current data is: `+E+`.
89
89
  color: #fff;
90
90
  background: #2563eb;
91
91
  }
92
- `,document.head.appendChild(e)}const fE=44;function hE(e){const t=()=>e.isCapsuleHidden?.()?0:fE;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 qd({message:r,status:n})},showLoading:Gd,hideLoading:Yd,vibrate:Qd,openAppPage:aE,openWindow:cE,showShareMenu:dE,captureAndShare:uE,setScreenshotChromeHidden:Bd}}const Fa=["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 mE{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]:[...Fa];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(ce("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((d,f)=>{o=d,s=f}),c={cancelled:!1,listeners:new Set([r.onProgress]),promise:a,reject:s,resolve:o,timers:new Set};{const d={status:{state:"preparing",progress:Cr[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),Cr.forEach((f,h)=>{const u=this.schedule(()=>{if(c.timers.delete(u),!c.cancelled){d.status={state:"preparing",progress:f};try{c.listeners.forEach(g=>g(f))}catch(g){c.cancelled=!0;for(const T of c.timers)this.clearSchedule(T);d.operation=void 0,d.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",n,{message:g instanceof Error?g.message:String(g)}),c.reject(g);return}if(this.diagnostic("prepare.progress",n,{phase:f.phase}),h===Cr.length-1){if(d.operation=void 0,n==="prepare-fail"){d.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},c.reject(ce("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",n,{code:"COMPANION_INTEGRITY_FAILED"});return}d.status={state:"ready",preparedAt:this.now()},c.resolve(this.getInfo(n)),this.diagnostic("prepare.ready",n)}}},h+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(ce("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(fu,{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 ce("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw ce("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw ce("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
92
+ `,document.head.appendChild(e)}const fE=44;function hE(e){const t=()=>e.isCapsuleHidden?.()?0:fE;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 Wd({message:r,status:n})},showLoading:qd,hideLoading:Gd,vibrate:Yd,openAppPage:aE,openWindow:cE,showShareMenu:dE,captureAndShare:uE,setScreenshotChromeHidden:Qd}}const Fa=["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 mE{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]:[...Fa];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(ce("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((d,f)=>{o=d,s=f}),c={cancelled:!1,listeners:new Set([r.onProgress]),promise:a,reject:s,resolve:o,timers:new Set};{const d={status:{state:"preparing",progress:Cr[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),Cr.forEach((f,h)=>{const u=this.schedule(()=>{if(c.timers.delete(u),!c.cancelled){d.status={state:"preparing",progress:f};try{c.listeners.forEach(g=>g(f))}catch(g){c.cancelled=!0;for(const T of c.timers)this.clearSchedule(T);d.operation=void 0,d.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",n,{message:g instanceof Error?g.message:String(g)}),c.reject(g);return}if(this.diagnostic("prepare.progress",n,{phase:f.phase}),h===Cr.length-1){if(d.operation=void 0,n==="prepare-fail"){d.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},c.reject(ce("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",n,{code:"COMPANION_INTEGRITY_FAILED"});return}d.status={state:"ready",preparedAt:this.now()},c.resolve(this.getInfo(n)),this.diagnostic("prepare.ready",n)}}},h+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(ce("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(hu,{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 ce("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw ce("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw ce("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
93
  `),this.queueOutput(o,"stderr",1,`fake:diagnostic
94
94
  `)},20),r==="normal-exit"&&this.schedule(()=>this.requestExit(o,{reason:"exited",exitCode:0}),40),r==="crash"&&this.schedule(()=>this.requestExit(o,{reason:"crashed",exitCode:1}),40),r==="output-limit"&&this.schedule(()=>this.requestExit(o,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("stdio"))throw ce("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw ce("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 ce("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw ce("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 ce("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw ce("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 ce("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(uu,{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(lu,{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 ce("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw ce("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!Fa.includes(t))throw ce("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 gE=Object.freeze({[vn]:!0,[Cn]:!0,[Rn]:!0,[Pn]:!0,[kn]:!0,[xn]:!0,[jn]:!0,[zn]:!0,[Un]:!0,[Hn]:!0,[Fn]:!0,[Vn]:!0,[ir]:!0,[nr]:!0,[or]:!0});function pE(e){return new mE(e)}function ce(e,t){return Object.assign(new Error(t),{code:e})}const yE=/^[A-Za-z0-9_-]{22}$/,EE="https://api.xiaoheihe.cn/open_inapp/";function IE(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(!yE.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 wE(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`${EE}#${r}`}function ME(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 NE="__hb_sdk_mini_dev__",AE="hb-sdk:mini-dev-console",DE="__hb_sdk_mini_dev_console_installed__",Ba=DE;function TE(e,t=console){bE(t,e,t)}const SE=["log","debug","info","warn","error"];function bE(e,t,r){if(!r||r[Ba]===!0)return!1;let n=!1;for(const i of SE){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[Ba]=!0),n}const to=1,Qa=64*1024,OE=64,_E=/^[A-Za-z0-9_-]{22}$/;class ge extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function LE(e,t=!1){const r=CE(e,t);switch(ro(r,"Server message"),RE(r),r.type){case"grant":return $t(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),Kt(r.connectionEpoch,"connectionEpoch"),nt(r.nextClientSequence,"nextClientSequence"),nt(r.nextServerSequence,"nextServerSequence"),Ya(r.snapshot),r;case"event":return $t(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),Kt(r.connectionEpoch,"connectionEpoch"),nt(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&$e("event must be account.changed or status.changed"),Ya(r.snapshot),r;case"heartbeat":return $t(r,["version","type","connectionEpoch","sequence"],"heartbeat"),Kt(r.connectionEpoch,"connectionEpoch"),nt(r.sequence,"sequence"),r;default:return $e("Unknown server message type")}}function vE(e){const t=e.connectionEpoch;Kt(t,"connectionEpoch"),nt(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(Kt(n.connectionEpoch,"connectionEpoch"),nt(n.sequence,"sequence"),n.connectionEpoch!==t)throw new ge("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new ge("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new ge("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function CE(e,t){if(t)throw new ge("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new ge("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Qa)throw new ge("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Qa)throw new ge("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return PE(e),JSON.parse(e)}catch(r){throw r instanceof ge?r:new ge("INVALID_JSON","Channel frame must contain strict JSON")}}function Ya(e){ro(e,"snapshot"),$t(e,["account","permissions"],"snapshot"),ro(e.account,"snapshot.account"),$t(e.account,["revision"],"snapshot.account"),nt(e.account.revision,"snapshot.account.revision"),Ky(e.permissions)||$e("snapshot.permissions is invalid")}function RE(e){e.version!==to&&$e("version must be 1")}function ro(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&$e(`${t} must be a plain JSON object`)}function $t(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)))&&$e(`${r} fields are invalid`)}function nt(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&$e(`${t} must be a non-negative safe integer`)}function Kt(e,t){(typeof e!="string"||!_E.test(e))&&$e(`${t} must be a 22-character base64url value`)}function $e(e){throw new ge("INVALID_MESSAGE",e)}function PE(e){new kE(e).scan()}class kE{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>=OE)throw new ge("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 ge("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 Ga=[1e3,2e3,4e3,8e3,15e3];function xE(e){const t=new Set,r=e.webSocketFactory??(m=>new WebSocket(m)),n=e.randomValues??(m=>crypto.getRandomValues(m)),i=e.timers??{clearTimeout:m=>window.clearTimeout(m),setTimeout:(m,E)=>window.setTimeout(m,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,d,f,h=!1,u=0,g,T=!1,M=!1;const S=new Set,w=(m,E)=>{if(!(!e.onDiagnostic||S.has(m))){S.add(m);try{e.onDiagnostic({phase:m,...E?{code:E}:{}})}catch{}}},_=(m,E,I=!1)=>{if(f&&m.account.revision<f.account.revision)return;const D=f&&JSON.stringify(m)===JSON.stringify(f);if(f=m,!(D&&!I))for(const C of t)C(m,E)},A=()=>{if(h||g!==void 0||c)return;const m=Ga[Math.min(u,Ga.length-1)];u+=1,g=i.setTimeout(()=>{g=void 0,p()},m)},v=()=>{h||!T||c||(g!==void 0&&(i.clearTimeout(g),g=void 0),p())},U=()=>{a()&&v()},L=()=>{s&&!s.hidden&&v()},N=()=>{M||(M=!0,o?.addEventListener("online",U),s?.addEventListener("visibilitychange",L))},l=()=>{M&&(M=!1,o?.removeEventListener("online",U),s?.removeEventListener("visibilitychange",L))},p=()=>{if(h||c)return;T=!0,N(),g!==void 0&&(i.clearTimeout(g),g=void 0);let m,E;try{m=r(e.url)}catch{w("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),A();return}try{E=zE(n)}catch{w("entropy","NONCE_GENERATION_FAILED");try{m?.close(1011,"channel initialization failed")}catch{}A();return}c=m;let I,D,C;const F=()=>{m.removeEventListener("open",O),m.removeEventListener("message",P),m.removeEventListener("close",b),m.removeEventListener("error",x),d===F&&(d=void 0)},R=()=>{if(c===m){c=void 0,F();try{m.close(1008,"invalid channel state")}catch{}A()}},O=()=>{if(!(h||c!==m))try{m.send(JSON.stringify({version:to,type:"hello",csrfToken:e.csrfToken,clientNonce:E}))}catch{w("send","HELLO_SEND_FAILED"),R()}},P=j=>{if(h||c!==m)return;if(typeof j.data!="string"){w("parse","TEXT_FRAME_REQUIRED"),R();return}let z;try{z=LE(j.data)}catch(B){w("parse",B instanceof ge?B.code:"INVALID_MESSAGE"),R();return}if(z.type==="grant"){if(C){w("sequence","DUPLICATE_GRANT"),R();return}I=z.connectionEpoch,D=z.nextClientSequence,C=vE({connectionEpoch:I,nextSequence:z.nextServerSequence}),u=0,S.clear(),_(z.snapshot,{type:"grant"});return}if(!C||!I||D===void 0){w("sequence","MESSAGE_BEFORE_GRANT"),R();return}try{C.accept(z)}catch{w("sequence","INVALID_SEQUENCE"),R();return}if(z.type==="heartbeat"){try{m.send(JSON.stringify({version:to,type:"heartbeat.ack",connectionEpoch:I,sequence:D}))}catch{w("send","HEARTBEAT_ACK_SEND_FAILED"),R()}D=D===Number.MAX_SAFE_INTEGER?void 0:D+1;return}_(z.snapshot,{type:"event",event:z.event},!0)},b=()=>{c===m&&(w("close","SOCKET_CLOSED"),c=void 0,F(),A())},x=()=>{w("open","SOCKET_ERROR"),R()};m.addEventListener("open",O),m.addEventListener("message",P),m.addEventListener("close",b),m.addEventListener("error",x),d=F};return{connect:p,subscribeUpdates(m){return t.add(m),()=>t.delete(m)},dispose(){if(h)return;h=!0,T=!1,l(),g!==void 0&&i.clearTimeout(g),g=void 0;const m=c;c=void 0,d?.(),m?.close(1e3,"client disposed"),t.clear()}}}function jE(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 zE(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=jE(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}try{TE((e,t)=>{mr(`console.${e}`,{source:"host",message:t.map(r=>bd(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const UE="/__hb_sdk_bootstrap__",HE="/__hb_sdk__/mobile-launch-redirect",FE="/__hb_sdk__/network",VE="/session/status",BE="/session/request",QE="/session/events",YE=320,GE=1e3,qE=1e3,WE=15e3,qa="dark",Nd=new URL(location.href).searchParams,Ad=Nd.get("mini_url"),ut=Nd.get("ui_preview")==="1",K={device:Ut("#device"),get mobileLanSelect(){return Ut("#mobile-lan-select")},get mobileQrImage(){return Ut("#mobile-qr-image")},get mobileQrStatus(){return Ut("#mobile-qr-status")},storageSnapshot:Ut("#storage-snapshot")};if(!Ad&&!ut)throw K.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Dd=Ad??"about:blank",ie=await zo();Y.openPlatformBaseUrl=ie.openPlatformBaseUrl;Y.devReadiness=ie.devReadiness;Y.miniProgramSupportsDesktop=ie.miniProgramSupportsDesktop;Y.desktopLaunch.workspaceCardsEnabled=ie.workspaceCardsEnabled;let He=ie.lanAddresses,Ur=ie.defaultLanAddressId,wt=ie.mobileLaunchRedirect,xo=ie.nativeAppLaunchUnavailableReason,Hr=ie.devSessionId,no=ie.miniProgramManifestAccessToken,Bt=ie.workspaceCardsEnabled,Fr=ie,jo=Jn(ie),fe=ie.devContext,pe=_n(fe);Ho();let _t=qn(pe),J=!1,$n=0;const Kn=new AbortController;let Re=0,At,ur,Vr=0,qe,io,oo,Fe=0,We=!1,Br,so,Ui=!1;const Jt=tu({apply:ru,waitForLayout:async e=>{await nu(),await iu(e),await ou(e)}});let ao,co,Wa=Date.now(),Qt=!1,$a=Promise.resolve(),Zt=-1,lr=!1,it,uo,lo,Qr,et;const Ln=new Set,fo=pE({onDiagnostic:({action:e,alias:t,detail:r})=>we(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Lt=rE({applyStatus:e=>Cd(e,!0),fetchStatus:e=>vd(Ud(Kn.signal,e)),getCanonicalRevision:()=>Zt,onError:MI,reconcile:()=>sI($n)}),ho=nE({connectEvents:Rd,invalidate:()=>Lt.invalidate(),isDisposed:()=>J,maxDelayMs:WE,minDelayMs:qE,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let Hi=0,Yt="",Fi=!1,mo;await go(!1);xd();zd(jd(ie));ut&&ZE();Zn();ut||await Sd();await Ir("initial");ut||(Rd(),iI());$E();uI();function Td(){!ut&&!J&&(mo=window.setTimeout(()=>{Sd().finally(Td)},1e3))}Td();async function Sd(){if(!(Fi||J)){Fi=!0;try{const e=await fetch(`/__hb_sdk__/device-logs?after=${Hi}&limit=500`,{signal:AbortSignal.any([Kn.signal,AbortSignal.timeout(5e3)])});if(!e.ok)return;const t=await e.json();if(J)return;if(Yt&&t.epoch!==Yt){Hi=0,Yt=t.epoch;return}Yt=t.epoch,Y.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,Ka(n)}Hi=t.nextCursor}catch{}finally{Fi=!1}}}function $E(){window.addEventListener("beforeunload",NI),window.addEventListener("hb-sdk:restart-runtime",_d),window.addEventListener("hb-sdk:refresh-storage",Zn),window.addEventListener("hb-sdk:qr-open-change",Od),window.addEventListener("message",KE),ao=$d(()=>document.querySelector("#host-fullscreen-exit-mount")),co=Kd(()=>Y.devicePresetId,()=>Jt.notifyViewportChange(),{flush:"post"})}function KE(e){const t=e.data;if(e.source===null||!le(t)||t.type!==AE||!le(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=>bd(n)).join(" ")},r.timestamp,r.level==="log"||r.level==="debug"?"log":r.level)}function bd(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
95
+ `);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw ce("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw ce("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 ce("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(lu,{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(fu,{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 ce("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw ce("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!Fa.includes(t))throw ce("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 gE=Object.freeze({[vn]:!0,[Cn]:!0,[Rn]:!0,[Pn]:!0,[kn]:!0,[xn]:!0,[jn]:!0,[zn]:!0,[Un]:!0,[Hn]:!0,[Fn]:!0,[Vn]:!0,[ir]:!0,[nr]:!0,[or]:!0});function pE(e){return new mE(e)}function ce(e,t){return Object.assign(new Error(t),{code:e})}const yE=/^[A-Za-z0-9_-]{22}$/,EE="https://api.xiaoheihe.cn/open_inapp/";function IE(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(!yE.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 wE(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`${EE}#${r}`}function ME(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 NE="__hb_sdk_mini_dev__",AE="hb-sdk:mini-dev-console",DE="__hb_sdk_mini_dev_console_installed__",Ba=DE;function TE(e,t=console){bE(t,e,t)}const SE=["log","debug","info","warn","error"];function bE(e,t,r){if(!r||r[Ba]===!0)return!1;let n=!1;for(const i of SE){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[Ba]=!0),n}const to=1,Qa=64*1024,OE=64,_E=/^[A-Za-z0-9_-]{22}$/;class ge extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function LE(e,t=!1){const r=CE(e,t);switch(ro(r,"Server message"),RE(r),r.type){case"grant":return $t(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),Kt(r.connectionEpoch,"connectionEpoch"),nt(r.nextClientSequence,"nextClientSequence"),nt(r.nextServerSequence,"nextServerSequence"),Ya(r.snapshot),r;case"event":return $t(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),Kt(r.connectionEpoch,"connectionEpoch"),nt(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&$e("event must be account.changed or status.changed"),Ya(r.snapshot),r;case"heartbeat":return $t(r,["version","type","connectionEpoch","sequence"],"heartbeat"),Kt(r.connectionEpoch,"connectionEpoch"),nt(r.sequence,"sequence"),r;default:return $e("Unknown server message type")}}function vE(e){const t=e.connectionEpoch;Kt(t,"connectionEpoch"),nt(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(Kt(n.connectionEpoch,"connectionEpoch"),nt(n.sequence,"sequence"),n.connectionEpoch!==t)throw new ge("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new ge("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new ge("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function CE(e,t){if(t)throw new ge("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new ge("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Qa)throw new ge("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Qa)throw new ge("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return PE(e),JSON.parse(e)}catch(r){throw r instanceof ge?r:new ge("INVALID_JSON","Channel frame must contain strict JSON")}}function Ya(e){ro(e,"snapshot"),$t(e,["account","permissions"],"snapshot"),ro(e.account,"snapshot.account"),$t(e.account,["revision"],"snapshot.account"),nt(e.account.revision,"snapshot.account.revision"),Ky(e.permissions)||$e("snapshot.permissions is invalid")}function RE(e){e.version!==to&&$e("version must be 1")}function ro(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&$e(`${t} must be a plain JSON object`)}function $t(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)))&&$e(`${r} fields are invalid`)}function nt(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&$e(`${t} must be a non-negative safe integer`)}function Kt(e,t){(typeof e!="string"||!_E.test(e))&&$e(`${t} must be a 22-character base64url value`)}function $e(e){throw new ge("INVALID_MESSAGE",e)}function PE(e){new kE(e).scan()}class kE{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>=OE)throw new ge("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 ge("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 Ga=[1e3,2e3,4e3,8e3,15e3];function xE(e){const t=new Set,r=e.webSocketFactory??(m=>new WebSocket(m)),n=e.randomValues??(m=>crypto.getRandomValues(m)),i=e.timers??{clearTimeout:m=>window.clearTimeout(m),setTimeout:(m,E)=>window.setTimeout(m,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,d,f,h=!1,u=0,g,T=!1,M=!1;const S=new Set,w=(m,E)=>{if(!(!e.onDiagnostic||S.has(m))){S.add(m);try{e.onDiagnostic({phase:m,...E?{code:E}:{}})}catch{}}},_=(m,E,I=!1)=>{if(f&&m.account.revision<f.account.revision)return;const D=f&&JSON.stringify(m)===JSON.stringify(f);if(f=m,!(D&&!I))for(const C of t)C(m,E)},A=()=>{if(h||g!==void 0||c)return;const m=Ga[Math.min(u,Ga.length-1)];u+=1,g=i.setTimeout(()=>{g=void 0,p()},m)},v=()=>{h||!T||c||(g!==void 0&&(i.clearTimeout(g),g=void 0),p())},U=()=>{a()&&v()},L=()=>{s&&!s.hidden&&v()},N=()=>{M||(M=!0,o?.addEventListener("online",U),s?.addEventListener("visibilitychange",L))},l=()=>{M&&(M=!1,o?.removeEventListener("online",U),s?.removeEventListener("visibilitychange",L))},p=()=>{if(h||c)return;T=!0,N(),g!==void 0&&(i.clearTimeout(g),g=void 0);let m,E;try{m=r(e.url)}catch{w("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),A();return}try{E=zE(n)}catch{w("entropy","NONCE_GENERATION_FAILED");try{m?.close(1011,"channel initialization failed")}catch{}A();return}c=m;let I,D,C;const F=()=>{m.removeEventListener("open",O),m.removeEventListener("message",P),m.removeEventListener("close",b),m.removeEventListener("error",x),d===F&&(d=void 0)},R=()=>{if(c===m){c=void 0,F();try{m.close(1008,"invalid channel state")}catch{}A()}},O=()=>{if(!(h||c!==m))try{m.send(JSON.stringify({version:to,type:"hello",csrfToken:e.csrfToken,clientNonce:E}))}catch{w("send","HELLO_SEND_FAILED"),R()}},P=j=>{if(h||c!==m)return;if(typeof j.data!="string"){w("parse","TEXT_FRAME_REQUIRED"),R();return}let z;try{z=LE(j.data)}catch(B){w("parse",B instanceof ge?B.code:"INVALID_MESSAGE"),R();return}if(z.type==="grant"){if(C){w("sequence","DUPLICATE_GRANT"),R();return}I=z.connectionEpoch,D=z.nextClientSequence,C=vE({connectionEpoch:I,nextSequence:z.nextServerSequence}),u=0,S.clear(),_(z.snapshot,{type:"grant"});return}if(!C||!I||D===void 0){w("sequence","MESSAGE_BEFORE_GRANT"),R();return}try{C.accept(z)}catch{w("sequence","INVALID_SEQUENCE"),R();return}if(z.type==="heartbeat"){try{m.send(JSON.stringify({version:to,type:"heartbeat.ack",connectionEpoch:I,sequence:D}))}catch{w("send","HEARTBEAT_ACK_SEND_FAILED"),R()}D=D===Number.MAX_SAFE_INTEGER?void 0:D+1;return}_(z.snapshot,{type:"event",event:z.event},!0)},b=()=>{c===m&&(w("close","SOCKET_CLOSED"),c=void 0,F(),A())},x=()=>{w("open","SOCKET_ERROR"),R()};m.addEventListener("open",O),m.addEventListener("message",P),m.addEventListener("close",b),m.addEventListener("error",x),d=F};return{connect:p,subscribeUpdates(m){return t.add(m),()=>t.delete(m)},dispose(){if(h)return;h=!0,T=!1,l(),g!==void 0&&i.clearTimeout(g),g=void 0;const m=c;c=void 0,d?.(),m?.close(1e3,"client disposed"),t.clear()}}}function jE(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 zE(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=jE(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}try{TE((e,t)=>{mr(`console.${e}`,{source:"host",message:t.map(r=>Od(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const UE="/__hb_sdk_bootstrap__",HE="/__hb_sdk__/mobile-launch-redirect",FE="/__hb_sdk__/network",VE="/session/status",BE="/session/request",QE="/session/events",YE=320,GE=1e3,qE=1e3,WE=15e3,qa="dark",Ad=new URL(location.href).searchParams,Dd=Ad.get("mini_url"),ut=Ad.get("ui_preview")==="1",K={device:Ut("#device"),get mobileLanSelect(){return Ut("#mobile-lan-select")},get mobileQrImage(){return Ut("#mobile-qr-image")},get mobileQrStatus(){return Ut("#mobile-qr-status")},storageSnapshot:Ut("#storage-snapshot")};if(!Dd&&!ut)throw K.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Td=Dd??"about:blank",ie=await zo();Y.openPlatformBaseUrl=ie.openPlatformBaseUrl;Y.devReadiness=ie.devReadiness;Y.miniProgramSupportsDesktop=ie.miniProgramSupportsDesktop;Y.desktopLaunch.workspaceCardsEnabled=ie.workspaceCardsEnabled;let He=ie.lanAddresses,Ur=ie.defaultLanAddressId,wt=ie.mobileLaunchRedirect,xo=ie.nativeAppLaunchUnavailableReason,Hr=ie.devSessionId,no=ie.miniProgramManifestAccessToken,Bt=ie.workspaceCardsEnabled,Fr=ie,jo=Jn(ie),fe=ie.devContext,pe=_n(fe);Ho();let _t=qn(pe),J=!1,$n=0;const Kn=new AbortController;let Re=0,At,ur,Vr=0,qe,io,oo,Fe=0,We=!1,Br,so,Ui=!1;const Jt=ru({apply:nu,waitForLayout:async e=>{await iu(),await ou(e),await su(e)}});let ao,co,Wa=Date.now(),Qt=!1,$a=Promise.resolve(),Zt=-1,lr=!1,it,uo,lo,Qr,et;const Ln=new Set,fo=pE({onDiagnostic:({action:e,alias:t,detail:r})=>we(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Lt=rE({applyStatus:e=>Rd(e,!0),fetchStatus:e=>Cd(Hd(Kn.signal,e)),getCanonicalRevision:()=>Zt,onError:MI,reconcile:()=>sI($n)}),ho=nE({connectEvents:Pd,invalidate:()=>Lt.invalidate(),isDisposed:()=>J,maxDelayMs:WE,minDelayMs:qE,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let Hi=0,Yt="",Fi=!1,mo;await go(!1);jd();Ud(zd(ie));ut&&ZE();Zn();ut||await bd();await Ir("initial");ut||(Pd(),iI());$E();uI();function Sd(){!ut&&!J&&(mo=window.setTimeout(()=>{bd().finally(Sd)},1e3))}Sd();async function bd(){if(!(Fi||J)){Fi=!0;try{const e=await fetch(`/__hb_sdk__/device-logs?after=${Hi}&limit=500`,{signal:AbortSignal.any([Kn.signal,AbortSignal.timeout(5e3)])});if(!e.ok)return;const t=await e.json();if(J)return;if(Yt&&t.epoch!==Yt){Hi=0,Yt=t.epoch;return}Yt=t.epoch,Y.logDevices=t.devices,t.gap&&mr("console.warn",{message:"部分设备日志已超出服务器缓冲,存在日志缺口"});for(const r of t.items){const n=$d(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,Ka(n)}Hi=t.nextCursor}catch{}finally{Fi=!1}}}function $E(){window.addEventListener("beforeunload",NI),window.addEventListener("hb-sdk:restart-runtime",Ld),window.addEventListener("hb-sdk:refresh-storage",Zn),window.addEventListener("hb-sdk:qr-open-change",_d),window.addEventListener("message",KE),ao=Kd(()=>document.querySelector("#host-fullscreen-exit-mount")),co=Jd(()=>Y.devicePresetId,()=>Jt.notifyViewportChange(),{flush:"post"})}function KE(e){const t=e.data;if(e.source===null||!le(t)||t.type!==AE||!le(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
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 Od(e){const t=e.detail?.open===!0;t!==We&&(We=t,Fe+=1,Xn(),t&&(K.mobileLanSelect.addEventListener("change",JE),Pd(),wr()))}function JE(){We&&wr()}function _d(){fr("manual restart")}function fr(e){J||At!==void 0||(we("runtime.restart",{boundary:Re+1}),At=window.setTimeout(()=>{At=void 0,J||Ir(e)},0))}async function Ir(e){if(Qt)return;const t=++Re;if(ur=void 0,hr(e),Ld(),Y.runtimeStatus="loading",Vd(_t),K.device.replaceChildren(),ut){K.device.innerHTML=`
97
+ `):"")||`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}return String(e)}function _d(e){const t=e.detail?.open===!0;t!==We&&(We=t,Fe+=1,Xn(),t&&(K.mobileLanSelect.addEventListener("change",JE),kd(),wr()))}function JE(){We&&wr()}function Ld(){fr("manual restart")}function fr(e){J||At!==void 0||(we("runtime.restart",{boundary:Re+1}),At=window.setTimeout(()=>{At=void 0,J||Ir(e)},0))}async function Ir(e){if(Qt)return;const t=++Re;if(ur=void 0,hr(e),vd(),Y.runtimeStatus="loading",Bd(_t),K.device.replaceChildren(),ut){K.device.innerHTML=`
98
98
  <div class="browser-mock-preview">
99
99
  <span class="browser-mock-preview__icon">UI</span>
100
100
  <strong>Browser Mock</strong>
101
101
  <small>mp_preview</small>
102
- </div>`,Y.runtimeStatus="idle";return}const r=document.createElement("iframe");r.dataset.testid="device-iframe",r.title="小程序预览",r.allow="clipboard-read; clipboard-write",r.name=NE,K.device.appendChild(r);const n=new AbortController;io=n;let i=!1;try{const o=await Ty(XE(n.signal,t));if(J||t!==Re){o.dispose();return}oo=o.dispose,o.ports.companion=fo.port;const s=cy({iframe:r,ports:o.ports,environment:o.environment,hostCapabilities:{...o.hostCapabilities,...gE},authPresentation:o.authPresentation,companionPresentation:fo.presentation,resolveLaunchConfiguration:async()=>(await o.resolveLaunch()).configuration,dispose:o.dispose,onReady:()=>{Y.runtimeStatus="ready",we("runtime.ready",{generation:t})},onTrace:a=>rI(t,a),onError:()=>{i=!0,Y.runtimeStatus="error"},onCapabilityTrace:a=>{Yt||we(a.method,a),a.method==="storage.setStorage"&&a.outcome==="success"&&Zn()}});qe=s,await s.start()}catch(o){if(J||t!==Re||n.signal.aborted)return;Y.runtimeStatus="error",i||we("runtime.start.failed",Jd(o))}}function ZE(){we("runtime.ready",{generation:1}),mr("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info"),we("user.getInfo",{durationMs:34,outcome:"success"}),we("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function XE(e,t){const r=pe,n=Zy(r.runtimePermissions,_t,r);return{signal:e,account:{async getCurrentUserId(){return(await go(!1,e)).user_id},async ensureAuthenticated({signal:i}){await go(!1,i)},onChange(i){return Ln.add(i),()=>Ln.delete(i)}},authenticatedRequest:nI,storage:{area:"local",storage:localStorage},presentation:hE({close:async()=>{Za(),qe?.destroy(),Jt.reset(),Ld(),Y.runtimeStatus="closed"},reload:()=>{!J&&t===Re&&(ur=t)},onNavigationBarStyleChange:Ja,pushLog:we,getDeviceMetrics:()=>su.value,applyDisplay:(i,o)=>Jt.applyDisplay(i,o),isCapsuleHidden:()=>Y.display.capsuleHidden,onViewportChange:i=>Jt.onViewportChange(i)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:i=>{document.title=i}},resolveLaunch:async()=>({configuration:sE({launchUrl:Dd,runtimePermissions:n,...r.miniProgramId?{miniProgramId:r.miniProgramId}:{},operatingSystem:Zd.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:i=>oE(i)},protocol:eI()}}function eI(){return{async invoke(e){we("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:tI(e)})}}}function tI(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 le(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function Ld(){document.documentElement.dataset.navigationBarStyle=qa,Ja(qa)}function rI(e,t){const r=Xd(t,e);r&&Ka(r),!(t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||ur!==e||e!==Re)&&(ur=void 0,fr("navigation.reload"))}async function nI(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 Uo(n?FE:BE,{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&&Lt.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function go(e,t){const r=$n,n=await vd(Ud(Kn.signal,t));return Hd(r)?Cd(n,e).status:po()}async function vd(e){return await(await fetch(VE,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Cd(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Zt)return{changed:!1,status:po()};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!==Zt||e.authenticated!==lr||r!==it||n!==uo||i!==lo;return Zt=e.revision,lr=e.authenticated,it=r,uo=n,lo=i,xd(),t&&o&&Ln.forEach(s=>s(it)),{changed:o,status:po()}}function po(){return{authenticated:lr,revision:Zt,...lr&&it?{user_id:it}:{}}}function iI(){if(!(!ie.csrfToken||J))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",et=xE({csrfToken:ie.csrfToken,onDiagnostic:t=>we("channel.diagnostic",t),url:e.toString()}),et.subscribeUpdates((t,r)=>oI(t,r)),et.connect()}catch{et?.dispose(),et=void 0}}function oI(e,t){Lt.invalidate(e.account.revision),TI(_t,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Ir("status changed"):(_t=Vd(e.permissions),aI())}function Rd(){if(Qr?.close(),Qr=void 0,!it||J)return;const e=new EventSource(QE);Qr=e,e.addEventListener("account-invalidated",()=>{Lt.invalidate()}),e.addEventListener("account-revision",()=>{Lt.invalidate()}),e.onopen=()=>{ho.reset()},e.onerror=()=>{e.close(),ho.schedule()}}async function sI(e){Hd(e)&&await Ir("account revision changed")}function hr(e){Vr+=1,Za(),qe&&fo.reset(),qe?.destroy(),qe=void 0,io?.abort(new DOMException(e,"AbortError")),io=void 0,oo?.(),oo=void 0,Jt.reset()}async function aI(){J||(await Ir("permission changed"),!J&&await wr())}async function zo(){const e=await fetch(UE,{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(!le(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Fd(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new vt;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:cI(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:dI(t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(DI):[],loginAvailable:t.loginAvailable===!0,miniProgram:II(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 cI(e){if(!le(e))return;const t=s=>{if(!(!le(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||!le(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=>le(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 dI(e,t){return le(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:le(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 Uo(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 uI(){Fo(),ut||(so=window.setInterval(()=>{EI()},GE))}function Pd(e=K.mobileLanSelect.options.length>0?K.mobileLanSelect.value:void 0){K.mobileLanSelect.replaceChildren();for(const t of He){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,K.mobileLanSelect.appendChild(r)}e&&He.some(({id:t})=>t===e)?K.mobileLanSelect.value=e:Ur&&He.some(({id:t})=>t===Ur)?K.mobileLanSelect.value=Ur:He[0]&&(K.mobileLanSelect.value=He[0].id),K.mobileLanSelect.disabled=He.length===0}async function wr(){if(J)return;const e=++Fe;if(Xn(),fe.source!=="remote"||!fe.localDevLaunchToken||fe.expiresAt!==void 0&&fe.expiresAt<=Date.now()){K.mobileQrImage.removeAttribute("src"),K.mobileQrStatus.textContent=xo||"需要有效的本地调试启动票";return}const t=AI();if(!t?.mobileAppQrPayload){K.mobileQrImage.removeAttribute("src"),K.mobileQrStatus.textContent="未发现可用的局域网地址";return}K.mobileQrStatus.textContent="正在生成二维码...";try{const r=await gI(t);if(e!==Fe||J)return;const n=await lI(r.address,r.expiresAt);if(e!==Fe||J)return;const i=await Wy.toDataURL(n.payload,{width:YE,margin:1});if(e!==Fe||J)return;K.mobileQrImage.src=i,K.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,yI(n.expiresAt,e)}catch(r){if(e!==Fe||J)return;if(r instanceof vt){Yr();return}K.mobileQrImage.removeAttribute("src"),K.mobileQrStatus.textContent=Vo(r)}}async function lI(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await fI(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:wE(IE({host:e.address,port:location.port,token:n.token}))}}catch{throw new vt}}async function fI(e,t){if(wt?.addressId===e.id)return wt;if(!wt)return;const r=await Uo(HE,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:wt.token})});if(!r.ok)throw new vt;const n=await r.json(),i=le(n)?Fd({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new vt;return wt=i,Fr={...Fr,mobileLaunchRedirect:i},jo=Jn(Fr),i}async function hI(e){const t=await zo(),r=mI(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return kd(t),{...r,mobileAppQrPayload:n}}function mI(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function kd(e){const t=rt(pe);Y.devReadiness=e.devReadiness,Y.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,Bt=e.workspaceCardsEnabled,Fr=e,jo=Jn(e),fe=e.devContext,pe=_n(fe),_t=qn(pe),Ho(),He=e.lanAddresses,Ur=e.defaultLanAddressId,wt=e.mobileLaunchRedirect,xo=e.nativeAppLaunchUnavailableReason,Hr=e.devSessionId,no=e.miniProgramManifestAccessToken,zd(jd(e)),We&&Pd(),Fo(),t!==rt(pe)&&(Re+=1,hr("local permission context changed"),fr("local permission context changed"))}function Ho(){Y.localPermissions=ME(pe),Y.devContextWarning=pe.source==="anonymous"?"未连接线上上下文":pe.warning?"本地上下文受限,请检查 CLI 状态":""}function Fo(){let e;try{e=eu(Dd)}catch{}const t=fe.miniProgramId?.trim().toLowerCase();let r=xo?.trim()??"";!r&&(fe.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!fe.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&Bt&&!Hr&&(r="本地调试会话尚未就绪"),!r&&fe.expiresAt!==void 0&&fe.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),Xa({...e?{address:e}:{},...t?{miniProgramId:t}:{},...Bt&&Hr?{devSessionId:Hr}:{},...Bt&&no?{miniProgramManifestToken:no}:{},workspaceCardsEnabled:Bt,ready:r==="",...r?{unavailableReason:r}:{}})}class vt extends Error{}async function gI(e){const t=$a.then(()=>pI(e));return $a=t.then(()=>{},()=>{}),t}async function pI(e){const t=new URL(e.appUrl),r=new URL($y,location.origin),n=await Uo(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:Xy(fe)})}),i=await n.json();if(!n.ok||!le(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await hI(e.id),expiresAt:i.expires_at}}function yI(e,t){Br=window.setTimeout(()=>{!J&&We&&t===Fe&&wr()},Math.max(1e3,e-Date.now()-3e4))}async function EI(){if(!(Ui||J)){Ui=!0;try{const e=await zo();Wa=Date.now();const t=Qt;Qt=!1;const r=Jn(e);if(!t&&r===jo&&rt(_n(e.devContext))===rt(pe))return;kd(e),t&&fr("CLI dev session reconnected"),We&&wr()}catch(e){e instanceof vt&&Yr();const t=_n(fe);rt(t)!==rt(pe)&&(pe=t,_t=qn(pe),Ho(),Re+=1,hr("local permission context expired"),fr("local permission context expired"),Fo(),We&&Yr()),Date.now()-Wa>=3e4&&!Qt&&(Qt=!0,Re+=1,hr("CLI dev session disconnected"),K.device.replaceChildren(),Y.runtimeStatus="closed",Y.localPermissions=[],Y.devContextWarning="调试会话已断开",Xa({ready:!1,unavailableReason:"调试会话已断开"}),Y.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},We&&Yr())}finally{Ui=!1}}}function Yr(){Fe+=1,Xn(),K.mobileQrImage.removeAttribute("src"),K.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 xd(){if(!lr){Y.account={authenticated:!1,avatar:"",nickname:"未登录"};return}Y.account={authenticated:!0,avatar:lo??"",nickname:uo||it||"已登录"}}function jd(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function zd(e){if(!!!e?.miniProgramId||!e){Y.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}Y.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function II(e){if(e===null)return null;if(!le(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 Zn(){const e=++Vr,t=qe,r=t?.diagnostics.storage;if(!r){Y.storage=[],Y.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(J||e!==Vr||t!==qe)return;Y.storage=n.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),Y.storageError=""}catch(n){if(J||e!==Vr||t!==qe)return;Y.storage=[],Y.storageError=Vo(n)}}function wI(e,t){we("host.message",{message:e,status:t})}function MI(e){J||wI(Vo(e),"error")}function we(e,t){mr(e,t)}function NI(){mo!==void 0&&window.clearTimeout(mo),!J&&(J=!0,window.removeEventListener("hb-sdk:restart-runtime",_d),window.removeEventListener("hb-sdk:refresh-storage",Zn),window.removeEventListener("hb-sdk:qr-open-change",Od),$n+=1,Kn.abort(new DOMException("Browser Dev Host disposed","AbortError")),Lt.dispose(),Re+=1,hr("Browser Dev Host disposed"),Qr?.close(),et?.dispose(),et=void 0,ho.dispose(),ur=void 0,At!==void 0&&window.clearTimeout(At),At=void 0,Xn(),so!==void 0&&window.clearInterval(so),Ln.clear(),ao?.(),ao=void 0,co?.(),co=void 0)}function Xn(){Br!==void 0&&window.clearTimeout(Br),Br=void 0}function Ud(e,t){return t?AbortSignal.any([e,t]):e}function Hd(e){return!J&&e===$n}function AI(){return He.find(({id:e})=>e===K.mobileLanSelect.value)}function DI(e){return le(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 Fd(e){if(!(!le(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 TI(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function Vo(e){return e instanceof Error&&e.message?e.message:"操作失败"}function le(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ut(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}
102
+ </div>`,Y.runtimeStatus="idle";return}const r=document.createElement("iframe");r.dataset.testid="device-iframe",r.title="小程序预览",r.allow="clipboard-read; clipboard-write",r.name=NE,K.device.appendChild(r);const n=new AbortController;io=n;let i=!1;try{const o=await Ty(XE(n.signal,t));if(J||t!==Re){o.dispose();return}oo=o.dispose,o.ports.companion=fo.port;const s=cy({iframe:r,ports:o.ports,environment:o.environment,hostCapabilities:{...o.hostCapabilities,...gE},authPresentation:o.authPresentation,companionPresentation:fo.presentation,resolveLaunchConfiguration:async()=>(await o.resolveLaunch()).configuration,dispose:o.dispose,onReady:()=>{Y.runtimeStatus="ready",we("runtime.ready",{generation:t})},onTrace:a=>rI(t,a),onError:()=>{i=!0,Y.runtimeStatus="error"},onCapabilityTrace:a=>{Yt||we(a.method,a),a.method==="storage.setStorage"&&a.outcome==="success"&&Zn()}});qe=s,await s.start()}catch(o){if(J||t!==Re||n.signal.aborted)return;Y.runtimeStatus="error",i||we("runtime.start.failed",Zd(o))}}function ZE(){we("runtime.ready",{generation:1}),mr("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info"),we("user.getInfo",{durationMs:34,outcome:"success"}),we("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function XE(e,t){const r=pe,n=Zy(r.runtimePermissions,_t,r);return{signal:e,account:{async getCurrentUserId(){return(await go(!1,e)).user_id},async ensureAuthenticated({signal:i}){await go(!1,i)},onChange(i){return Ln.add(i),()=>Ln.delete(i)}},authenticatedRequest:nI,storage:{area:"local",storage:localStorage},presentation:hE({close:async()=>{Za(),qe?.destroy(),Jt.reset(),vd(),Y.runtimeStatus="closed"},reload:()=>{!J&&t===Re&&(ur=t)},onNavigationBarStyleChange:Ja,pushLog:we,getDeviceMetrics:()=>au.value,applyDisplay:(i,o)=>Jt.applyDisplay(i,o),isCapsuleHidden:()=>Y.display.capsuleHidden,onViewportChange:i=>Jt.onViewportChange(i)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:i=>{document.title=i}},resolveLaunch:async()=>({configuration:sE({launchUrl:Td,runtimePermissions:n,...r.miniProgramId?{miniProgramId:r.miniProgramId}:{},operatingSystem:Xd.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:i=>oE(i)},protocol:eI()}}function eI(){return{async invoke(e){we("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:tI(e)})}}}function tI(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 le(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function vd(){document.documentElement.dataset.navigationBarStyle=qa,Ja(qa)}function rI(e,t){const r=eu(t,e);r&&Ka(r),!(t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||ur!==e||e!==Re)&&(ur=void 0,fr("navigation.reload"))}async function nI(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 Uo(n?FE:BE,{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&&Lt.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function go(e,t){const r=$n,n=await Cd(Hd(Kn.signal,t));return Fd(r)?Rd(n,e).status:po()}async function Cd(e){return await(await fetch(VE,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Rd(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Zt)return{changed:!1,status:po()};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!==Zt||e.authenticated!==lr||r!==it||n!==uo||i!==lo;return Zt=e.revision,lr=e.authenticated,it=r,uo=n,lo=i,jd(),t&&o&&Ln.forEach(s=>s(it)),{changed:o,status:po()}}function po(){return{authenticated:lr,revision:Zt,...lr&&it?{user_id:it}:{}}}function iI(){if(!(!ie.csrfToken||J))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",et=xE({csrfToken:ie.csrfToken,onDiagnostic:t=>we("channel.diagnostic",t),url:e.toString()}),et.subscribeUpdates((t,r)=>oI(t,r)),et.connect()}catch{et?.dispose(),et=void 0}}function oI(e,t){Lt.invalidate(e.account.revision),TI(_t,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Ir("status changed"):(_t=Bd(e.permissions),aI())}function Pd(){if(Qr?.close(),Qr=void 0,!it||J)return;const e=new EventSource(QE);Qr=e,e.addEventListener("account-invalidated",()=>{Lt.invalidate()}),e.addEventListener("account-revision",()=>{Lt.invalidate()}),e.onopen=()=>{ho.reset()},e.onerror=()=>{e.close(),ho.schedule()}}async function sI(e){Fd(e)&&await Ir("account revision changed")}function hr(e){Vr+=1,Za(),qe&&fo.reset(),qe?.destroy(),qe=void 0,io?.abort(new DOMException(e,"AbortError")),io=void 0,oo?.(),oo=void 0,Jt.reset()}async function aI(){J||(await Ir("permission changed"),!J&&await wr())}async function zo(){const e=await fetch(UE,{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(!le(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Vd(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new vt;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:cI(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:dI(t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(DI):[],loginAvailable:t.loginAvailable===!0,miniProgram:II(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 cI(e){if(!le(e))return;const t=s=>{if(!(!le(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||!le(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=>le(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 dI(e,t){return le(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:le(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 Uo(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 uI(){Fo(),ut||(so=window.setInterval(()=>{EI()},GE))}function kd(e=K.mobileLanSelect.options.length>0?K.mobileLanSelect.value:void 0){K.mobileLanSelect.replaceChildren();for(const t of He){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,K.mobileLanSelect.appendChild(r)}e&&He.some(({id:t})=>t===e)?K.mobileLanSelect.value=e:Ur&&He.some(({id:t})=>t===Ur)?K.mobileLanSelect.value=Ur:He[0]&&(K.mobileLanSelect.value=He[0].id),K.mobileLanSelect.disabled=He.length===0}async function wr(){if(J)return;const e=++Fe;if(Xn(),fe.source!=="remote"||!fe.localDevLaunchToken||fe.expiresAt!==void 0&&fe.expiresAt<=Date.now()){K.mobileQrImage.removeAttribute("src"),K.mobileQrStatus.textContent=xo||"需要有效的本地调试启动票";return}const t=AI();if(!t?.mobileAppQrPayload){K.mobileQrImage.removeAttribute("src"),K.mobileQrStatus.textContent="未发现可用的局域网地址";return}K.mobileQrStatus.textContent="正在生成二维码...";try{const r=await gI(t);if(e!==Fe||J)return;const n=await lI(r.address,r.expiresAt);if(e!==Fe||J)return;const i=await Wy.toDataURL(n.payload,{width:YE,margin:1});if(e!==Fe||J)return;K.mobileQrImage.src=i,K.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,yI(n.expiresAt,e)}catch(r){if(e!==Fe||J)return;if(r instanceof vt){Yr();return}K.mobileQrImage.removeAttribute("src"),K.mobileQrStatus.textContent=Vo(r)}}async function lI(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await fI(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:wE(IE({host:e.address,port:location.port,token:n.token}))}}catch{throw new vt}}async function fI(e,t){if(wt?.addressId===e.id)return wt;if(!wt)return;const r=await Uo(HE,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:wt.token})});if(!r.ok)throw new vt;const n=await r.json(),i=le(n)?Vd({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new vt;return wt=i,Fr={...Fr,mobileLaunchRedirect:i},jo=Jn(Fr),i}async function hI(e){const t=await zo(),r=mI(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return xd(t),{...r,mobileAppQrPayload:n}}function mI(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function xd(e){const t=rt(pe);Y.devReadiness=e.devReadiness,Y.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,Bt=e.workspaceCardsEnabled,Fr=e,jo=Jn(e),fe=e.devContext,pe=_n(fe),_t=qn(pe),Ho(),He=e.lanAddresses,Ur=e.defaultLanAddressId,wt=e.mobileLaunchRedirect,xo=e.nativeAppLaunchUnavailableReason,Hr=e.devSessionId,no=e.miniProgramManifestAccessToken,Ud(zd(e)),We&&kd(),Fo(),t!==rt(pe)&&(Re+=1,hr("local permission context changed"),fr("local permission context changed"))}function Ho(){Y.localPermissions=ME(pe),Y.devContextWarning=pe.source==="anonymous"?"未连接线上上下文":pe.warning?"本地上下文受限,请检查 CLI 状态":""}function Fo(){let e;try{e=tu(Td)}catch{}const t=fe.miniProgramId?.trim().toLowerCase();let r=xo?.trim()??"";!r&&(fe.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!fe.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&Bt&&!Hr&&(r="本地调试会话尚未就绪"),!r&&fe.expiresAt!==void 0&&fe.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),Xa({...e?{address:e}:{},...t?{miniProgramId:t}:{},...Bt&&Hr?{devSessionId:Hr}:{},...Bt&&no?{miniProgramManifestToken:no}:{},workspaceCardsEnabled:Bt,ready:r==="",...r?{unavailableReason:r}:{}})}class vt extends Error{}async function gI(e){const t=$a.then(()=>pI(e));return $a=t.then(()=>{},()=>{}),t}async function pI(e){const t=new URL(e.appUrl),r=new URL($y,location.origin),n=await Uo(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:Xy(fe)})}),i=await n.json();if(!n.ok||!le(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await hI(e.id),expiresAt:i.expires_at}}function yI(e,t){Br=window.setTimeout(()=>{!J&&We&&t===Fe&&wr()},Math.max(1e3,e-Date.now()-3e4))}async function EI(){if(!(Ui||J)){Ui=!0;try{const e=await zo();Wa=Date.now();const t=Qt;Qt=!1;const r=Jn(e);if(!t&&r===jo&&rt(_n(e.devContext))===rt(pe))return;xd(e),t&&fr("CLI dev session reconnected"),We&&wr()}catch(e){e instanceof vt&&Yr();const t=_n(fe);rt(t)!==rt(pe)&&(pe=t,_t=qn(pe),Ho(),Re+=1,hr("local permission context expired"),fr("local permission context expired"),Fo(),We&&Yr()),Date.now()-Wa>=3e4&&!Qt&&(Qt=!0,Re+=1,hr("CLI dev session disconnected"),K.device.replaceChildren(),Y.runtimeStatus="closed",Y.localPermissions=[],Y.devContextWarning="调试会话已断开",Xa({ready:!1,unavailableReason:"调试会话已断开"}),Y.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},We&&Yr())}finally{Ui=!1}}}function Yr(){Fe+=1,Xn(),K.mobileQrImage.removeAttribute("src"),K.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 jd(){if(!lr){Y.account={authenticated:!1,avatar:"",nickname:"未登录"};return}Y.account={authenticated:!0,avatar:lo??"",nickname:uo||it||"已登录"}}function zd(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Ud(e){if(!!!e?.miniProgramId||!e){Y.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}Y.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function II(e){if(e===null)return null;if(!le(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 Zn(){const e=++Vr,t=qe,r=t?.diagnostics.storage;if(!r){Y.storage=[],Y.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(J||e!==Vr||t!==qe)return;Y.storage=n.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),Y.storageError=""}catch(n){if(J||e!==Vr||t!==qe)return;Y.storage=[],Y.storageError=Vo(n)}}function wI(e,t){we("host.message",{message:e,status:t})}function MI(e){J||wI(Vo(e),"error")}function we(e,t){mr(e,t)}function NI(){mo!==void 0&&window.clearTimeout(mo),!J&&(J=!0,window.removeEventListener("hb-sdk:restart-runtime",Ld),window.removeEventListener("hb-sdk:refresh-storage",Zn),window.removeEventListener("hb-sdk:qr-open-change",_d),$n+=1,Kn.abort(new DOMException("Browser Dev Host disposed","AbortError")),Lt.dispose(),Re+=1,hr("Browser Dev Host disposed"),Qr?.close(),et?.dispose(),et=void 0,ho.dispose(),ur=void 0,At!==void 0&&window.clearTimeout(At),At=void 0,Xn(),so!==void 0&&window.clearInterval(so),Ln.clear(),ao?.(),ao=void 0,co?.(),co=void 0)}function Xn(){Br!==void 0&&window.clearTimeout(Br),Br=void 0}function Hd(e,t){return t?AbortSignal.any([e,t]):e}function Fd(e){return!J&&e===$n}function AI(){return He.find(({id:e})=>e===K.mobileLanSelect.value)}function DI(e){return le(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 Vd(e){if(!(!le(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 Bd(e){return{networkRequest:{...e.networkRequest}}}function TI(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function Vo(e){return e instanceof Error&&e.message?e.message:"操作失败"}function le(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ut(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}