@heybox/hb-sdk 0.8.0 → 0.8.1-alpha.2

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 (39) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +19 -0
  3. package/dist/cli-chunks/{build-PYCNacya.cjs → build-FQoALfGC.cjs} +5 -5
  4. package/dist/cli-chunks/{context-m2W2XbL0.cjs → context-CA_Q1lyH.cjs} +2 -2
  5. package/dist/cli-chunks/{create-BdAg3WGA.cjs → create-BjIl4hy4.cjs} +1 -1
  6. package/dist/cli-chunks/{dev-CyZuw7Yn.cjs → dev-CiPQYsW_.cjs} +9 -9
  7. package/dist/cli-chunks/{doctor-DU8rCfUF.cjs → doctor-CS6c3n-W.cjs} +1 -1
  8. package/dist/cli-chunks/{index-MMW2ibQm.cjs → index-BEn7WaqA.cjs} +15 -15
  9. package/dist/cli-chunks/{index-DATObqzK.cjs → index-CsP_x6y6.cjs} +2 -2
  10. package/dist/cli-chunks/{index.esm-BiAaAUFC.cjs → index.esm-DeEc_-uV.cjs} +7 -7
  11. package/dist/cli-chunks/{login-B3TThMss.cjs → login-BENCVgaQ.cjs} +2 -2
  12. package/dist/cli-chunks/{project-vite-BQj8YLI4.cjs → project-vite-BO8oOfcs.cjs} +1 -1
  13. package/dist/cli-chunks/{remote-DNvI7tHH.cjs → remote-IiVCXcSq.cjs} +7 -7
  14. package/dist/cli-chunks/{runtime-gate-BEFp1w_s.cjs → runtime-gate-BMSY22AL.cjs} +1 -1
  15. package/dist/cli-chunks/{runtime-permission-env-CtL8rsjB.cjs → runtime-permission-env-BPRwn4Yc.cjs} +1 -1
  16. package/dist/cli-chunks/{session-DjBkjaF8.cjs → session-C0eIKZ6V.cjs} +1 -1
  17. package/dist/cli-chunks/{skill-cR_wnaw2.cjs → skill-DpInwbiA.cjs} +2 -2
  18. package/dist/cli-chunks/{version-yEn1E2Bg.cjs → version-BONZQWPR.cjs} +1 -1
  19. package/dist/cli.cjs +1 -1
  20. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DzEst9n7.js +99 -0
  21. package/dist/devtools/browser-dev-host/assets/{index-C5MZZDa5.js → index-B-NHlLsr.js} +2 -2
  22. package/dist/devtools/browser-dev-host/index.html +1 -1
  23. package/dist/index.cjs.js +83 -2
  24. package/dist/index.esm.js +83 -3
  25. package/dist/vite.cjs.js +1 -1
  26. package/dist/vite.esm.js +1 -1
  27. package/package.json +8 -10
  28. package/skill/SKILL.md +3 -0
  29. package/skill/references/api-protocol.md +7 -3
  30. package/skill/references/api-root.md +104 -1
  31. package/skill/references/recipes.md +1 -0
  32. package/skill/skill.json +5 -5
  33. package/types/core/client.d.ts +7 -1
  34. package/types/core/sdk.d.ts +3 -0
  35. package/types/core/singleton.d.ts +3 -0
  36. package/types/index.d.ts +3 -1
  37. package/types/modules/environment/index.d.ts +70 -0
  38. package/types/protocol.d.ts +1 -1
  39. package/dist/devtools/browser-dev-host/assets/browser-dev-host-TzYf9L6C.js +0 -99
@@ -0,0 +1,99 @@
1
+ import{ah as Oa,aB as ka,E as Na,an as Ma,ao as Ua,a8 as ei,aI as Q,b as Ai,ae as us}from"./workbench-state-BwV7bm4n.js";const tr="auth.login",rr="user.getInfo",nr="user.revokeAuthorization",ir="user.getSteamGameList",or="share.copyLink",sr="share.showShareMenu",ar="share.screenshot",cr="viewport.getWindowInfo",dr="viewport.setNavigationBarStyle",At="storage.getStorage",St="storage.setStorage",ur="network.request",lr="network.download",hr="files.pickFiles",fr="files.pickDirectory",mr="files.saveFile",vt="file.create",Rt="file.remove",gr="file.exists",pr="file.readText",yr="file.writeText",wr="file.readBytes",Er="file.writeBytes",br="file.stat",_r="directory.create",Dt="directory.remove",Ir="directory.exists",Ar="directory.list",Sr="ui.showToast",vr="ui.showLoading",Rr="ui.hideLoading",Dr="device.vibrate",Tr="device.setClipboard",Pr="navigation.close",Lr="navigation.reload",Cr="navigation.openAppPage",_e="cloud.leaderboard.submit",ce="cloud.leaderboard.getList",Pe="cloud.leaderboard.getCurrentUserEntry",Ve="cloud.leaderboard.deleteCurrentUserEntry",fe="cloud.leaderboard.getInfo",Le=[{method:tr,module:"auth",capability:tr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:rr,module:"user",capability:rr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:nr,module:"user",capability:nr,requirement:{kind:"none"},risk:"high"},{method:ir,module:"user",capability:ir,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:or,module:"share",capability:or,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:sr,module:"share",capability:sr,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:ar,module:"share",capability:ar,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:cr,module:"viewport",capability:cr,requirement:{kind:"none"},risk:"low"},{method:dr,module:"viewport",capability:dr,requirement:{kind:"none"},risk:"low"},{method:At,module:"storage",capability:At,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:St,module:"storage",capability:St,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:ur,module:"network",capability:ur,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:lr,module:"network",capability:lr,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:hr,module:"files",capability:hr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:fr,module:"files",capability:fr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:mr,module:"files",capability:mr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:vt,module:"file",capability:vt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Rt,module:"file",capability:Rt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:gr,module:"file",capability:gr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:pr,module:"file",capability:pr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:yr,module:"file",capability:yr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:wr,module:"file",capability:wr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Er,module:"file",capability:Er,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:br,module:"file",capability:br,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_r,module:"directory",capability:_r,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dt,module:"directory",capability:Dt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ir,module:"directory",capability:Ir,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ar,module:"directory",capability:Ar,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Sr,module:"ui",capability:Sr,requirement:{kind:"none"},risk:"low"},{method:vr,module:"ui",capability:vr,requirement:{kind:"none"},risk:"low"},{method:Rr,module:"ui",capability:Rr,requirement:{kind:"none"},risk:"low"},{method:Dr,module:"device",capability:Dr,requirement:{kind:"none"},risk:"low"},{method:Tr,module:"device",capability:Tr,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Pr,module:"navigation",capability:Pr,requirement:{kind:"none"},risk:"medium"},{method:Lr,module:"navigation",capability:Lr,requirement:{kind:"none"},risk:"medium"},{method:Cr,module:"navigation",capability:Cr,requirement:{kind:"none"},risk:"medium"},{method:_e,module:"cloud",capability:_e,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:ce,module:"cloud",capability:ce,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Pe,module:"cloud",capability:Pe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ve,module:"cloud",capability:Ve,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:fe,module:"cloud",capability:fe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"}],ke="heybox:miniprogram",ls=2,Ha="hb_mini_bridge_nonce",hs="sdk.handshake",Vt="runtime.location.probe",xa="sdk.location.report",Ba="sdk.csp.violation",fs="operation.progress";function Fa(e){return!$e(e)||e.namespace!==ke||e.version!==1&&e.version!==2||!Y(e.nonce)?!1:e.type==="handshake"?Y(e.id)&&e.method===hs&&e.error===void 0&&qa(e.payload):e.type==="request"?Y(e.id)&&Y(e.method)&&e.error===void 0:e.type==="response"?Y(e.id)&&(e.method===void 0||Y(e.method))&&(e.error===void 0||$a(e.error)):e.type==="event"?!Y(e.method)||e.error!==void 0?!1:e.method===fs?e.version===2&&Y(e.id)&&Va(e.payload):e.id===void 0||Y(e.id):e.type==="cancel"?e.version===2&&Y(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function ti(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function ms(e){return $e(e)?e.kind==="sandbox"?qe(e,["kind"]):e.kind==="directory"&&Y(e.handleId)&&qe(e,["kind","handleId"]):!1}function gs(e){return!$e(e)||e.kind!=="file"?!1:Y(e.handleId)?qe(e,["kind","handleId"]):ms(e.root)&&ti(e.relativePath)&&qe(e,["kind","root","relativePath"])}function ps(e){return!$e(e)||e.kind!=="directory"?!1:Y(e.handleId)?qe(e,["kind","handleId"]):ms(e.root)&&ti(e.relativePath)&&qe(e,["kind","root","relativePath"])}function Va(e){return!$e(e)||!Si(e.loaded)||typeof e.lengthComputable!="boolean"||!qe(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Si(e.total)&&e.loaded<=e.total:e.total===void 0}function qa(e){return $e(e)&&Y(e.href)&&typeof e.userAgent=="string"&&Y(e.sdkVersion)}function $a(e){return $e(e)&&Y(e.code)&&typeof e.message=="string"}function Si(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Y(e){return typeof e=="string"&&e.length>0}function qe(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function $e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const xr=["identity","profile"],ri=["userInfo","steamLibrary","share","storage","filesystem","clipboard","leaderboard","network"];new Set(ri);const ja=new Set(ri);function za(e){return ja.has(e)}function Br(e){if(!ct(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(!ct(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),!za(o)){if(!ct(n.config))return{valid:!1,permissions:{}};continue}if(o==="network"){const s=n.config;if(!ct(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&&(!ct(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 ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Le.map(e=>e.method);function U(e,t,r){return{code:e,message:t,data:r}}function ys(e){return Ga(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?U("RUNTIME_ERROR",e.message):U("UNKNOWN_ERROR","小程序运行时异常",e)}function Ga(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function Wa(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Ka=1e3;function Ya(e,t=Wa()){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<=Ka}const Qa="runtime.gate.probe",ws=new Set(Le.map(e=>e.method));class Xa{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=ls;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:ke,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:ke,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:ke,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:ke,version:2,nonce:this.nonce,type:"event",id:t,method:fs,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=Ya(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&&Fa(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:ke,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:hs,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===Qa){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,U("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!ws.has(t.method)){this.postResponse(t,void 0,U("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,U("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=ys(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:ke,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!Ja(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 Ja(e){return typeof e=="string"&&ws.has(e)}const Es="METHOD_FORBIDDEN";function pe(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Es,t}class q 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 vi={[tr]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[rr]:["account.getCurrentUserId","account.onChange","network.request"],[nr]:["account.getCurrentUserId","account.onChange","network.request"],[ir]:["account.getCurrentUserId","account.onChange","network.request"],[or]:["presentation.setClipboard"],[sr]:["presentation.showShareMenu"],[ar]:["presentation.getViewportMetrics","presentation.captureAndShare"],[cr]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[dr]:["presentation.setNavigationBarStyle"],[At]:["storage.getRaw"],[St]:["storage.setRaw"],[ur]:["network.request"],[lr]:["network.stream","files.transfer","files.access"],[hr]:["files.external"],[fr]:["files.external"],[mr]:["files.save"],[vt]:["files.access"],[Rt]:["files.removeFile"],[gr]:["files.access"],[pr]:["files.access"],[yr]:["files.access"],[wr]:["files.access"],[Er]:["files.access"],[br]:["files.access"],[_r]:["files.access"],[Dt]:["files.removeDirectory"],[Ir]:["files.access"],[Ar]:["files.access"],[Sr]:["presentation.showToast"],[vr]:["presentation.showLoading"],[Rr]:["presentation.hideLoading"],[Dr]:["presentation.vibrate"],[Tr]:["presentation.setClipboard"],[Pr]:["presentation.close"],[Lr]:["presentation.reload"],[Cr]:["presentation.openAppPage"],[_e]:["account.getCurrentUserId","account.onChange","network.request"],[ce]:["account.onChange","network.request"],[Pe]:["account.getCurrentUserId","account.onChange","network.request"],[Ve]:["account.getCurrentUserId","account.onChange","network.request"],[fe]:["account.onChange","network.request"]};function Za(e,t){if(t[e]!==!0)throw pe(e)}const ec=32*1024*1024,tc=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function rc(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:ec},i);return nc(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function nc(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:ic(t,sc(e,"content-type"))}}function ic(e,t){oc(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new q("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!tc.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function oc(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new q(`Host network response 不支持 charset=${t}`)}function sc(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function L(e){return typeof e=="function"}function Ri(e){return(...t)=>{throw pe(e)}}function K(e){return async(...t)=>{throw pe(e)}}const ac=(e,t)=>{},cc=()=>()=>{};function dc(e){const t={request:L(e.network?.request)?e.network.request.bind(e.network):K("network.request")},r={getCurrentUserId:L(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):K("account.getCurrentUserId"),ensureAuthenticated:L(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):K("account.ensureAuthenticated"),onChange:L(e.account?.onChange)?e.account.onChange.bind(e.account):cc},n={getRaw:L(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):K("storage.getRaw"),setRaw:L(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):K("storage.setRaw")},i={close:L(e.presentation?.close)?e.presentation.close.bind(e.presentation):K("presentation.close"),reload:L(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):K("presentation.reload"),openAppPage:L(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):K("presentation.openAppPage"),getViewportMetrics:L(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Ri("presentation.getViewportMetrics"),getNavigationBarHeight:L(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Ri("presentation.getNavigationBarHeight"),setNavigationBarStyle:L(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):K("presentation.setNavigationBarStyle"),showShareMenu:L(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):K("presentation.showShareMenu"),setScreenshotChromeHidden:L(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):ac,captureAndShare:L(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):K("presentation.captureAndShare"),showToast:L(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):K("presentation.showToast"),showLoading:L(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):K("presentation.showLoading"),hideLoading:L(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):K("presentation.hideLoading"),vibrate:L(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):K("presentation.vibrate"),setClipboard:L(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):K("presentation.setClipboard")},o=L(e.storageDiagnostics?.listRaw)?{listRaw:e.storageDiagnostics.listRaw.bind(e.storageDiagnostics)}:void 0;return{network:t,account:r,storage:n,presentation:i,...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 uc(e){const t=lc(e.files?.sandbox),r=L(e.picker?.pickFiles)&&L(e.picker?.pickDirectory),n=L(e.picker?.saveFile),i=t||r||n,o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getCurrentUserId":L(e.account?.getCurrentUserId),"account.ensureAuthenticated":L(e.account?.ensureAuthenticated),"account.onChange":L(e.account?.onChange),"network.request":L(e.network?.request),"network.stream":L(e.transfer?.network.open)&&L(e.transfer?.network.release),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":L(o?.remove),"files.removeDirectory":L(e.files?.sandbox.remove),"files.transfer":L(e.transfer?.files.writeResource),"storage.getRaw":L(e.storage?.getRaw),"storage.setRaw":L(e.storage?.setRaw),"presentation.close":L(e.presentation?.close),"presentation.reload":L(e.presentation?.reload),"presentation.openAppPage":L(e.presentation?.openAppPage),"presentation.getViewportMetrics":L(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":L(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":L(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":L(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":L(e.presentation?.captureAndShare),"presentation.showToast":L(e.presentation?.showToast),"presentation.showLoading":L(e.presentation?.showLoading),"presentation.hideLoading":L(e.presentation?.hideLoading),"presentation.vibrate":L(e.presentation?.vibrate),"presentation.setClipboard":L(e.presentation?.setClipboard)}}function lc(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&L(t.file)&&L(t.directory)&&L(t.create)&&L(t.stat)&&L(t.list)}function Di(e,t){return t?.[e]!==!1}function hc(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")}function bs(e,t={}){const r={};for(const n of Object.keys(vi)){const o=vi[n].every(a=>e[a]),s=!hc(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=Di(n,t.callerCapabilities)&&Di(n,t.hostCapabilities)&&o&&s}return r}function _s(e={},t={}){const r=uc(e),n=bs(r,t);return{ports:dc(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function ni(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):fc(e.signal,t);return{...e,signal:r}}function fc(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 mc(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"}function l(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function M(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gc(e){return typeof e=="object"&&e!==null}function ne(e,t){const r=e.data;if(!gc(r)||typeof r.status!="string")throw new Error(t);return r}const Is={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},pc={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 ne(e,"工坊小程序详情加载失败")}};function Mt(e){return{mini_program_id:e.miniProgramId}}function yc(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function wc(e){const t=ne(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=yc(r.consent_challenge)),{...t,result:n}}const Ec={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=>({...Mt(e.runtimeContext),challenge:e.challenge}),parse:e=>ne(e,"小程序授权取消接口响应异常")},bc={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=>Mt(e.runtimeContext),parse:e=>ne(e,"小程序授权撤销接口响应异常")},_c={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=>Mt(e.runtimeContext),parse(e){const t=ne(e,"小程序隔离身份接口响应异常");return{...t,result:{appUserId:t.result.app_user_id}}}},Ic={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=>({...Mt(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>wc(e)},Ac={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=>({...Mt(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=ne(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},Sc=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],vc=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Rc=/authorization|cookie|pkey|password|secret|token/i,As=/authorization|cookie|pkey|token|password|secret/i;function ue(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Dc(e){for(const t of Object.keys(e))if(!vc.has(t))throw new q(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of Sc)if(Object.prototype.hasOwnProperty.call(e,t)&&ue(e,t)!==void 0)throw new q(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(ue(e,"bodyEncoding")!==void 0&&ue(e,"bodyEncoding")!=="json"&&ue(e,"bodyEncoding")!=="form")throw new q("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(ue(e,"failurePresentation")!==void 0&&ue(e,"failurePresentation")!=="none")throw new q("endpoint failurePresentation 必须为 none");if(ue(e,"auth")!==void 0&&ue(e,"auth")!=="none"&&ue(e,"auth")!=="optional"&&ue(e,"auth")!=="required")throw new q("endpoint auth 必须为 none、optional 或 required")}function pt(e){if(Array.isArray(e))return e.map(pt);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Rc.test(n)||(r[n]=pt(i));return r}function Ti(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))As.test(r)||(t[r]=n);return t}function Tc(e){if(!e)return;const t=Object.keys(e).find(r=>As.test(r));if(t)throw new q(`endpoint 禁止声明 credential-bearing header: ${t}`)}class rt extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,Object.setPrototypeOf(this,new.target.prototype)}}function Ss(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class nt extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Ss(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Ut extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Ss(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function Pc(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:pt(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Ti(o),method:e.method,metadata:{endpointId:e.id},query:pt(n),timeout:e.timeout,url:r},data:pt(a.data),headers:Ti(a.headers)||{},status:a.status,statusText:a.statusText}}async function Fr(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(Dc(t),typeof t.id!="string"||!t.id)throw new q("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new q("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new q("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;Tc(a);let c;try{c=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...o===void 0?{}:{params:o},...s===void 0?{}:{data:s},...a===void 0?{}:{headers:a},credentials: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(d){throw d instanceof q?d:new nt({endpointId:t.id,cause:d})}if(c.status<200||c.status>=300)throw new rt({endpointId:t.id,status:c.status});const u=Pc(t,r,i,o,s,a,n,c);if(t.parse)try{return await t.parse(u,r)}catch(d){throw new Ut({endpointId:t.id,cause:d})}return u.data}const Lc=new Set(xr),Cc=1e3;function Oc(e){const t=new Set,r=new Map,n=new Map,i=new Set;let o=0,s=!1,a=Promise.resolve(),c;const u=e.account.onChange(m=>{d(),h("heybox_app_login_change",{isHeyboxAppLoggedIn:!!m})});function d(){o+=1,c?.abort(),r.clear(),n.clear(),i.clear()}function h(m,g){for(const E of t)try{E(m,g)}catch{}}function p(){const m=e.identity.get()?.miniProgramId?.trim();if(!m)throw l("INVALID_STATE","当前能力缺少 canonical 小程序身份");return m}function f(){if(s||e.operationContext.signal.aborted)throw l("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function _(){f();let m;try{m=await e.account.getCurrentUserId(e.operationContext)}catch(g){throw Oi(g,e.operationContext.signal,"读取小黑盒账号失败")}return typeof m=="string"&&m.trim()?m.trim():void 0}async function b(m,g){const E=await _();if(o!==g||E!==m)throw l("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function I(m){f();try{await e.account.ensureAuthenticated({trustedUserGesture:m,reason:"runtime_auth",signal:e.operationContext.signal})}catch(E){throw Oi(E,e.operationContext.signal,"小黑盒登录失败")}const g=await _();if(!g)throw l("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return g}async function y(m,g,E=e.operationContext.signal){try{if(E.aborted)throw Nn();return await xc(Fr(e.network,m,g,{...e.operationContext,credentials:"heybox-session",signal:E}),E)}catch(T){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):T instanceof q?l("REQUEST_UNSUPPORTED",T.message):T instanceof Ut?l("INVALID_RESPONSE","授权接口响应不合法"):T instanceof nt?l("REQUEST_FAILED","授权请求失败"):T instanceof rt?l("REQUEST_FAILED",T.message):vs(T)?T:l("REQUEST_FAILED","授权请求失败")}}async function A(m,g){await y(Ec,{runtimeContext:{miniProgramId:m},challenge:g}).catch(()=>{})}function v(m){const g=async()=>{const T=Li(e.operationContext.signal);c=T;try{return await m(T.signal)}finally{c===T&&(c=void 0),T.abort()}},E=a.then(g,g);return a=E.then(()=>{},()=>{}),E}async function P(m,g,E,T,k){if(!E)throw await A(m,g.challenge),l("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await A(m,g.challenge),l("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return v(async F=>{await b(T,k);const V=await H(m,g.displayedScopes,F);await b(T,k);let Z;try{Z=await e.authPresentation.confirmAuthorization({miniProgramId:m,scopes:g.displayedScopes,...V,signal:F})}catch(J){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await b(T,k),await A(m,g.challenge),kc("REQUEST_FAILED","授权确认界面执行失败",J))}if(await b(T,k),Z.status!=="granted")throw await A(m,g.challenge),l("AUTHORIZATION_CANCELLED","用户取消授权");const se=Uc(Z.grantedScopes,g.displayedScopes);if(!se.includes("identity"))throw await A(m,g.challenge),l("AUTHORIZATION_CANCELLED","用户拒绝授权");return se})}async function H(m,g,E){const T=Li(E),k=setTimeout(()=>T.abort(),Cc);try{const F=Hc(e.miniProgramPresentation),[V,Z]=await Promise.all([F?Promise.resolve(F):R(m,T.signal),g.includes("profile")?O(T.signal):Promise.resolve(void 0)]);return{...V?{miniProgram:V}:{},...Z?{userProfile:Z}:{}}}finally{clearTimeout(k),T.abort()}}async function R(m,g){try{const E=e.identity.get()?.version?.trim(),T=await y(pc,{mini_program_id:m,...E?{miniprogram_version:E}:{}},g),k=We(T,"小程序公开资料"),F=Je(k.name),V=Je(k.icon_url);return F||V?{...F?{name:F}:{},...V?{avatarUrl:V}:{}}:void 0}catch{return}}async function O(m){try{const g=await y(Is,void 0,m),E=We(g,"账号基础信息"),T=Je(E.display_username),k=Je(E.display_avatar);return T||k?{...T?{nickname:T}:{},...k?{avatar:k}:{}}:void 0}catch{return}}async function C(m,g){const E=p(),T=await I(g),k=o,F=await y(Ic,{runtimeContext:{miniProgramId:E},scopes:m});await b(T,k);const V=We(F,"小程序登录"),Z=Ci(V,"loginCode"),se=Ci(V,"consentChallenge");if(Z===se)throw l("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let J;if(Z)J=Pi(V.loginCode);else{const z=Nc(V.consentChallenge),ye=await P(E,z,g,T,k);await b(T,k);const Wr=await y(Ac,{runtimeContext:{miniProgramId:E},challenge:z.challenge,selectedScopes:ye});if(await b(T,k),J=Pi(We(Wr,"小程序登录确认")),J.scopes.some(at=>!ye.includes(at)))throw l("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}i.clear();for(const z of J.scopes)i.add(z);return h("heybox_app_login_change",{isHeyboxAppLoggedIn:!0}),h("user_info_authorization_change",Yr(i)),J}async function S(m,g){const E=o,T=await y(_c,{runtimeContext:{miniProgramId:g}});await b(m,E);const k=Mc(We(T,"用户本地身份"));for(const F of xr)i.add(F);return h("user_info_authorization_change",Yr(i)),k}function w(m){f();const g=p(),E=`${m}\0${g}`,T=r.get(E);if(T)return Promise.resolve(T);const k=n.get(E);if(k)return k;const F=S(m,g).then(V=>(r.set(E,V),V)).finally(()=>{n.get(E)===F&&n.delete(E)});return n.set(E,F),F}async function D(m){if(!m)throw l("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const g=p(),E=o,T=await _();if(!T)throw l("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const k=await y(bc,{runtimeContext:{miniProgramId:g}});await b(T,E),We(k,"用户授权撤销"),d(),h("user_info_authorization_change",{identity:"denied",profile:"denied"})}return{login:C,getOrCreateLocalIdentity:w,getAuthorization:()=>Yr(i),revoke:D,onEvent(m){return t.add(m),()=>t.delete(m)},dispose(){s||(s=!0,d(),u(),t.clear())}}}function kc(e,t,r){const n=l(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function We(e,t){if(!M(e))throw l("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 l(n,r)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Pi(e){if(!M(e))throw l("INVALID_RESPONSE","login code 必须是对象");const t=Or(e.scopes,"login code scopes");if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!t.includes("identity"))throw l("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:t}}function Nc(e){if(!M(e))throw l("INVALID_RESPONSE","授权 challenge 必须是对象");const t=Or(e.requestedScopes,"challenge requestedScopes"),r=Or(e.displayedScopes,"challenge displayedScopes");if(typeof e.challenge!="string"||!e.challenge.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!Number.isInteger(e.consentUiVersion)||Number(e.consentUiVersion)<0||!t.length||!t.includes("identity")||!r.length||!r.includes("identity")||t.some(n=>!r.includes(n)))throw l("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:t,displayedScopes:r}}function Mc(e){if(!M(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw l("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");return{appUserId:e.appUserId.trim()}}function Uc(e,t){const r=Or(e,"授权选择 scopes");if(r.some(n=>!t.includes(n)))throw l("INVALID_RESPONSE","授权选择包含未展示的 scope");return r}function Je(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Hc(e){const t=Je(e?.name),r=Je(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Li(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 xc(e,t){return t.aborted?Promise.reject(Nn()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Nn()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Nn(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Or(e,t){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!Lc.has(r))||new Set(e).size!==e.length)throw l("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Yr(e){return Object.fromEntries(xr.map(t=>[t,e.has(t)?"granted":"not_requested"]))}function Ci(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function vs(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Oi(e,t,r){return t.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):vs(e)?e:l("REQUEST_FAILED",r)}const Bc=new Set(xr);function Fc(e){return{[tr]:async(t,r)=>e.authorization.login(Vc(t),r.trustedUserGesture)}}function Vc(e){if(e===void 0)return["identity"];if(!M(e)||Object.keys(e).some(t=>t!=="scopes"))throw ki();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Bc.has(t))||new Set(e.scopes).size!==e.scopes.length)throw ki();return[...e.scopes]}function ki(){return l("INVALID_PARAMS","auth.login 参数不合法")}const qc={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 ne(e,"排行榜记录删除接口响应异常")}},$c={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 ne(e,"当前排行榜记录接口响应异常")}},jc={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 ne(e,"排行榜信息接口响应异常")}},zc={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 ne(e,"排行榜列表接口响应异常")}},Gc={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 ne(e,"排行榜提交接口响应异常")}};function Kt(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Ni(e){return e instanceof q?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function W(e){if(e.aborted)throw Kt()}function $(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Kt());let n;try{n=e()}catch(i){return Promise.reject(Ni(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Kt())):new Promise((i,o)=>{let s=!1;const a=u=>{s||(s=!0,t.removeEventListener("abort",c),u())},c=()=>a(()=>o(Kt()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(u=>a(()=>i(u)),u=>a(()=>o(Ni(u))))})}const Wc="default",Kc=/^[A-Za-z0-9_-]{1,64}$/,Yc=300*1e3,Qc=250,Xc=3,Jc={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 Zc{constructor(t){this.options=t,this.unsubscribeAccountChange=td(t.account,()=>this.invalidateForAccountChange()),t.operationContext.signal.aborted?this.dispose():t.operationContext.signal.addEventListener("abort",this.handleTerminalAbort,{once:!0})}accountGeneration=0;buckets=new Map;inflight=new Map;unsubscribeAccountChange;disposed=!1;handleTerminalAbort=()=>this.dispose();async submit(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Gc,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=dt(i,_e);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),Qr(o,_e)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=ut("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(zc,{miniProgramId:r,...t}),s=dt(o,ce);if(!me(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw j(`${ce} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw j(`${ce} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>Qr(a,ce)),...typeof s.cursor=="string"&&s.cursor?{cursor:s.cursor}:{},hasMore:s.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId(),i=await this.requireCurrentUser(r),o=this.createBucketKey(n,t.key),s=ut("current",i);return this.read(o,"current",s,async()=>{const a=await this.request($c,{miniProgramId:n,...t}),c=dt(a,Pe);if(!me(c))throw j(`${Pe} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Qr(c.entry,Pe)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(qc,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=dt(i,Ve);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!me(o)||typeof o.deleted!="boolean")throw j(`${Ve} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",ut("info"),async()=>{const i=await this.request(jc,{miniProgramId:r,...t}),o=dt(i,fe);if(!me(o)||typeof o.key!="string"||!Kc.test(o.key))throw j(`${fe} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw j(`${fe} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw j(`${fe} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw j(`${fe} 返回的 rankLimit 必须是非负整数`);return{key:o.key,order:o.order,rankLimit:o.rank_limit}})}read(t,r,n,i){this.assertUsable();const o=this.getOrCreateBucket(t),s=o?.caches[r],a=s?.get(n);if(a&&a.expiresAt>Date.now())return Promise.resolve(a.value);s?.delete(n);const c=ut(t,n),u=this.inflight.get(c);if(u)return u.promise;const d=this.accountGeneration,h=o?.generation,p=i().then(f=>(this.assertAccountGeneration(d),o&&s&&o.generation===h&&(r==="list"?s.size>=Qc&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+Yc,value:f})),f)).finally(()=>{this.inflight.get(c)?.promise===p&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:p}),p}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=Xc)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)Ui(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){Ui(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 $(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw xi(n)?n:Hi()}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ae("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ae("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return ut(t,r??Wc)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ae("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){this.assertUsable();const n={request:async(i,o)=>(this.assertUsable(),this.options.network.request(i,o))};try{return await $(()=>Fr(n,t,r,{...this.options.operationContext,credentials:"heybox-session"}),this.options.operationContext.signal)}catch(i){throw xi(i)||Mn(i,"REQUEST_UNSUPPORTED")?i:i instanceof q?ae("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求"):i instanceof nt&&Mn(i.cause,"INVALID_STATE")?i.cause:i instanceof rt&&(i.status===401||i.status===403)?ae("UNAUTHORIZED","当前用户未登录"):i instanceof nt||i instanceof rt?Hi():i instanceof Ut?j(i.cause instanceof Error?i.cause.message:"排行榜响应不合法"):j(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(W(this.options.operationContext.signal),this.disposed)throw ae("INVALID_STATE","Cloud capability 已释放")}}function ed(e){return new Zc(e)}function td(e,t){try{return e.onChange(t)}catch(r){if(Mn(r,Es))return()=>{};throw r}}function dt(e,t){if(!me(e)||typeof e.status!="string")throw j(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw rd(e);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw j(`${t} 响应缺少 result`);return e.result}function Qr(e,t){if(!me(e))throw j(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw j(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw j(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw j(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw j(`${t} 返回的 score 必须是有限数字`);if(!me(e.extra))throw j(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw j(`${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 rd(e){if(e.status==="login"||e.status==="relogin")throw ae("UNAUTHORIZED",mt(e.msg)||"当前用户未登录");const t=Mi(e.result)??Mi(e),r=mt(t?.user_message)||mt(e.msg)||mt(t?.developer_message)||"排行榜请求失败";throw t?ae(nd(t),r,{status:e.status,sbe:t}):ae("HEYBOX_API_ERROR",r,{status:e.status})}function Mi(e){return me(e)&&me(e.sbe)?e.sbe:void 0}function nd(e){const t=mt(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 Jc[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 Ui(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function ut(...e){return JSON.stringify(e)}function me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Mn(e,t){return me(e)&&e.code===t}function ae(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function j(e){return ae("INVALID_RESPONSE",e)}function Hi(){return ae("REQUEST_FAILED","排行榜请求失败")}function xi(e){return e instanceof Error&&e.name==="AbortError"}const id=/^[A-Za-z0-9_-]{1,64}$/,Bi=20,od=100,Fi=2048;function sd(e){const t=ed(e);return{handlers:{[_e]:async n=>t.submit(ad(n)),[ce]:async n=>t.getList(cd(n)),[Pe]:async n=>t.getCurrentUserEntry(Xr(n,Pe)),[Ve]:async n=>t.deleteCurrentUserEntry(Xr(n,Ve)),[fe]:async n=>t.getInfo(Xr(n,fe))},dispose:()=>t.dispose()}}function ad(e){const t=ii(e,_e,!1);if(oi(t,["key","score","extra"],_e),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw ge("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...si(t.key,_e),score:t.score,...t.extra===void 0?{}:{extra:dd(t.extra)}}}function cd(e){if(e===void 0)return{limit:Bi};const t=ii(e,ce,!0);oi(t,["key","limit","cursor"],ce);const r=t.limit===void 0?Bi:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>od)throw ge("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw ge("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...si(t.key,ce),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Xr(e,t){if(e===void 0)return{};const r=ii(e,t,!0);return oi(r,["key"],t),si(r.key,t)}function ii(e,t,r){if(e===void 0&&r)return{};if(!Rs(e))throw ge("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function oi(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw ge("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function si(e,t){if(e===void 0)return{};if(typeof e!="string"||!id.test(e))throw ge("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function dd(e){if(!Rs(e))throw ge("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw ge("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw ge("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>Fi)throw ge("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${Fi} 字节`);return e}function Rs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ge(e,t){return{code:e,message:t}}const Vi=5e3,qi=1e4;function Ue(e){throw{code:"INVALID_PARAMS",message:e}}function Ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ts(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Ue(`${r} 不支持字段: ${n.join(", ")}`)}function ud(e){if(e===void 0)return{intensity:"light",delay:0};if(!Ds(e))return Ue("device.vibrate 参数必须是对象");Ts(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>Vi?Ue(`device.vibrate delay 必须是 0-${Vi} 的整数毫秒`):{intensity:r,delay:n}}function ld(e){return Ds(e)?(Ts(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?Ue("device.setClipboard text 必须是非空字符串"):e.text.length>qi?Ue(`device.setClipboard text 不能超过 ${qi} 字符`):{text:e.text}):Ue("device.setClipboard 参数必须是对象")}function hd(e){return{[Dr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.vibrate(ud(t),e.operationContext),e.operationContext.signal)},[Tr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.setClipboard(ld(t),e.operationContext),e.operationContext.signal)}}}const fd=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"]),md={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 ai(e){const t=Ps(e),r=t&&fd.has(t)?l(t,md[t]??"文件操作失败"):l("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function be(e){try{return e()}catch(t){throw ai(t)}}function Ps(e){try{if(!M(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}function Ls(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):Un,remove:o?s=>e.remove(s):Os,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Un,stat:s=>e.stat(s)})}function Cs(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=>Ls(e.file(a),n,{allowRemove:o}),directory:a=>Cs(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Un,remove:s?(a,c)=>e.remove(a,c):Os,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Un(){return Promise.reject(l("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Os(){return Promise.reject(l("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const $i=1024;class gd{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 qt(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=be(()=>{if(!Array.isArray(t))throw l("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw l("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>$i)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let u=0;u<a;u+=1){if(!Object.prototype.hasOwnProperty.call(t,u))throw l("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[u],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>qt(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 zi(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}resolveFileEntry(t){this.assertCanonicalDetail();const r=yd(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Tt(r.relativePath),o=this.prepareFile(be(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=wd(t);if("handleId"in r){const s=this.readDirect(r.handleId,"directory");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Tt(r.relativePath),o=this.prepareDirectory(be(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Wi(t),qt(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),be(()=>{if(!Array.isArray(r))throw l("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw l("FILE_IO_FAILED","Host 返回了稀疏目录列表");o.push(this.describeListedEntry(t,r[s]))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return be(()=>{if(M(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return qt(n.handle,ji(t.ref,n.handle.name))}if(M(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return zi(n.handle,pd(t.ref,n.handle.name))}throw l("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Ht(r),i=this.prepareFile(be(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:ji(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw l("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return be(()=>{Wi(t);const i=n??t.mode;return Gi(t.mode,i),{handle:Ls(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return be(()=>{_d(t,i);const o=n??t.mode;return Gi(t.mode,o),{handle:Cs(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>$i)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Ed();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw l("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!bd(t))throw l("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw l("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw pe("files.sandbox");return this.prepareDirectory(be(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw pe("files")}}function Tt(e){if(!ti(e))throw l("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Ht(e,t="文件名"){const r=Tt(e);if(r.includes("/"))throw l("INVALID_PARAMS",`${t} 只能是 basename`);return r}function ji(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Tt(`${e.relativePath}/${t}`)}}function pd(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Tt(`${e.relativePath}/${t}`)}}function qt(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function zi(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Gi(e,t){if(t==="readwrite"&&e!=="readwrite")throw l("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function yd(e){return gs(e)||ks(),e}function wd(e){return ps(e)||ks(),e}function ks(){throw l("INVALID_PARAMS","文件引用不合法")}function Ed(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw l("FILE_IO_FAILED","当前环境缺少安全随机数能力");const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function bd(e){return/^[0-9a-f]{32}$/.test(e)}function Wi(e){if(!M(e)||e.kind!=="file"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.create!="function"||typeof e.read!="function"||typeof e.write!="function"||typeof e.stat!="function")throw l("FILE_IO_FAILED","Host 返回了无效 File handle");Ht(e.name,"Host File name")}function _d(e,t=!1){if(!M(e)||e.kind!=="directory"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.file!="function"||typeof e.directory!="function"||typeof e.create!="function"||typeof e.stat!="function"||typeof e.list!="function")throw l("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw l("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&Ht(e.name,"Host Directory name")}const Ki=1e3,Id=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function Ad(e){const t=r=>ni(e.operationContext,r.signal);return{files:{[hr]:async(r,n)=>{Jr(n);const i=Zr(e.picker),o=Sd(r),s=await ee(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[fr]:async(r,n)=>{Jr(n);const i=Zr(e.picker),o=vd(r),s=await ee(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[mr]:async(r,n)=>{Jr(n);const i=Zr(e.picker),o=Rd(r).suggestedName,s=t(n);if(!i.saveFile)throw pe("files.saveFile");const a=await ee(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[vt]:async(r,n)=>{const i=ie(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);Ke(o.mode),await ee(()=>o.create(Yi(i),t(n)))},[Rt]:async(r,n)=>{const i=ie(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),Ke(o.handle.mode),!o.handle.remove)throw pe(Rt);await ee(()=>o.handle.remove(t(n)))},[gr]:async(r,n)=>{const i=ie(r);return Qi(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!M(o)||o.kind!=="file")throw Ji()})},[pr]:async(r,n)=>{const i=ie(r),o=Xi(await ee(()=>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 l("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[yr]:async(r,n)=>{const i=ie(r,["content"]);typeof i.content!="string"&&oe("content 必须是字符串");const o=e.registry.resolveFile(i.target);Ke(o.mode),await ee(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[wr]:async(r,n)=>{const i=ie(r),o=await ee(()=>e.registry.resolveFile(i.target).read(t(n)));return Xi(o)},[Er]:async(r,n)=>{const i=ie(r,["content"]),o=e.registry.resolveFile(i.target);Ke(o.mode),await ee(()=>o.write(Td(i.content),t(n)))},[br]:async(r,n)=>{const i=ie(r),o=await ee(()=>e.registry.resolveFile(i.target).stat(t(n)));return Pd(o)}},directory:{[_r]:async(r,n)=>{const i=ie(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);Ke(o.mode),await ee(()=>o.create(Yi(i),t(n)))},[Dt]:async(r,n)=>{const i=ie(r,["recursive"]),o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),Ke(o.handle.mode),!o.handle.remove)throw pe(Dt);await ee(()=>o.handle.remove({recursive:i.recursive===void 0?!1:kr(i.recursive,"recursive")},t(n)))},[Ir]:async(r,n)=>{const i=ie(r);return Qi(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!M(o)||o.kind!=="directory")throw Ji()})},[Ar]:async(r,n)=>{const i=ie(r,["limit"]),o=Dd(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await ee(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function Sd(e){if(e===void 0)return{mode:"read",multiple:!1};M(e)||oe("pickFiles 参数必须是对象"),Vr(e,["mode","accept","multiple"]);const t=Ns(e.mode,"read"),r=e.multiple===void 0?!1:kr(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)))&&oe("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function vd(e){return e===void 0?{mode:"read"}:(M(e)||oe("pickDirectory 参数必须是对象"),Vr(e,["mode"]),{mode:Ns(e.mode,"read")})}function Rd(e){return M(e)||oe("saveFile 参数必须是对象"),Vr(e,["suggestedName"]),{suggestedName:Ht(e.suggestedName,"suggestedName")}}function ie(e,t=[]){return(!M(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&oe("文件操作参数必须包含 target"),Vr(e,["target",...t]),e}function Yi(e){return{recursive:e.recursive===void 0?!1:kr(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:kr(e.exclusive,"exclusive")}}function Ns(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&oe("mode 必须是 read 或 readwrite"),e)}function kr(e,t){return typeof e!="boolean"&&oe(`${t} 必须是布尔值`),e}function Dd(e){if(e===void 0)return Ki;if((!Number.isSafeInteger(e)||e<=0)&&oe("limit 必须是正整数"),e>Ki)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Vr(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&oe(`不支持字段: ${r.join(", ")}`)}function Ke(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Jr(e){if(!e.trustedUserGesture)throw l("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Zr(e){if(!e)throw pe("files.external");return e}async function Qi(e){try{return await e(),!0}catch(t){if(Id.has(Ps(t)??""))return!1;throw ai(t)}}async function ee(e){try{return await e()}catch(t){throw ai(t)}}function Td(e){return e instanceof Uint8Array||oe("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&oe("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Xi(e){if(!(e instanceof Uint8Array))throw l("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Ji(){return l("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Pd(e){if(!M(e)||e.kind!=="file"||!Ld(e.size))throw l("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Cd(e[t]))throw l("FILE_IO_FAILED",`Host 返回了无效 ${t}`);return{kind:"file",size:e.size,...e.modifiedAt===void 0?{}:{modifiedAt:e.modifiedAt},...e.createdAt===void 0?{}:{createdAt:e.createdAt}}}function Ld(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Cd(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function oe(e){throw l("INVALID_PARAMS",e)}const Od=["pc","console","mobile"],kd=["game","wiki"];function Nr(e){throw{code:"INVALID_PARAMS",message:e}}function Nd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function He(e,t){return typeof e!="string"||!e.trim()?Nr(t):e.trim()}function Zi(e,t,r){return typeof e!="string"||!t.includes(e)?Nr(r):e}function Md(e){const t={target:"game_detail",appId:He(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Zi(e.gameType,Od,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Zi(e.page,kd,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=He(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=He(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Ud(e){return{target:"user_detail",userId:He(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Hd(e){const t={target:"post_detail",linkId:He(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=He(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=He(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function xd(e){return Nd(e)?e.target==="game_detail"?Md(e):e.target==="user_detail"?Ud(e):e.target==="post_detail"?Hd(e):Nr("navigation.openAppPage target 不支持"):Nr("navigation.openAppPage options 必须是对象")}function Bd(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 Fd(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Vd(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 qd(e){const t=xd(e);return t.target==="game_detail"?Bd(t):t.target==="user_detail"?Fd(t):Vd(t)}function $d(e){throw{code:"INVALID_PARAMS",message:e}}function eo(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&$d(`${t} 不支持参数`)}function jd(e){return{[Pr]:async t=>{W(e.operationContext.signal),eo(t,"navigation.close"),await $(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Lr]:async t=>{W(e.operationContext.signal),eo(t,"navigation.reload"),await $(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[Cr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.openAppPage(qd(t),e.operationContext),e.operationContext.signal)}}}const zd=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Gd=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Wd=new Set(["range","if-range","a-im"]),Kd=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"]),Yd=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,$t={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Qd{constructor(t){this.signal=t}phase="initial";transition(t){if($t[t]<=$t[this.phase])throw l("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if($t[this.phase]<$t.committed&&this.signal.aborted)throw Hs()}normalizeHostError(t,r){return this.throwIfCancelled(),ci(t,r,this.signal)}}async function Xd(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw pe("network.download");const o=ni(r.operationContext,t.signal),s=new Qd(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await tu(e,i,o)}catch(d){throw s.normalizeHostError(d,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(d){throw s.normalizeHostError(d,"network")}let u=!1;try{s.throwIfCancelled(),s.transition("validate");const d=nu(c);iu(c,d);const h=ou(c.status,d);if(e.maxBytes!==void 0&&h.expectedBytes!==void 0&&h.expectedBytes>e.maxBytes)throw l("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const p=ru(e,a,d,i);let f=0;const _=Zd(h.expectedBytes,e.maxBytes);tn(t,en(0,h));const b={...o,onProgress(A){!Number.isSafeInteger(A)||A<f||_!==void 0&&A>_||(f=A,tn(t,en(f,h)))}};s.transition("transfer"),u=!0;let I;try{I=await n.files.writeResource(p.hostHandle,c.body,{mode:p.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...h.expectedBytes===void 0?{}:{expectedBytes:h.expectedBytes}},b)}catch(A){throw s.normalizeHostError(A,"transfer")}s.transition("committed"),f=Jd(I,h,f,e.maxBytes),tn(t,en(f,h));const y=i.describeFile(p.handle,p.ref);return s.transition("completed"),y}finally{u||eu(n.network,c.body)}}function Jd(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 Zd(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function eu(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function tu(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Hn(i.handle.mode),await hu(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Hn(n.handle.mode),await fu(n.handle,r),{kind:"directory",...n}}function ru(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=au(e,r),o=n.deriveFile(t,i);return Hn(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function nu(e){if(!e||typeof e!="object"||!Number.isInteger(e.status)||e.status<100||e.status>599||e.statusText!==void 0&&typeof e.statusText!="string"||!e.body||typeof e.body!="object")throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!M(e.headers))throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!zd.has(r)||!Array.isArray(n)||n.length===0)throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw l("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function iu(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw l("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:lu(t,Gd)});if((t["content-range"]?.length??0)>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function ou(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(u=>u!=="0"))throw l("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw l("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=su(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 su(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function en(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function tn(e,t){try{e.postProgress(t)}catch{}}function au(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=cu(i);if(o&&Yt(o))return o}for(const i of r){const o=du(i);if(o&&Yt(o))return o}if(e.suggestedName!==void 0)return Ms(e.suggestedName);const n=uu(e.url);return n&&Yt(n)?n:"download.bin"}function cu(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 du(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 uu(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Ms(e){try{Ht(e,"suggestedName")}catch{throw l("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Yt(e))throw l("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Yt(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Yd.test(e))}function lu(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function hu(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Us()}catch(r){throw ci(r,"file",t.signal)}}async function fu(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Us()}catch(r){throw ci(r,"file",t.signal)}}function Hn(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","下载目标只允许读取")}const mu={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 ci(e,t,r){if(r.aborted)return Hs();const n=gu(e);if(n&&Kd.has(n)){const o=l(n,mu[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?l("DOWNLOAD_TIMEOUT","下载网络请求超时"):l("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?l("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):l("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function gu(e){return M(e)&&typeof e.code=="string"?e.code:void 0}function Us(){return l("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Hs(){return l("DOWNLOAD_CANCELLED","下载已取消")}function pu(e){if(!e)return;const t=Object.keys(e).find(r=>Wd.has(r.trim().toLowerCase()));if(t)throw l("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const yu=4,wu=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Eu=["/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 bu(e,t){const r=_u(e);return r===null||to(r,wu)?!0:t&&to(r,Eu)}function _u(e){let t=e;for(let r=0;r<yu;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return ro(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return ro(t)}function to(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function ro(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}const Iu=new Set(["url","method","params","data","headers","timeout","withCredentials"]),Au=new Set(["url","to","params","headers","timeout","withCredentials","suggestedName","overwrite","maxBytes"]),Su=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),no=3e4,io=2*1024*1024,vu=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Ru=new Set(["authorization","connection","content-length","cookie","host","origin","proxy-authorization","referer","set-cookie","transfer-encoding","user-agent"]),Du=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Tu="network.request 不支持 multipart/form-data,请使用专用上传能力";function Pu(e){const t=Lu(e.runtimePermissions),r=ju(e.allowedHttpOrigins);return{[lr]:async(n,i)=>{const o=Ou(n,{permission:t,allowedHttpOrigins:r});return Xd(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[ur]:async(n,i)=>{const o=ni(e.operationContext,i?.signal);W(o.signal);const s=Cu(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await $(()=>e.network.request(s,o),o.signal)}catch(c){throw Ku(c)?c:Yu(c,"REQUEST_UNSUPPORTED")?N("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):N("REQUEST_FAILED","网络请求失败")}return Wu(a)}}}function Lu(e){const t=Br(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Cu(e,t){const r=qr(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!Iu.has(c));if(n.length>0)throw N("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);const i=xs(r,t,"network.request"),o=Nu(r.method),s=r.data;s!==void 0&&xu(s),Fu(i.headers,s);const a=Vu(i.headers,s,i.official);return{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",...o===void 0?{}:{method:o},...i.params===void 0?{}:{params:i.params},...s===void 0?{}:{data:s},...i.headers===void 0?{}:{headers:i.headers},...i.withCredentials===void 0?{}:{withCredentials:i.withCredentials},...a===void 0?{}:{bodyEncoding:a},...i.timeout===void 0?{}:{timeout:i.timeout}}}function Ou(e,t){const r=qr(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!Au.has(c));if(n.length>0)throw N("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);const i=xs(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw N("INVALID_PARAMS","network.download timeout 必须是有限正数");pu(i.headers);const o=gs(r.to),s=ps(r.to);if(!o&&!s)throw N("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw N("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw N("INVALID_PARAMS","suggestedName 必须是字符串");a=Ms(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw N("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw N("INVALID_PARAMS","maxBytes 必须是正的 safe integer");return{request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",method:"GET",...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout},...i.withCredentials===void 0?{}:{withCredentials:i.withCredentials}},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 xs(e,t,r){const n=ku(e.url,t.allowedHttpOrigins,r),i=Gu(n);if(i&&!t.permission.useOfficialDomain)throw N("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(bu(n.pathname,i))throw N("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,withCredentials:Hu(e.withCredentials,`${r} withCredentials 必须是布尔值`),params:e.params===void 0?void 0:{...qr(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Mu(e.headers,r),timeout:Uu(e.timeout,r)}}function ku(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw N("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw N("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw N("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw N("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw N("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Nu(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw N("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!Su.has(t))throw N("INVALID_PARAMS","network.request method 不合法");return t}function Mu(e,t="network.request"){const r=qr(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){if(!i.trim()||typeof o!="string")throw N("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);const s=i.trim().toLowerCase();if(Ru.has(s)||s.startsWith("x-heybox-")||s.startsWith("x-xhh-"))throw N("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[i]=o}return n}function Uu(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw N("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>no)throw N("INVALID_PARAMS",`${t} timeout 不能超过 ${no}ms`);return e}}function Hu(e,t){if(e!==void 0){if(typeof e!="boolean")throw N("INVALID_PARAMS",t);return e}}function xu(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw N("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Bu(e)>io)throw N("INVALID_PARAMS",`network.request data 不能超过 ${io} 字节`)}function Bu(e){if(typeof e=="string")return rn(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return rn(e.toString());try{const t=JSON.stringify(e);return t?rn(t):0}catch{throw N("INVALID_PARAMS","network.request data 必须可序列化")}}function Fu(e,t){const r=Bs(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 N("INVALID_PARAMS",Tu)}function Vu(e,t,r){if(t===void 0)return;const n=Bs(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)||$u(t))?"form":qu(t)?"json":void 0}function Bs(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function qu(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function $u(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ju(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&&zu(n.hostname)&&t.add(n.origin)}catch{}return t}function zu(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 Gu(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return vu.some(r=>t===r||t.endsWith(`.${r}`))}function Wu(e){return Object.keys(e.headers).some(oo)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!oo(t)))}:e}function oo(e){const t=e.trim().toLowerCase();return Du.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Ku(e){return e instanceof Error&&e.name==="AbortError"}function Yu(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function qr(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw N("INVALID_PARAMS",t);return e}function rn(e){return new TextEncoder().encode(e).length}function N(e,t){return{code:e,message:t}}const jt=4294967296;function Qu(e){const t=new Xu;return t.write(e),t.finish()}class Xu{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<jt?(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=Ju(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<jt)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/jt),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/jt)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Ju(e){const t=new Uint8Array(Zu(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 Zu(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 el(e){xn(e);const t=Qu(e);if(t.byteLength>128)throw new Error("share extra is too large");return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function xn(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)xn(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.values(e);if(i.length>64)throw new Error("extra object has too many fields");for(const o of i)xn(o,t+1,r);r.delete(e)}function tl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rl(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 nl(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=rl(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function il(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 Fs(e,t){if(e==null)return{};if(!tl(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=nl(e.topicIds),n=il(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 ol(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function sl(e){try{if(ol(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function X(e){throw{code:"INVALID_PARAMS",message:e}}function xt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bn(e,t){return typeof e!="string"||!e.trim()?X(t):e}function al(e,t){const r=Bn(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?X(t):r}catch{return X(t)}}function cl(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Vs(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return X(`${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 X(`${t} 缺少有效的小程序分享地址`)}}function dl(e,t){if(!xt(e))return X("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return X("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!cl(r))return X("share.showShareMenu channel 不合法");const n=qs(e.extra,"share.showShareMenu");return{title:Bn(e.title,"share.showShareMenu title 必须是非空字符串"),description:Bn(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Vs(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:al(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function qs(e,t){if(e!==void 0)try{return el(e)}catch{return X(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function $s(e,t){return e.invalidMessage&&await $(()=>sl(t.environment),t.operationContext.signal)?X(e.invalidMessage):e.post}function so(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function ul(e){const t=e.getViewportMetrics();return{left:0,top:0,width:so(t.windowWidth,0),height:so(t.windowHeight,0)}}function Fn(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?X(t):r}function ao(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?X(t):r}function ll(e){return xt(e)?{left:Fn(e.left,"share.screenshot rect.left 必须是非负数字"),top:Fn(e.top,"share.screenshot rect.top 必须是非负数字"),width:ao(e.width,"share.screenshot rect.width 必须是正数"),height:ao(e.height,"share.screenshot rect.height 必须是正数")}:X("share.screenshot rect 必须是对象")}function hl(e,t){if(e!=null&&!xt(e))return X("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?X("share.screenshot saveToAlbum 必须是布尔值"):{rect:r.rect===void 0?ul(t):ll(r.rect),...r.delay===void 0?{}:{delay:Fn(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function fl(e,t){W(t.operationContext.signal);const r=dl(e,t);let n=Fs(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await $s(n,t);return $(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function ml(e,t){if(W(t.operationContext.signal),e!==void 0&&!xt(e))return X("share.copyLink 参数必须是对象");const r=qs(e?.extra,"share.copyLink"),n=Vs(t,"share.copyLink",r);return await $(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function gl(e,t){W(t.operationContext.signal);const r=hl(e,t.presentation),n=Fs(xt(e)?e.post:void 0,{method:"share.screenshot"}),i=await $s(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=pl();let a=!1,c;try{a=!0,await $(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),c={status:"fulfilled",value:await $(()=>t.presentation.captureAndShare({...r,post:i,...o?{sourceMiniProgramId:o}:{}},t.operationContext),t.operationContext.signal)}}catch(d){c={status:"rejected",error:d}}const u=a?await yl(t.presentation,s,t.operationContext.signal):void 0;if(c.status==="rejected")throw c.error;if(u)throw u;return c.value}function pl(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function yl(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await $(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function wl(e){return{[or]:(t,r)=>ml(t,e),[sr]:(t,r)=>fl(t,e),[ar]:(t,r)=>gl(t,e)}}const El=128,bl=/^[A-Za-z0-9_-]+$/;function _l(e){const t=Il(e),r={[At]:async n=>{W(e.operationContext.signal);const i=co(n,At,e.storageLimits?.maxKeyLength),o=await $(()=>e.storage.getRaw(nn(t(),i),e.operationContext),e.operationContext.signal);return{data:uo(o)}},[St]:async n=>{W(e.operationContext.signal);const i=js(n,"storage.setStorage 参数必须是对象"),o=co(i,St,e.storageLimits?.maxKeyLength),s=Al(i.data,e.storageLimits?.maxValueBytes);await $(()=>e.storage.setRaw(nn(t(),o),s,e.operationContext),e.operationContext.signal)}};return e.storageDiagnostics?{handlers:r,diagnostics:{getSnapshot:async()=>{W(e.operationContext.signal);let n;try{n=t()}catch{throw Ce("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const i=nn(n,"");return(await $(()=>e.storageDiagnostics.listRaw(e.operationContext),e.operationContext.signal)).filter(s=>s.key.startsWith(i)).map(s=>{const a=s.value;return{area:s.area,key:s.key.slice(i.length),value:uo(a),serializedValue:a,bytes:zs(a)}}).sort((s,a)=>s.key.localeCompare(a.key))}}}:{handlers:r}}function Il(e){let t=!1,r;return()=>{if(!t){const n=e.identity.get()?.miniProgramId.trim();if(n)r=`id_${lo(n)}`;else{const i=e.anonymousStorageScope?.trim();i&&(r=`anon_${lo(i)}`)}t=r!==void 0}if(!r)throw Ce("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return r}}function nn(e,t){return`hb_miniprogram_${e}_${t}`}function co(e,t,r=El){const i=js(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Ce("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!bl.test(i))throw Ce("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function Al(e,t){let r;try{r=JSON.stringify(e)}catch{throw Ce("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw Ce("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&zs(r)>t)throw Ce("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function uo(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function js(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Ce("INVALID_PARAMS",t);return e}function lo(e){return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:Sl(e)}function Sl(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function zs(e){return new TextEncoder().encode(e).length}function Ce(e,t){return{code:e,message:t}}const ho=120;function De(e){throw{code:"INVALID_PARAMS",message:e}}function di(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gs(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&De(`${r} 不支持字段: ${n.join(", ")}`)}function vl(e){if(!di(e))return De("ui.showToast 参数必须是对象");if(Gs(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return De("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>ho)return De(`ui.showToast message 不能超过 ${ho} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return De("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function Rl(e){return e===void 0?{dismissible:!1}:di(e)?(Gs(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?De("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):De("ui.showLoading 参数必须是对象")}function Dl(e){e!==void 0&&(!di(e)||Object.keys(e).length)&&De("ui.hideLoading 不支持参数")}function Tl(e){return{[Sr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.showToast(vl(t),e.operationContext),e.operationContext.signal)},[vr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.showLoading(Rl(t),e.operationContext),e.operationContext.signal)},[Rr]:async t=>{W(e.operationContext.signal),Dl(t),await $(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const Pl={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ne(e,"当前用户首页资料接口响应异常")}},Ll=3e4;function Cl(e,t,r={}){const n=r.ttlMs??Ll;let i=0,o,s;async function a(){let u;try{u=await Fr(e,Pl,void 0,{...t,credentials:"heybox-session"})}catch(d){throw t.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):d instanceof q?l("REQUEST_UNSUPPORTED",d.message):d instanceof Ut?l("INVALID_RESPONSE","user home_v2 响应不合法"):d instanceof nt?l("REQUEST_FAILED","user home_v2 请求失败"):d instanceof rt?l("REQUEST_FAILED",d.message):kl(d)?d:l("REQUEST_FAILED","user home_v2 请求失败")}return Ol(u,"user home_v2")}function c(u){const d=Date.now();if(o?.userId===u&&o.expiresAt>d)return Promise.resolve(o.value);if(s?.userId===u&&s.generation===i)return s.promise;const h=i,p=a().then(f=>(i===h&&(o={userId:u,value:f,expiresAt:Date.now()+n}),f)).finally(()=>{s?.promise===p&&(s=void 0)});return s={userId:u,generation:h,promise:p},p}return{get:c,clear(){i+=1,o=void 0,s=void 0}}}function Ol(e,t){if(!M(e))throw l("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 l(n,r)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function kl(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Nl={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 ne(e,"Steam 游戏库接口响应异常")}},Ws=20,Ml=100,Ks=0,Ys="weeks",Ul=100,Hl=new Set(["weeks","all","achieved"]);function xl(e){const t=Cl(e.network,e.operationContext),r=new Map;let n=0,i=!1;const o=e.account.onChange(()=>{n+=1,t.clear(),r.clear()}),s=e.authorization.onEvent((b,I)=>{b==="user_info_authorization_change"&&"identity"in I&&I.identity==="denied"&&(n+=1,t.clear(),r.clear())});function a(){if(i||e.operationContext.signal.aborted)throw l("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function c(){const b=e.identity.get()?.miniProgramId?.trim();if(!b)throw l("INVALID_STATE","用户能力缺少 canonical 小程序身份");return b}async function u(){a();let b;try{b=await e.account.getCurrentUserId(e.operationContext)}catch(I){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):mo(I)?I:l("REQUEST_FAILED","读取小黑盒账号失败")}return typeof b=="string"&&b.trim()?b.trim():void 0}async function d(b,I){const y=await u();if(n!==I||y!==b)throw l("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function h(b,I){try{return await Fr(e.network,b,I,{...e.operationContext,credentials:"heybox-session"})}catch(y){throw e.operationContext.signal.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):y instanceof q?l("REQUEST_UNSUPPORTED",y.message):y instanceof Ut?l("INVALID_RESPONSE","用户接口响应不合法"):y instanceof nt?l("REQUEST_FAILED","用户请求失败"):y instanceof rt?l("REQUEST_FAILED",y.message):mo(y)?y:l("REQUEST_FAILED","用户请求失败")}}async function p(){c();const b=n,I=await u();if(!I)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[y,A]=await Promise.all([e.authorization.getOrCreateLocalIdentity(I),f(I)]);return await d(I,b),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:y.appUserId,profile:A}}}function f(b){const I=r.get(b);if(I)return I;const y=h(Is,void 0).then(A=>{const v=fo(A,"账号基础信息");if(v.display_username!==void 0&&typeof v.display_username!="string")throw l("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(v.display_avatar!==void 0&&typeof v.display_avatar!="string")throw l("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:v.display_username??"",avatar:v.display_avatar??""}}).catch(()=>({nickname:"",avatar:""})).finally(()=>{r.get(b)===y&&r.delete(b)});return r.set(b,y),y}async function _(b){const I=Bl(b);c();const y=n,A=await u();if(!A)return{isLogin:!1,isBound:!1,data:null};const v=await t.get(A);await d(A,y);const P=ui(v.steam_id_info);if(Object.keys(P).length===0)return{isLogin:!0,isBound:!1,data:null};const H=await h(Nl,{userId:A,...I,personalInformationOpen:Qs(P.personal_infomation_open??P.personal_information_open)});await d(A,y);const R=fo(H,"Steam 游戏库");return{isLogin:!0,isBound:!0,data:jl(R,I)}}return{getInfo:p,getSteamGameList:_,dispose(){i||(i=!0,n+=1,o(),s(),t.clear(),r.clear())}}}function Bl(e){if(e==null)return{limit:Ws,offset:Ks,sort:Ys,includeHidden:!1};if(!M(e))throw Te("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Te(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Fl(e.limit),offset:Vl(e.offset),sort:ql(e.sort),includeHidden:$l(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim())throw Te("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Te("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Ul))}return r}function Fl(e){if(e===void 0)return Ws;if(!Number.isInteger(e)||Number(e)<1)throw Te("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Ml)}function Vl(e){if(e===void 0)return Ks;if(!Number.isInteger(e)||Number(e)<0)throw Te("user.getSteamGameList offset 必须是非负整数");return Number(e)}function ql(e){if(e===void 0)return Ys;if(typeof e!="string"||!Hl.has(e))throw Te("user.getSteamGameList sort 不支持");return e}function $l(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Te("user.getSteamGameList includeHidden 必须是 boolean");return e}function jl(e,t){if(!Array.isArray(e.game_list))throw l("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(zl).filter(a=>a!==void 0),n=Mr(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=Qs(e.is_me);return s!==void 0&&(o.isMe=s),o}function zl(e){const t=ui(e),r=Mr(t.appid),n=Mr(t.steam_appid)??r,i=li(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};yt(o,"image",t.image),yt(o,"icon",t.appicon??t.icon),wt(o,"playtimeForever",t.playtime_forever),wt(o,"playtime2Weeks",t.playtime_2weeks);const s=Wl(t.external_tags??t.tags);s.length&&(o.tags=s);const a=Gl(t.price);return a&&(o.price=a),o}function Gl(e){const t=ui(e),r={};return yt(r,"current",t.current),yt(r,"initial",t.initial),wt(r,"discount",t.discount),wt(r,"lowestPrice",t.lowest_price),yt(r,"deadlineDate",t.deadline_date),wt(r,"deadlineTimestamp",t.deadline_timestamp),Object.keys(r).length?r:void 0}function fo(e,t){if(!M(e))throw l("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 l(n,r)}if(!M(e.result))throw l("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function ui(e){return M(e)?e:{}}function li(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Wl(e){return Array.isArray(e)?e.map(li).filter(Boolean):[]}function Mr(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function Qs(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function yt(e,t,r){const n=li(r);n&&Object.assign(e,{[t]:n})}function wt(e,t,r){const n=Mr(r);n!==void 0&&Object.assign(e,{[t]:n})}function Te(e){return l("INVALID_PARAMS",e)}function mo(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Kl(e){return{[rr]:async t=>(go(t,"user.getInfo"),e.user.getInfo()),[nr]:async(t,r)=>{go(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[ir]:async t=>e.user.getSteamGameList(t)}}function go(e,t){if(e!==void 0)throw l("INVALID_PARAMS",`${t} 不接收入参`)}function po(e){throw{code:"INVALID_PARAMS",message:e}}function lt(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Xs(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function zt(e,t,r){return Math.min(Xs(e,t),r)}async function Yl(e){try{return Xs(await e.getNavigationBarHeight(),0)}catch{return 0}}function Ql(e,t,r,n){const i=zt(e.safeArea?.left,0,t),o=Math.max(i,zt(e.safeArea?.right,t,t)),s=zt(e.safeArea?.top,n,r),a=Math.max(s,zt(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Xl(e){const t=e.getViewportMetrics(),r=lt(t.windowWidth,0),n=lt(t.windowHeight,0),i=await Yl(e);return{pixelRatio:lt(t.pixelRatio,1),screenWidth:lt(t.screenWidth,r),screenHeight:lt(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:Ql(t,r,n,i),screenTop:i}}function Jl(e){return{[cr]:async()=>(W(e.operationContext.signal),Xl(e.presentation)),[dr]:async t=>{if(W(e.operationContext.signal),typeof t!="object"||t===null||Array.isArray(t))return po("viewport.setNavigationBarStyle 参数必须是对象");const r=t.foregroundStyle;if(r!=="light"&&r!=="dark")return po("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await $(()=>e.presentation.setNavigationBarStyle(r,e.operationContext),e.operationContext.signal)}}}const Zl=new Map(Le.map(e=>[e.method,e]));function on(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function eh(e){const t=Br(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 th(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=d=>{a||(a=!0,n.removeEventListener("abort",u),d())},u=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",u,{once:!0}),i.then(d=>c(()=>o({status:"handled",value:d})),d=>c(()=>s(d)))})}function rh(e){const t=eh(e.runtimePermissions);let r=0;return{async dispatch(n,i,o){const s=e.now??nh,a=e.onTrace?s():0,c=e.onTrace?`cap_${++r}`:"";try{if(e.terminalSignal.aborted)throw on("RUNTIME_DESTROYED","小程序 Runtime 已终止");Za(n,e.effectiveCapabilities);const u=Zl.get(n);if(!u)throw new Error(`Capability method ${n} 缺少 protocol metadata`);const d=t(u);if(!d.allowed)throw on(d.code,d.message,d.data);const h=e.handlers[n];if(!h)throw new Error(`Capability method ${n} 缺少 handler`);const p=await th(async()=>{for(const f of e.policies??[]){const _=await f.evaluate({method:n,payload:i,capability:u});if(e.terminalSignal.aborted)throw Eo();if(!_.allowed)throw on(_.code,_.message,_.data)}if(e.terminalSignal.aborted)throw Eo();return h(i,o)},void 0,o,e.terminalSignal);return yo(e.onTrace,wo(c,n,i,a,p),s),p}catch(u){throw yo(e.onTrace,wo(c,n,i,a,{status:"error",error:u}),s),u}}}}function nh(){return typeof performance>"u"?Date.now():performance.now()}function yo(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 wo(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:ih(i.error)}:{},...oh(t,r,i)}}function ih(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function oh(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"&&sh(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 sh(e){return typeof e=="object"&&e!==null}function Eo(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function ah(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=new gd(e.files,e.miniProgramDetail),n=Ad({registry:r,picker:e.picker,operationContext:t}),i=Oc({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation});let o,s,a=()=>{};try{o=xl({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:i}),a=i.onEvent((f,_)=>e.eventSink.postEvent(f,_)),s=sd({account:e.account,identity:e.identity,network:e.network,operationContext:t});const c=_l({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),u=[{name:"auth",handlers:Fc({authorization:i})},{name:"user",handlers:Kl({user:o,authorization:i})},{name:"share",handlers:wl({environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:Jl({operationContext:t,presentation:e.hostPresentation})},{name:"storage",handlers:c.handlers},{name:"network",handlers:Pu({network:e.network,transfer:e.transfer,fileRegistry:r,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins})},{name:"files",handlers:n.files},{name:"file",handlers:n.file},{name:"directory",handlers:n.directory},{name:"ui",handlers:Tl({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:hd({operationContext:t,presentation:e.hostPresentation})},{name:"navigation",handlers:jd({operationContext:t,presentation:e.hostPresentation})},{name:"cloud",handlers:s.handlers}],d=ch(u);let h=!1;const p=()=>{h||(h=!0,e.terminalSignal.removeEventListener("abort",p),s?.dispose(),a(),o?.dispose(),i.dispose(),r.dispose())};return e.terminalSignal.aborted?p():e.terminalSignal.addEventListener("abort",p,{once:!0}),{modules:u,handlers:d,...c.diagnostics?{storageDiagnostics:c.diagnostics}:{},dispose:p}}catch(c){throw s?.dispose(),a(),o?.dispose(),i.dispose(),r.dispose(),c}}function ch(e){const t=new Map(Le.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=Le.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Le.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const dh="heybox-mini-dev:";function bo(e){try{return uh(new URL(e))}catch{return!1}}function uh(e){return e.protocol===dh}function lh(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||hh(e)}function hh(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 fh=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function mh(e,t){const r=[],n=gh(e.environmentInfo,r),i=Qt(n?.appVersion,"host.appVersion",r),o=yh(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:ph(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:Qt(t.miniProgramId),version:Qt(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function gh(e,t){if(e!=null){if(Js(e))return e;t.push("environmentInfo")}}function ph(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function yh(e,t){if(e==null)return{name:"unknown",version:null};if(!Js(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=fh.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:Qt(e.version,"operatingSystem.version",t)}}function Qt(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const wh=1,Zs="allow-scripts allow-same-origin",Eh="",bh="no-referrer";function _h(e=Zs){return!e.split(/\s+/).includes("allow-same-origin")}function _o(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Ih=new Set(["javascript:","data:","blob:","file:"]),Io="xiaoheihe.cn";function Ah(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(Ih.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!Th(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Sh(e,t){const r=new URL(e);return r.searchParams.set(Ha,t),r.toString()}function vh(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Rh(r)??Dh(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function Rh(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Dh(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function Ao(e){const t=new URL(e);return hi(t)?"loopback":fi(t)?"lan":"production"}function Th(e,t,r){return Ph(e)||hi(e)||fi(e)&&Ch(t,r)}function Ph(e){return e.protocol==="https:"&&Nh(e.hostname)}function hi(e){return e.protocol==="http:"&&Lh(e.hostname)}function Lh(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function fi(e){return e.protocol==="http:"&&Oh(e.hostname)}function Ch(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return hi(r)||fi(r)}catch{return!1}}function Oh(e){const t=kh(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function kh(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 Nh(e){return e===Io||e.endsWith(`.${Io}`)}const Mh=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"]),Uh=new Set(["url","inline","eval","unknown"]),Hh=/^\/(?:\:segment(?:\/\:segment)*)?$/,xh=/^[a-f0-9]{64}$/,Bh=255,Fh=160,Vh=256;function qh(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!Mh.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>Vh||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Uh.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=$h(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>Fh||!Hh.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!xh.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 $h(e){if(e!==void 0&&!(typeof e!="string"||e.length>Bh))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const jh=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 zh(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:Gh(i.pathname),sanitizedPathnameHash:Wh(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function Gh(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function Wh(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 I=0;I<16;I+=1)o[I]=s.getUint32(a+I*4,!1);for(let I=16;I<64;I+=1){const y=o[I-15],A=o[I-2],v=le(y,7)^le(y,18)^y>>>3,P=le(A,17)^le(A,19)^A>>>10;o[I]=o[I-16]+v+o[I-7]+P>>>0}let[c,u,d,h,p,f,_,b]=i;for(let I=0;I<64;I+=1){const y=b+(le(p,6)^le(p,11)^le(p,25))+(p&f^~p&_)+jh[I]+o[I]>>>0,A=(le(c,2)^le(c,13)^le(c,22))+(c&u^c&d^u&d);b=_,_=f,f=p,p=h+y>>>0,h=d,d=u,u=c,c=y+A>>>0}[c,u,d,h,p,f,_,b].forEach((I,y)=>{i[y]=i[y]+I>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function le(e,t){return e>>>t|e<<32-t}const Kh=/^(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 Yh(e){if(!e?.minimumSdkVersion)throw U("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=gt(e.minimumSdkVersion),r=e.sdkVersion?gt(e.sdkVersion):void 0;if(!t)throw U("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw U("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=gt("0.6.0");if(!r){if(sn(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw U("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0)throw U("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(sn(r,t)<0)throw U("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:sn(r,gt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Qh(e,t){if(typeof t!="string"||!gt(t))throw U("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw U("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function gt(e){const t=Kh.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 sn(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 Xh=1e4,an=2e3,Jh=2,Zh="open-with-native-credential-policy",ea="安全提示",ta="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class ef{nonce=_o();runtimeId=_o();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;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;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=_s(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??Xh,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??U("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??U("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(uf(),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=U("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"),!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.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=Yh(t.sdkVersionPolicy);const r=mh(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.miniProgramDetail=ff(t),this.effectiveCapabilities=bs(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),of(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}this.bridgeServer?.setTargetOrigin(af(n)),this.launchUrl=n,this.miniProgramSrc=Sh(n,this.nonce),this.traceSecurityPolicy(n),this.setStatus("src_resolved"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"src_resolved"}),this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ae(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=ah({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,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,miniProgramPresentation:this.miniProgramPresentation,miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins});const r=rh({handlers:this.capabilityGraph.handlers,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:u,network:d})=>{const h={type:"capability",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...u?{errorCode:u}:{},...this.identity,...d?{network:d}:{}};Ae(this.options.onCapabilityTrace,h)}}:{}});this.bridgeServer=new Xa({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(U("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 nf(t)?t:ra(U("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 Ah(t,r,{allowPrivateNetwork:bo(r)||So(r)||await this.isDevRuntime()})}catch(r){throw U("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??df)({message:ta,title:ea,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Ao(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!bo(r)&&!So(r)}async closeAfterDevLaunchCancellation(){const t=U("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{vo(),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(()=>vo())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Eh),this.iframe.setAttribute("referrerpolicy",bh),this.iframe.setAttribute("sandbox",Zs)}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),Ae(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),Ae(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Qh(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(U("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>=Jh)){this.failRuntime(U("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Vt,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},an),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Vt})}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(Vt,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Vt})}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(U("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 文档再验证超时")))},an))}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()},an))}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===Ba){this.handleCspViolation(t.payload);return}if(t.method!==xa)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(U("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!vh(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(U("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=qh(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){Ae(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=zh(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(U("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:wh,launchUrlType:Ao(t),networkPolicy:Zh})}failRuntime(t){const r=tf(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),Ae(this.options.onError,rf(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,Ae(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ae(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 tf(e){const t=ys(e);return Ur(e)&&"cause"in e&&ra(t,e.cause),t}function ra(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function rf(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function nf(e){return Ur(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Ur(e){return!!e&&typeof e=="object"}function Ae(e,t){try{e?.(t)}catch{}}function of(e,t,r){try{e?.(t,r)}catch{}}function So(e){try{const t=new URL(e);return t.protocol==="http:"&&lh(t.hostname)}catch{return!1}}function sf(e){try{return new URL(e).origin}catch{return}}function af(e){return _h()?"*":sf(e)}function cf(e){return`${ea}
2
+
3
+ ${ta}
4
+
5
+ URL: ${e}`}function df(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(cf(e.url))}function vo(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function uf(){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:ls,knownMethodCount:Le.length,supportsFileCreate:Le.some(i=>i.method===vt),system:lf(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:Ye(e?.hardwareConcurrency),maxTouchPoints:Ye(e?.maxTouchPoints),screen:{width:Ye(t?.width),height:Ye(t?.height)},viewport:{width:Ye(r?.innerWidth),height:Ye(r?.innerHeight),devicePixelRatio:hf(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function lf(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 Ye(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function hf(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function ff(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 mf(e){if(!Ur(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!Ur(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 ef(e)}const gf=/^(?: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;function pf(e,t,r){return rc({mode:"request-only",request:(n,i={signal:t.signal})=>t.run(i.signal,async o=>{const s={...i,signal:o},a=Ef(n),c=n.source==="public-sdk"&&n.withCredentials===!0?await yf(a,e,r(),s):await e.authenticatedRequest(a,s);return bf(c)})}).network}function yf(e,t,r,n){if(e.source!=="public-sdk"||e.target.kind!=="absolute-url")throw new q("Web public session 只支持按 origin 隔离的 absolute-url 请求");if(!t.partitionedOriginRequest)throw new q("Web Host 未提供按 origin 隔离的 cookie jar");if(!r)throw new q("origin-session 请求前必须先解析 canonical mini-program ID");return t.partitionedOriginRequest(e,wf(e.target.url,r),n)}function wf(e,t){let r;try{r=new URL(e)}catch{throw new q("origin-session 目标必须是有效的 absolute URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new q("origin-session 目标必须使用 HTTP(S)");return{canonicalMiniProgramId:t,targetOrigin:r.origin,redirectPolicy:"error"}}function Ef(e){const t=na(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function bf(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:na(e.headers)??{}}}function na(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!_f(t)))}function _f(e){const t=e.trim().toLowerCase();return gf.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function If(e,t,r,n){const i=Df(e.presentation,t);return{account:vf(e,t,r),network:pf(e,t,n),...e.storage===void 0?{}:{storage:Rf(e,t)},...e.storage===void 0?{}:Af(e,t),...i===void 0?{}:{presentation:i}}}function Af(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 Sf(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 vf(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 Rf(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 Df(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.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)=>mc(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 Tf(){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 Gt(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(d=>d.aborted);if(i)throw Gt(i.reason);const o=new AbortController;let s;const a=new Promise((d,h)=>{s=h}),c=n.map(d=>{const h=()=>{o.signal.aborted||o.abort(d.reason),s(Gt(d.reason))};return d.addEventListener("abort",h,{once:!0}),{listener:h,source:d}});let u;try{u=Promise.resolve(r(o.signal))}catch(d){u=Promise.reject(d)}try{const d=await Promise.race([u,a]),h=n.find(p=>p.aborted);if(h)throw Gt(h.reason);return d}finally{for(const{listener:d,source:h}of c)h.removeEventListener("abort",d)}}}}function Gt(e){return new DOMException("Web Host operation aborted","AbortError")}async function Pf(e){const t=Tf(),r=new Set;let n=!1;const i=p=>{if(n||t.signal.aborted)return cn(p),()=>{};let f=!0;const _=()=>{f&&(f=!1,r.delete(_),cn(p))};return r.add(_),_},o=()=>s(e.signal.reason),s=p=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(p);for(const f of[...r])f();e.onDispose&&cn(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);let a;const c=If(e,t,i,()=>a),u=_s(c,{hostCapabilities:e.hostCapabilities}),d=Sf(e,t);let h;return{platform:"web",ports:c,environment:d,resolveLaunch:()=>(h??=t.run(void 0,async p=>{const f=await e.resolveLaunch(p),_=f.configuration.canonicalIdentity?.miniProgramId;return a=(typeof _=="string"?_.trim():"")||void 0,f}),h),...e.authPresentation===void 0?{}:{authPresentation:Lf(e.authPresentation,t)},hostCapabilities:u.effectiveCapabilities,dispose:s}}function cn(e){try{e()}catch{}}function Lf(e,t){return{confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var Qe={},dn,Ro;function Cf(){return Ro||(Ro=1,dn=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),dn}var un={},Se={},Do;function je(){if(Do)return Se;Do=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 Se.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},Se.getSymbolTotalCodewords=function(n){return t[n]},Se.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Se.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Se.isKanjiModeEnabled=function(){return typeof e<"u"},Se.toSJIS=function(n){return e(n)},Se}var ln={},To;function mi(){return To||(To=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}}})(ln)),ln}var hn,Po;function Of(){if(Po)return hn;Po=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++}},hn=e,hn}var fn,Lo;function kf(){if(Lo)return fn;Lo=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]},fn=e,fn}var mn={},Co;function Nf(){return Co||(Co=1,(function(e){const t=je().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}})(mn)),mn}var gn={},Oo;function Mf(){if(Oo)return gn;Oo=1;const e=je().getSymbolSize,t=7;return gn.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},gn}var pn={},ko;function Uf(){return ko||(ko=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,u=null,d=null;for(let h=0;h<o;h++){a=c=0,u=d=null;for(let p=0;p<o;p++){let f=i.get(h,p);f===u?a++:(a>=5&&(s+=t.N1+(a-5)),u=f,a=1),f=i.get(p,h),f===d?c++:(c>=5&&(s+=t.N1+(c-5)),d=f,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 u=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(u===4||u===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let u=0;u<o;u++){a=c=0;for(let d=0;d<o;d++)a=a<<1&2047|i.get(u,d),d>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(d,u),d>=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 u=0;u<s;u++){o(u),e.applyMask(u,i);const d=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(u,i),d<c&&(c=d,a=u)}return a}})(pn)),pn}var Wt={},No;function ia(){if(No)return Wt;No=1;const e=mi(),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 Wt.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}},Wt.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}},Wt}var yn={},ht={},Mo;function Hf(){if(Mo)return ht;Mo=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let i=0;i<255;i++)e[i]=n,t[n]=i,n<<=1,n&256&&(n^=285);for(let i=255;i<512;i++)e[i]=e[i-255]})(),ht.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},ht.exp=function(n){return e[n]},ht.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},ht}var Uo;function xf(){return Uo||(Uo=1,(function(e){const t=Hf();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}})(yn)),yn}var wn,Ho;function Bf(){if(Ho)return wn;Ho=1;const e=xf();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},wn=t,wn}var En={},bn={},_n={},xo;function oa(){return xo||(xo=1,_n.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),_n}var he={},Bo;function sa(){if(Bo)return he;Bo=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
+ ]))+`;he.KANJI=new RegExp(r,"g"),he.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),he.BYTE=new RegExp(n,"g"),he.NUMERIC=new RegExp(e,"g"),he.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return he.testKanji=function(c){return i.test(c)},he.testNumeric=function(c){return o.test(c)},he.testAlphanumeric=function(c){return s.test(c)},he}var Fo;function ze(){return Fo||(Fo=1,(function(e){const t=oa(),r=sa();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}}})(bn)),bn}var Vo;function Ff(){return Vo||(Vo=1,(function(e){const t=je(),r=ia(),n=mi(),i=ze(),o=oa(),s=7973,a=t.getBCHDigit(s);function c(p,f,_){for(let b=1;b<=40;b++)if(f<=e.getCapacity(b,_,p))return b}function u(p,f){return i.getCharCountIndicator(p,f)+4}function d(p,f){let _=0;return p.forEach(function(b){const I=u(b.mode,f);_+=I+b.getBitsLength()}),_}function h(p,f){for(let _=1;_<=40;_++)if(d(p,_)<=e.getCapacity(_,f,i.MIXED))return _}e.from=function(f,_){return o.isValid(f)?parseInt(f,10):_},e.getCapacity=function(f,_,b){if(!o.isValid(f))throw new Error("Invalid QR Code version");typeof b>"u"&&(b=i.BYTE);const I=t.getSymbolTotalCodewords(f),y=r.getTotalCodewordsCount(f,_),A=(I-y)*8;if(b===i.MIXED)return A;const v=A-u(b,f);switch(b){case i.NUMERIC:return Math.floor(v/10*3);case i.ALPHANUMERIC:return Math.floor(v/11*2);case i.KANJI:return Math.floor(v/13);case i.BYTE:default:return Math.floor(v/8)}},e.getBestVersionForData=function(f,_){let b;const I=n.from(_,n.M);if(Array.isArray(f)){if(f.length>1)return h(f,I);if(f.length===0)return 1;b=f[0]}else b=f;return c(b.mode,b.getLength(),I)},e.getEncodedBits=function(f){if(!o.isValid(f)||f<7)throw new Error("Invalid QR Code version");let _=f<<12;for(;t.getBCHDigit(_)-a>=0;)_^=s<<t.getBCHDigit(_)-a;return f<<12|_}})(En)),En}var In={},qo;function Vf(){if(qo)return In;qo=1;const e=je(),t=1335,r=21522,n=e.getBCHDigit(t);return In.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},In}var An={},Sn,$o;function qf(){if($o)return Sn;$o=1;const e=ze();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))},Sn=t,Sn}var vn,jo;function $f(){if(jo)return vn;jo=1;const e=ze(),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)},vn=r,vn}var Rn,zo;function jf(){if(zo)return Rn;zo=1;const e=ze();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)},Rn=t,Rn}var Dn,Go;function zf(){if(Go)return Dn;Go=1;const e=ze(),t=je();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)}},Dn=r,Dn}var Tn={exports:{}},Wo;function Gf(){return Wo||(Wo=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,u,d,h,p,f,_,b,I;!a.empty();){c=a.pop(),u=c.value,h=c.cost,p=r[u]||{};for(d in p)p.hasOwnProperty(d)&&(f=p[d],_=h+f,b=s[d],I=typeof s[d]>"u",(I||b>_)&&(s[d]=_,a.push(d,_),o[d]=u))}if(typeof i<"u"&&typeof s[i]>"u"){var y=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(y)}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})(Tn)),Tn.exports}var Ko;function Wf(){return Ko||(Ko=1,(function(e){const t=ze(),r=qf(),n=$f(),i=jf(),o=zf(),s=sa(),a=je(),c=Gf();function u(y){return unescape(encodeURIComponent(y)).length}function d(y,A,v){const P=[];let H;for(;(H=y.exec(v))!==null;)P.push({data:H[0],index:H.index,mode:A,length:H[0].length});return P}function h(y){const A=d(s.NUMERIC,t.NUMERIC,y),v=d(s.ALPHANUMERIC,t.ALPHANUMERIC,y);let P,H;return a.isKanjiModeEnabled()?(P=d(s.BYTE,t.BYTE,y),H=d(s.KANJI,t.KANJI,y)):(P=d(s.BYTE_KANJI,t.BYTE,y),H=[]),A.concat(v,P,H).sort(function(O,C){return O.index-C.index}).map(function(O){return{data:O.data,mode:O.mode,length:O.length}})}function p(y,A){switch(A){case t.NUMERIC:return r.getBitsLength(y);case t.ALPHANUMERIC:return n.getBitsLength(y);case t.KANJI:return o.getBitsLength(y);case t.BYTE:return i.getBitsLength(y)}}function f(y){return y.reduce(function(A,v){const P=A.length-1>=0?A[A.length-1]:null;return P&&P.mode===v.mode?(A[A.length-1].data+=v.data,A):(A.push(v),A)},[])}function _(y){const A=[];for(let v=0;v<y.length;v++){const P=y[v];switch(P.mode){case t.NUMERIC:A.push([P,{data:P.data,mode:t.ALPHANUMERIC,length:P.length},{data:P.data,mode:t.BYTE,length:P.length}]);break;case t.ALPHANUMERIC:A.push([P,{data:P.data,mode:t.BYTE,length:P.length}]);break;case t.KANJI:A.push([P,{data:P.data,mode:t.BYTE,length:u(P.data)}]);break;case t.BYTE:A.push([{data:P.data,mode:t.BYTE,length:u(P.data)}])}}return A}function b(y,A){const v={},P={start:{}};let H=["start"];for(let R=0;R<y.length;R++){const O=y[R],C=[];for(let S=0;S<O.length;S++){const w=O[S],D=""+R+S;C.push(D),v[D]={node:w,lastCount:0},P[D]={};for(let m=0;m<H.length;m++){const g=H[m];v[g]&&v[g].node.mode===w.mode?(P[g][D]=p(v[g].lastCount+w.length,w.mode)-p(v[g].lastCount,w.mode),v[g].lastCount+=w.length):(v[g]&&(v[g].lastCount=w.length),P[g][D]=p(w.length,w.mode)+4+t.getCharCountIndicator(w.mode,A))}}H=C}for(let R=0;R<H.length;R++)P[H[R]].end=0;return{map:P,table:v}}function I(y,A){let v;const P=t.getBestModeForData(y);if(v=t.from(A,P),v!==t.BYTE&&v.bit<P.bit)throw new Error('"'+y+'" cannot be encoded with mode '+t.toString(v)+`.
8
+ Suggested mode is: `+t.toString(P));switch(v===t.KANJI&&!a.isKanjiModeEnabled()&&(v=t.BYTE),v){case t.NUMERIC:return new r(y);case t.ALPHANUMERIC:return new n(y);case t.KANJI:return new o(y);case t.BYTE:return new i(y)}}e.fromArray=function(A){return A.reduce(function(v,P){return typeof P=="string"?v.push(I(P,null)):P.data&&v.push(I(P.data,P.mode)),v},[])},e.fromString=function(A,v){const P=h(A,a.isKanjiModeEnabled()),H=_(P),R=b(H,v),O=c.find_path(R.map,"start","end"),C=[];for(let S=1;S<O.length-1;S++)C.push(R.table[O[S]].node);return e.fromArray(f(C))},e.rawSplit=function(A){return e.fromArray(h(A,a.isKanjiModeEnabled()))}})(An)),An}var Yo;function Kf(){if(Yo)return un;Yo=1;const e=je(),t=mi(),r=Of(),n=kf(),i=Nf(),o=Mf(),s=Uf(),a=ia(),c=Bf(),u=Ff(),d=Vf(),h=ze(),p=Wf();function f(R,O){const C=R.size,S=o.getPositions(O);for(let w=0;w<S.length;w++){const D=S[w][0],m=S[w][1];for(let g=-1;g<=7;g++)if(!(D+g<=-1||C<=D+g))for(let E=-1;E<=7;E++)m+E<=-1||C<=m+E||(g>=0&&g<=6&&(E===0||E===6)||E>=0&&E<=6&&(g===0||g===6)||g>=2&&g<=4&&E>=2&&E<=4?R.set(D+g,m+E,!0,!0):R.set(D+g,m+E,!1,!0))}}function _(R){const O=R.size;for(let C=8;C<O-8;C++){const S=C%2===0;R.set(C,6,S,!0),R.set(6,C,S,!0)}}function b(R,O){const C=i.getPositions(O);for(let S=0;S<C.length;S++){const w=C[S][0],D=C[S][1];for(let m=-2;m<=2;m++)for(let g=-2;g<=2;g++)m===-2||m===2||g===-2||g===2||m===0&&g===0?R.set(w+m,D+g,!0,!0):R.set(w+m,D+g,!1,!0)}}function I(R,O){const C=R.size,S=u.getEncodedBits(O);let w,D,m;for(let g=0;g<18;g++)w=Math.floor(g/3),D=g%3+C-8-3,m=(S>>g&1)===1,R.set(w,D,m,!0),R.set(D,w,m,!0)}function y(R,O,C){const S=R.size,w=d.getEncodedBits(O,C);let D,m;for(D=0;D<15;D++)m=(w>>D&1)===1,D<6?R.set(D,8,m,!0):D<8?R.set(D+1,8,m,!0):R.set(S-15+D,8,m,!0),D<8?R.set(8,S-D-1,m,!0):D<9?R.set(8,15-D-1+1,m,!0):R.set(8,15-D-1,m,!0);R.set(S-8,8,1,!0)}function A(R,O){const C=R.size;let S=-1,w=C-1,D=7,m=0;for(let g=C-1;g>0;g-=2)for(g===6&&g--;;){for(let E=0;E<2;E++)if(!R.isReserved(w,g-E)){let T=!1;m<O.length&&(T=(O[m]>>>D&1)===1),R.set(w,g-E,T),D--,D===-1&&(m++,D=7)}if(w+=S,w<0||C<=w){w-=S,S=-S;break}}}function v(R,O,C){const S=new r;C.forEach(function(E){S.put(E.mode.bit,4),S.put(E.getLength(),h.getCharCountIndicator(E.mode,R)),E.write(S)});const w=e.getSymbolTotalCodewords(R),D=a.getTotalCodewordsCount(R,O),m=(w-D)*8;for(S.getLengthInBits()+4<=m&&S.put(0,4);S.getLengthInBits()%8!==0;)S.putBit(0);const g=(m-S.getLengthInBits())/8;for(let E=0;E<g;E++)S.put(E%2?17:236,8);return P(S,R,O)}function P(R,O,C){const S=e.getSymbolTotalCodewords(O),w=a.getTotalCodewordsCount(O,C),D=S-w,m=a.getBlocksCount(O,C),g=S%m,E=m-g,T=Math.floor(S/m),k=Math.floor(D/m),F=k+1,V=T-k,Z=new c(V);let se=0;const J=new Array(m),z=new Array(m);let ye=0;const Wr=new Uint8Array(R.buffer);for(let Ge=0;Ge<m;Ge++){const Kr=Ge<E?k:F;J[Ge]=Wr.slice(se,se+Kr),z[Ge]=Z.encode(J[Ge]),se+=Kr,ye=Math.max(ye,Kr)}const at=new Uint8Array(S);let Ii=0,we,Ee;for(we=0;we<ye;we++)for(Ee=0;Ee<m;Ee++)we<J[Ee].length&&(at[Ii++]=J[Ee][we]);for(we=0;we<V;we++)for(Ee=0;Ee<m;Ee++)at[Ii++]=z[Ee][we];return at}function H(R,O,C,S){let w;if(Array.isArray(R))w=p.fromArray(R);else if(typeof R=="string"){let T=O;if(!T){const k=p.rawSplit(R);T=u.getBestVersionForData(k,C)}w=p.fromString(R,T||40)}else throw new Error("Invalid data");const D=u.getBestVersionForData(w,C);if(!D)throw new Error("The amount of data is too big to be stored in a QR Code");if(!O)O=D;else if(O<D)throw new Error(`
9
+ The chosen QR Code version cannot contain this amount of data.
10
+ Minimum version required to store current data is: `+D+`.
11
+ `);const m=v(O,C,w),g=e.getSymbolSize(O),E=new n(g);return f(E,O),_(E),b(E,O),y(E,C,0),O>=7&&I(E,O),A(E,m),isNaN(S)&&(S=s.getBestMask(E,y.bind(null,E,C))),s.applyMask(S,E),y(E,C,S),{modules:E,version:O,errorCorrectionLevel:C,maskPattern:S,segments:w}}return un.create=function(O,C){if(typeof O>"u"||O==="")throw new Error("No input text");let S=t.M,w,D;return typeof C<"u"&&(S=t.from(C.errorCorrectionLevel,t.M),w=u.from(C.version),D=s.from(C.maskPattern),C.toSJISFunc&&e.setToSJISFunction(C.toSJISFunc)),H(O,w,S,D)},un}var Pn={},Ln={},Qo;function aa(){return Qo||(Qo=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),u=Math.floor((s+o.margin*2)*c),d=o.margin*c,h=[o.color.light,o.color.dark];for(let p=0;p<u;p++)for(let f=0;f<u;f++){let _=(p*u+f)*4,b=o.color.light;if(p>=d&&f>=d&&p<u-d&&f<u-d){const I=Math.floor((p-d)/c),y=Math.floor((f-d)/c);b=h[a[I*s+y]?1:0]}n[_++]=b.r,n[_++]=b.g,n[_++]=b.b,n[_]=b.a}}})(Ln)),Ln}var Xo;function Yf(){return Xo||(Xo=1,(function(e){const t=aa();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,u=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(u=n()),c=t.getOptions(c);const d=t.getImageWidth(o.modules.size,c),h=u.getContext("2d"),p=h.createImageData(d,d);return t.qrToImageData(p.data,o,c),r(h,u,d),h.putImageData(p,0,0),u},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const u=e.render(o,s,c),d=c.type||"image/png",h=c.rendererOpts||{};return u.toDataURL(d,h.quality)}})(Pn)),Pn}var Cn={},Jo;function Qf(){if(Jo)return Cn;Jo=1;const e=aa();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,u=!1,d=0;for(let h=0;h<i.length;h++){const p=Math.floor(h%o),f=Math.floor(h/o);!p&&!u&&(u=!0),i[h]?(d++,h>0&&p>0&&i[h-1]||(a+=u?r("M",p+s,.5+f+s):r("m",c,0),c=0,u=!1),p+1<o&&i[h+1]||(a+=r("h",d),d=0)):c++}return a}return Cn.render=function(o,s,a){const c=e.getOptions(s),u=o.modules.size,d=o.modules.data,h=u+c.margin*2,p=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+h+"v"+h+'H0z"/>':"",f="<path "+t(c.color.dark,"stroke")+' d="'+n(d,u,c.margin)+'"/>',_='viewBox="0 0 '+h+" "+h+'"',I='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+_+' shape-rendering="crispEdges">'+p+f+`</svg>
12
+ `;return typeof a=="function"&&a(null,I),I},Cn}var Zo;function Xf(){if(Zo)return Qe;Zo=1;const e=Cf(),t=Kf(),r=Yf(),n=Qf();function i(o,s,a,c,u){const d=[].slice.call(arguments,1),h=d.length,p=typeof d[h-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(h<2)throw new Error("Too few arguments provided");h===2?(u=a,a=s,s=c=void 0):h===3&&(s.getContext&&typeof u>"u"?(u=c,c=void 0):(u=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(f,_){try{const b=t.create(a,c);f(o(b,s,c))}catch(b){_(b)}})}try{const f=t.create(a,c);u(null,o(f,s,c))}catch(f){u(f)}}return Qe.create=t.create,Qe.toCanvas=i.bind(null,r.render),Qe.toDataURL=i.bind(null,r.renderToDataURL),Qe.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),Qe}var Jf=Xf();const Pt=500,Zf=new Set(["authorization","cookie","proxy-authorization","set-cookie","token","x-pkey","api-key","apikey","x-api-key","x-auth-token","x-access-token","session","session-id","jwt","refresh-token","x-csrf-token"]),em=/(authorization|cookie|password|passwd|secret|token|pkey|private[_-]?key|access[_-]?key|client[_-]?secret|api[_-]?key|apikey|session|jwt|refresh[_-]?token|csrf)/i;function es(e){if(!e)return e;try{const t=new URL(e);if(t.username="",t.password="",ts(t.searchParams),t.hash&&t.hash.length>1){const r=t.hash.slice(1);if(r.includes("=")){const n=new URLSearchParams(r);ts(n)&&(t.hash=n.toString())}}return t.toString()}catch{return da(e)}}function tm(e){return e?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,rm(t)?"[redacted]":r])):{}}function Vn(e){if(e!==void 0){if(typeof e=="string")return ca(e);if(typeof e=="number"||typeof e=="boolean"||e===null)return e;try{const t=qn(e),r=JSON.stringify(t);return r===void 0?"[unserializable]":r.length<=Pt?t:gi(r,Pt)}catch{return"[unserializable]"}}}function Et(e){return Array.isArray(e)?e.slice(0,20).map(t=>Et(t)):typeof e=="string"?nm(e)?es(e):ca(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?e:$n(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>{const n=t.trim().toLowerCase();return st(t)?[t,"[redacted]"]:n==="headers"&&$n(r)?[t,tm(Object.fromEntries(Object.entries(r).flatMap(([i,o])=>typeof o=="string"?[[i,o]]:[])))]:(n==="url"||n.endsWith("_url")||n.endsWith("url"))&&typeof r=="string"?[t,es(r)]:[t,Et(r)]})):Vn(e)}function rm(e){const t=e.trim().toLowerCase();return Zf.has(t)||st(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function st(e){return em.test(e.trim())}function ca(e){const t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return Vn(JSON.parse(t))}catch{}if(t.includes("=")&&!t.includes(`
13
+ `)&&t.length<=Pt*2)try{const r=new URLSearchParams(t);if([...r.keys()].length>0){const n=Object.fromEntries([...r.entries()].map(([i,o])=>[i,st(i)?"[redacted]":o]));return Vn(n)}}catch{}return gi(da(e),Pt)}function qn(e){return Array.isArray(e)?e.slice(0,20).map(t=>qn(t)):$n(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,st(t)?"[redacted]":qn(r)])):typeof e=="string"?gi(e,Pt):e}function ts(e){let t=!1;for(const r of[...e.keys()])st(r)&&(e.set(r,"[redacted]"),t=!0);return t}function da(e){return e.replace(/([?&#]|^|[?&])([^=&#\s]+)=([^&#\s]*)/g,(t,r,n,i)=>st(n)?`${r}${n}=[redacted]`:t)}function nm(e){return/^https?:\/\//i.test(e.trim())||/^[a-z][a-z0-9+.-]*:\/\//i.test(e.trim())}function gi(e,t){return e.length<=t?e:`${e.slice(0,t)}…(truncated, total=${e.length})`}function $n(e){return Object.prototype.toString.call(e)==="[object Object]"}const im="/__hb_sdk__/dev-context";function om(e){if(!jn(e)||!rs(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!jn(t)||!rs(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const sm={networkRequest:{status:"disabled",useOfficialDomain:!1}};function am(e){const t=Br(e.runtimePermissions),r=t.permissions.network;return t.valid&&r?{networkRequest:{status:r.status,useOfficialDomain:r.config.useOfficialDomain===!0}}:um()}function cm(e,t){return ua(e,t,t.networkRequest.useOfficialDomain)}function dm(e,t){return ua(e,t,!1)}function um(){return{networkRequest:{...sm.networkRequest}}}function ua(e,t,r){const n=Br(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of ri){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=jn(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 jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function rs(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function lm(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 u;try{u=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 d;try{d=e.apply(u)}catch(h){a={ok:!1},n||s(h);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(d))try{await e.onChanged(d)}catch(h){a={ok:!1},n||s(h)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function hm(e){return lm({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 fm(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 mm={identity:"小程序身份",profile:"昵称和头像"};function gm(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=`
14
+ <div class="hb-sdk-auth-dialog__panel">
15
+ <h2>授权请求</h2>
16
+ <p class="hb-sdk-auth-dialog__app">${On(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
17
+ <ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(a=>`<li>${On(mm[a]||a)}</li>`).join("")}</ul>
18
+ ${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${On(e.userProfile.nickname)}</p>`:""}
19
+ <div class="hb-sdk-auth-dialog__actions">
20
+ <button type="button" data-action="deny">拒绝</button>
21
+ <button type="button" class="primary" data-action="allow">允许</button>
22
+ </div>
23
+ </div>
24
+ `;const i=a=>{s(),t(a)},o=()=>{s(),r(e.signal.reason)},s=()=>{e.signal.removeEventListener("abort",o),n.remove()};n.querySelector('[data-action="allow"]')?.addEventListener("click",()=>{i({status:"granted",grantedScopes:[...e.scopes]})}),n.querySelector('[data-action="deny"]')?.addEventListener("click",()=>{i({status:"cancelled"})}),e.signal.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n)})}function On(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}function pm(e){return{launchUrl:e.launchUrl,sdkVersionPolicy:{minimumSdkVersion:"0.5.0",releaseChannel:"development"},runtimePermissions:e.runtimePermissions,environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const ns="hb-sdk-action-dialog-style";function pi(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}bm();const n=document.createElement("div");n.className="hb-sdk-action-dialog",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.innerHTML=`
25
+ <div class="hb-sdk-action-dialog__panel">
26
+ <h2>${is(e.title)}</h2>
27
+ <pre class="hb-sdk-action-dialog__detail">${is(e.detail)}</pre>
28
+ <div class="hb-sdk-action-dialog__actions">
29
+ <button type="button" class="primary" data-action="confirm">确定</button>
30
+ </div>
31
+ </div>
32
+ `;const i=()=>{s(),t()},o=()=>{s(),r(e.signal?.reason)},s=()=>{e.signal?.removeEventListener("abort",o),n.remove()};n.querySelector('[data-action="confirm"]')?.addEventListener("click",i),e.signal?.addEventListener("abort",o,{once:!0}),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n)})}async function ym(e,t){await pi({title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+Lt(e.params)].join(`
33
+ `),signal:t.signal})}async function wm(e,t){await pi({title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+Lt(e.channel),"post: "+Lt(e.post)].join(`
34
+ `),signal:t.signal})}async function Em(e,t){await pi({title:"截图分享",detail:["rect: "+Lt(e.rect),"post: "+Lt(e.post)].join(`
35
+ `),signal:t.signal})}function Lt(e){return JSON.stringify(e,null,2)}function is(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}function bm(){if(document.getElementById(ns))return;const e=document.createElement("style");e.id=ns,e.textContent=`
36
+ .hb-sdk-action-dialog {
37
+ position: absolute;
38
+ inset: 0;
39
+ z-index: 40;
40
+ display: grid;
41
+ place-items: center;
42
+ padding: 24px;
43
+ background: rgba(15, 23, 42, 0.45);
44
+ }
45
+
46
+ .hb-sdk-action-dialog__panel {
47
+ width: min(420px, 100%);
48
+ border-radius: 12px;
49
+ padding: 20px;
50
+ background: #fff;
51
+ box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
52
+ }
53
+
54
+ .hb-sdk-action-dialog__panel h2 {
55
+ margin: 0 0 8px;
56
+ font-size: 18px;
57
+ }
58
+
59
+ .hb-sdk-action-dialog__detail {
60
+ margin: 0 0 16px;
61
+ max-height: 40vh;
62
+ overflow: auto;
63
+ color: #1f2933;
64
+ font-family: inherit;
65
+ font-size: 12px;
66
+ line-height: 1.6;
67
+ white-space: pre-wrap;
68
+ overflow-wrap: anywhere;
69
+ word-break: break-word;
70
+ }
71
+
72
+ .hb-sdk-action-dialog__actions {
73
+ display: flex;
74
+ justify-content: flex-end;
75
+ gap: 8px;
76
+ }
77
+
78
+ .hb-sdk-action-dialog__actions button {
79
+ min-height: 36px;
80
+ border: 1px solid #cad5e2;
81
+ border-radius: 6px;
82
+ padding: 0 12px;
83
+ background: #fff;
84
+ cursor: pointer;
85
+ }
86
+
87
+ .hb-sdk-action-dialog__actions .primary {
88
+ border-color: #2563eb;
89
+ color: #fff;
90
+ background: #2563eb;
91
+ }
92
+ `,document.head.appendChild(e)}function _m(e){return{close:async()=>{await e.close()},reload:async()=>{await e.reload()},getViewportMetrics:()=>{const t=e.getDeviceMetrics?.();return t?{windowWidth:t.screenWidth,windowHeight:t.screenHeight,screenWidth:t.screenWidth,screenHeight:t.screenHeight,pixelRatio:t.pixelRatio,safeArea:{top:t.safeAreaInsets.top,right:t.screenWidth-t.safeAreaInsets.right,bottom:t.screenHeight-t.safeAreaInsets.bottom,left:t.safeAreaInsets.left}}:{windowWidth:window.innerWidth,windowHeight:window.innerHeight,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}},getNavigationBarHeight:()=>e.getDeviceMetrics?.().statusBarHeight??0,setNavigationBarStyle:t=>{document.documentElement.dataset.navigationBarStyle=t},setClipboard:async({text:t})=>{await navigator.clipboard.writeText(t)},showToast:async({message:t,status:r})=>{e.pushLog("host.message",{message:t,status:r}),await Ua({message:t,status:r})},showLoading:Ma,hideLoading:Na,vibrate:ka,openAppPage:ym,showShareMenu:wm,captureAndShare:Em,setScreenshotChromeHidden:Oa}}const Im=/^[A-Za-z0-9_-]{22}$/,Am="https://api.xiaoheihe.cn/open_inapp/";function Sm(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(!Im.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 vm(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`${Am}#${r}`}const Rm="__hb_sdk_mini_dev__",Dm="hb-sdk:mini-dev-console",Tm="__hb_sdk_mini_dev_console_installed__",os=Tm;function Pm(e,t=console){Cm(t,e,t)}const Lm=["log","debug","info","warn","error"];function Cm(e,t,r){if(!r||r[os]===!0)return!1;let n=!1;for(const i of Lm){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[os]=!0),n}const zn=1,ss=64*1024,Om=64,km=/^[A-Za-z0-9_-]{22}$/;class te extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function Nm(e,t=!1){const r=Um(e,t);switch(Gn(r,"Server message"),Hm(r),r.type){case"grant":return bt(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),_t(r.connectionEpoch,"connectionEpoch"),Me(r.nextClientSequence,"nextClientSequence"),Me(r.nextServerSequence,"nextServerSequence"),as(r.snapshot),r;case"event":return bt(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),_t(r.connectionEpoch,"connectionEpoch"),Me(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&Oe("event must be account.changed or status.changed"),as(r.snapshot),r;case"heartbeat":return bt(r,["version","type","connectionEpoch","sequence"],"heartbeat"),_t(r.connectionEpoch,"connectionEpoch"),Me(r.sequence,"sequence"),r;default:return Oe("Unknown server message type")}}function Mm(e){const t=e.connectionEpoch;_t(t,"connectionEpoch"),Me(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(_t(n.connectionEpoch,"connectionEpoch"),Me(n.sequence,"sequence"),n.connectionEpoch!==t)throw new te("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new te("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new te("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function Um(e,t){if(t)throw new te("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new te("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>ss)throw new te("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>ss)throw new te("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return xm(e),JSON.parse(e)}catch(r){throw r instanceof te?r:new te("INVALID_JSON","Channel frame must contain strict JSON")}}function as(e){Gn(e,"snapshot"),bt(e,["account","permissions"],"snapshot"),Gn(e.account,"snapshot.account"),bt(e.account,["revision"],"snapshot.account"),Me(e.account.revision,"snapshot.account.revision"),om(e.permissions)||Oe("snapshot.permissions is invalid")}function Hm(e){e.version!==zn&&Oe("version must be 1")}function Gn(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Oe(`${t} must be a plain JSON object`)}function bt(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)))&&Oe(`${r} fields are invalid`)}function Me(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Oe(`${t} must be a non-negative safe integer`)}function _t(e,t){(typeof e!="string"||!km.test(e))&&Oe(`${t} must be a 22-character base64url value`)}function Oe(e){throw new te("INVALID_MESSAGE",e)}function xm(e){new Bm(e).scan()}class Bm{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>=Om)throw new te("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 te("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 cs=[1e3,2e3,4e3,8e3,15e3];function Fm(e){const t=new Set,r=e.webSocketFactory??(w=>new WebSocket(w)),n=e.randomValues??(w=>crypto.getRandomValues(w)),i=e.timers??{clearTimeout:w=>window.clearTimeout(w),setTimeout:(w,D)=>window.setTimeout(w,D)},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,u,d,h=!1,p=0,f,_=!1,b=!1;const I=new Set,y=(w,D)=>{if(!(!e.onDiagnostic||I.has(w))){I.add(w);try{e.onDiagnostic({phase:w,...D?{code:D}:{}})}catch{}}},A=(w,D,m=!1)=>{if(d&&w.account.revision<d.account.revision)return;const g=d&&JSON.stringify(w)===JSON.stringify(d);if(d=w,!(g&&!m))for(const E of t)E(w,D)},v=()=>{if(h||f!==void 0||c)return;const w=cs[Math.min(p,cs.length-1)];p+=1,f=i.setTimeout(()=>{f=void 0,S()},w)},P=()=>{h||!_||c||(f!==void 0&&(i.clearTimeout(f),f=void 0),S())},H=()=>{a()&&P()},R=()=>{s&&!s.hidden&&P()},O=()=>{b||(b=!0,o?.addEventListener("online",H),s?.addEventListener("visibilitychange",R))},C=()=>{b&&(b=!1,o?.removeEventListener("online",H),s?.removeEventListener("visibilitychange",R))},S=()=>{if(h||c)return;_=!0,O(),f!==void 0&&(i.clearTimeout(f),f=void 0);let w,D;try{w=r(e.url)}catch{y("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),v();return}try{D=qm(n)}catch{y("entropy","NONCE_GENERATION_FAILED");try{w?.close(1011,"channel initialization failed")}catch{}v();return}c=w;let m,g,E;const T=()=>{w.removeEventListener("open",F),w.removeEventListener("message",V),w.removeEventListener("close",Z),w.removeEventListener("error",se),u===T&&(u=void 0)},k=()=>{if(c===w){c=void 0,T();try{w.close(1008,"invalid channel state")}catch{}v()}},F=()=>{if(!(h||c!==w))try{w.send(JSON.stringify({version:zn,type:"hello",csrfToken:e.csrfToken,clientNonce:D}))}catch{y("send","HELLO_SEND_FAILED"),k()}},V=J=>{if(h||c!==w)return;if(typeof J.data!="string"){y("parse","TEXT_FRAME_REQUIRED"),k();return}let z;try{z=Nm(J.data)}catch(ye){y("parse",ye instanceof te?ye.code:"INVALID_MESSAGE"),k();return}if(z.type==="grant"){if(E){y("sequence","DUPLICATE_GRANT"),k();return}m=z.connectionEpoch,g=z.nextClientSequence,E=Mm({connectionEpoch:m,nextSequence:z.nextServerSequence}),p=0,I.clear(),A(z.snapshot,{type:"grant"});return}if(!E||!m||g===void 0){y("sequence","MESSAGE_BEFORE_GRANT"),k();return}try{E.accept(z)}catch{y("sequence","INVALID_SEQUENCE"),k();return}if(z.type==="heartbeat"){try{w.send(JSON.stringify({version:zn,type:"heartbeat.ack",connectionEpoch:m,sequence:g}))}catch{y("send","HEARTBEAT_ACK_SEND_FAILED"),k()}g=g===Number.MAX_SAFE_INTEGER?void 0:g+1;return}A(z.snapshot,{type:"event",event:z.event},!0)},Z=()=>{c===w&&(y("close","SOCKET_CLOSED"),c=void 0,T(),v())},se=()=>{y("open","SOCKET_ERROR"),k()};w.addEventListener("open",F),w.addEventListener("message",V),w.addEventListener("close",Z),w.addEventListener("error",se),u=T};return{connect:S,subscribeUpdates(w){return t.add(w),()=>t.delete(w)},dispose(){if(h)return;h=!0,_=!1,C(),f!==void 0&&i.clearTimeout(f),f=void 0;const w=c;c=void 0,u?.(),w?.close(1e3,"client disposed"),t.clear()}}}function Vm(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 qm(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=Vm(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}try{Pm((e,t)=>{ei(`console.${e}`,{source:"host",message:t.map(r=>ma(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const $m="/__hb_sdk_bootstrap__",jm="/__hb_sdk__/mobile-launch-redirect",zm="/__hb_sdk__/network",Gm="/session/status",Wm="/session/request",Km="/session/events",Ym=320,Qm=1e3,Xm=1e3,Jm=15e3,la=new URL(location.href).searchParams,ha=la.get("mini_url"),$r=la.get("ui_preview")==="1",x={device:ft("#device"),get mobileLanSelect(){return ft("#mobile-lan-select")},get mobileQrImage(){return ft("#mobile-qr-image")},get mobileQrStatus(){return ft("#mobile-qr-status")},storageSnapshot:ft("#storage-snapshot")};if(!ha&&!$r)throw x.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Zm=ha??"about:blank",de=await wi();let ve=de.lanAddresses,Xt=de.defaultLanAddressId,Xe=de.mobileLaunchRedirect,fa=bi(de),Ze=de.devContext,Ct=am(Ze),B=!1,jr=0;const yi=new AbortController;let xe=0,tt,Ot,Jt=0,Be,Wn,Kn,Re=0,kt=!1,Zt,et,kn=!1,ds=Promise.resolve(),It=-1,Nt=!1,Fe,Yn,Qn,er,Ne;const Hr=new Set,it=hm({applyStatus:e=>Ea(e,!0),fetchStatus:e=>wa(Ta(yi.signal,e)),getCanonicalRevision:()=>It,onError:Ig,reconcile:()=>dg(jr)}),Xn=fm({connectEvents:ba,invalidate:()=>it.invalidate(),isDisposed:()=>B,maxDelayMs:Jm,minDelayMs:Xm,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});await Jn(!1);va();Da(Ra(de));$r&&ng();zr();await Bt("initial");$r||(ba(),ag());eg();function eg(){window.addEventListener("beforeunload",Ag),window.addEventListener("hb-sdk:restart-runtime",pa),window.addEventListener("hb-sdk:refresh-storage",zr),window.addEventListener("hb-sdk:qr-open-change",ga),window.addEventListener("message",tg)}function tg(e){const t=e.data;if(e.source===null||!Ie(t)||t.type!==Dm||!Ie(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"||ei(`console.${r.level}`,{source:"app",message:r.args.map(n=>ma(n)).join(" ")},r.timestamp,r.level==="log"||r.level==="debug"?"log":r.level)}function ma(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
93
+ `).slice(0,4).join(`
94
+ `):"")||`${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 ga(e){const t=e.detail?.open===!0;t!==kt&&(kt=t,Re+=1,Gr(),et!==void 0&&window.clearInterval(et),et=void 0,t&&(x.mobileLanSelect.addEventListener("change",rg),Ia(),Ft(),de.devContext.source==="remote"&&(et=window.setInterval(()=>{Eg()},Qm))))}function rg(){kt&&Ft()}function pa(){ya("manual restart")}function ya(e){B||tt!==void 0||(re("runtime.restart",{boundary:xe+1}),tt=window.setTimeout(()=>{tt=void 0,B||Bt(e)},0))}async function Bt(e){const t=++xe;if(Ot=void 0,_a(e),Q.runtimeStatus="loading",Ca(Ct),x.device.replaceChildren(),$r){x.device.innerHTML=`
95
+ <div class="browser-mock-preview">
96
+ <span class="browser-mock-preview__icon">UI</span>
97
+ <strong>Browser Mock</strong>
98
+ <small>mp_preview</small>
99
+ </div>`,Q.runtimeStatus="idle";return}const r=document.createElement("iframe");r.dataset.testid="device-iframe",r.title="小程序预览",r.allow="clipboard-read; clipboard-write",r.name=Rm,x.device.appendChild(r);const n=new AbortController;Wn=n;try{const i=await Pf(ig(n.signal,t));if(B||t!==xe){i.dispose();return}Kn=i.dispose;const o=mf({iframe:r,ports:i.ports,environment:i.environment,hostCapabilities:i.hostCapabilities,authPresentation:i.authPresentation,resolveLaunchConfiguration:async()=>(await i.resolveLaunch()).configuration,dispose:i.dispose,onReady:()=>{Q.runtimeStatus="ready",re("runtime.ready",{generation:t})},onStateChange:s=>{re("runtime.state",{generation:t,state:s})},onTrace:s=>og(t,s),onError:s=>{Q.runtimeStatus="error",re("runtime.error",Et(s))},onSecurityViolation:s=>re("runtime.security",Et(s)),onCapabilityTrace:s=>{re(s.method,s),s.method==="storage.setStorage"&&s.outcome==="success"&&zr()}});Be=o,await o.start()}catch(i){if(B||t!==xe||n.signal.aborted)return;Q.runtimeStatus="error",re("runtime.start.failed",Et(i))}}function ng(){re("runtime.ready",{generation:1}),re("user.getInfo",{durationMs:34,outcome:"success"}),re("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function ig(e,t){return{signal:e,account:{async getCurrentUserId(){return(await Jn(!1,e)).user_id},async ensureAuthenticated({signal:r}){await Jn(!1,r)},onChange(r){return Hr.add(r),()=>Hr.delete(r)}},authenticatedRequest:sg,storage:{area:"local",storage:localStorage},presentation:_m({close:async()=>{us(),Be?.destroy(),Q.runtimeStatus="closed"},reload:()=>{!B&&t===xe&&(Ot=t)},pushLog:re,getDeviceMetrics:()=>Ai.value}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:r=>{document.title=r}},resolveLaunch:async()=>({configuration:pm({launchUrl:Zm,runtimePermissions:cm(Ze.runtimePermissions,Ct),...Ze.miniProgramId?{miniProgramId:Ze.miniProgramId}:{},operatingSystem:Ai.value.platform}),hostHints:{launchKind:Ze.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:r=>gm(r)}}}function og(e,t){t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||Ot!==e||e!==xe||(Ot=void 0,ya("navigation.reload"))}async function sg(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.withCredentials!==!0:e.credentials==="omit")&&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 未提供 public origin-session 请求闭包");const i=await Ei(n?zm:Wm,{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&&it.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function Jn(e,t){const r=jr,n=await wa(Ta(yi.signal,t));return Pa(r)?Ea(n,e).status:Zn()}async function wa(e){return await(await fetch(Gm,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Ea(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<It)return{changed:!1,status:Zn()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?G(e.nickname):void 0,i=e.authenticated?G(e.avatar):void 0,o=e.revision!==It||e.authenticated!==Nt||r!==Fe||n!==Yn||i!==Qn;return It=e.revision,Nt=e.authenticated,Fe=r,Yn=n,Qn=i,va(),t&&o&&Hr.forEach(s=>s(Fe)),{changed:o,status:Zn()}}function Zn(){return{authenticated:Nt,revision:It,...Nt&&Fe?{user_id:Fe}:{}}}function ag(){if(!(!de.csrfToken||B))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Ne=Fm({csrfToken:de.csrfToken,onDiagnostic:t=>re("channel.diagnostic",t),url:e.toString()}),Ne.subscribeUpdates((t,r)=>cg(t,r)),Ne.connect()}catch{Ne?.dispose(),Ne=void 0}}function cg(e,t){it.invalidate(e.account.revision),Rg(Ct,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Bt("status changed"):(Ct=Ca(e.permissions),ug())}function ba(){if(er?.close(),er=void 0,!Fe||B)return;const e=new EventSource(Km,{withCredentials:!0});er=e,e.addEventListener("account-invalidated",()=>{it.invalidate()}),e.addEventListener("account-revision",()=>{it.invalidate()}),e.onopen=()=>{Xn.reset()},e.onerror=()=>{e.close(),Xn.schedule()}}async function dg(e){Pa(e)&&await Bt("account revision changed")}function _a(e){Jt+=1,us(),Be?.destroy(),Be=void 0,Wn?.abort(new DOMException(e,"AbortError")),Wn=void 0,Kn?.(),Kn=void 0}async function ug(){B||(await Bt("permission changed"),!B&&await Ft())}async function wi(){const e=await fetch($m,{cache:"no-store",credentials:"same-origin",redirect:"error"});if(!e.ok)throw new Error("Browser Dev Host bootstrap request failed");const t=await e.json();if(!Ie(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=La(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new ot;return{csrfToken:typeof t.csrfToken=="string"?t.csrfToken:void 0,defaultLanAddressId:typeof t.defaultLanAddressId=="string"?t.defaultLanAddressId:void 0,devContext:lg(t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(vg):[],loginAvailable:t.loginAvailable===!0,miniProgram:bg(t.miniProgram),mobileLaunchRedirect:r,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0}}function lg(e,t){return Ie(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}:{source:"anonymous",runtimePermissions:t}}async function Ei(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),de.csrfToken&&r.set("x-hb-sdk-csrf",de.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function Ia(e=x.mobileLanSelect.options.length>0?x.mobileLanSelect.value:void 0){x.mobileLanSelect.replaceChildren();for(const t of ve){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,x.mobileLanSelect.appendChild(r)}e&&ve.some(({id:t})=>t===e)?x.mobileLanSelect.value=e:Xt&&ve.some(({id:t})=>t===Xt)?x.mobileLanSelect.value=Xt:ve[0]&&(x.mobileLanSelect.value=ve[0].id),x.mobileLanSelect.disabled=ve.length===0}async function Ft(){if(B)return;const e=++Re;Gr();const t=Sg();if(!t?.mobileAppQrPayload){x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent="未发现可用的局域网地址";return}x.mobileQrStatus.textContent="正在生成二维码...";try{const r=await pg(t);if(e!==Re||B)return;const n=await hg(r.address,r.expiresAt);if(e!==Re||B)return;const i=await Jf.toDataURL(n.payload,{width:Ym,margin:1});if(e!==Re||B)return;x.mobileQrImage.src=i,x.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,wg(n.expiresAt,e)}catch(r){if(e!==Re||B)return;if(r instanceof ot){Sa();return}x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent=_i(r)}}async function hg(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await fg(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:vm(Sm({host:e.address,port:location.port,token:n.token}))}}catch{throw new ot}}async function fg(e,t){if(Xe?.addressId===e.id)return Xe;if(!Xe)return;const r=await Ei(jm,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:Xe.token})});if(!r.ok)throw new ot;const n=await r.json(),i=Ie(n)?La({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new ot;return Xe=i,i}async function mg(e){const t=await wi(),r=gg(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return Aa(t),{...r,mobileAppQrPayload:n}}function gg(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function Aa(e){fa=bi(e),ve=e.lanAddresses,Xt=e.defaultLanAddressId,Xe=e.mobileLaunchRedirect,Da(Ra(e)),Ia()}class ot extends Error{}async function pg(e){const t=ds.then(()=>yg(e));return ds=t.then(()=>{},()=>{}),t}async function yg(e){const t=new URL(e.appUrl),r=new URL(im,location.origin),n=await Ei(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:dm(Ze.runtimePermissions,Ct)})}),i=await n.json();if(!n.ok||!Ie(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await mg(e.id),expiresAt:i.expires_at}}function wg(e,t){Zt=window.setTimeout(()=>{!B&&kt&&t===Re&&Ft()},Math.max(1e3,e-Date.now()-3e4))}async function Eg(){if(!(kn||B)){kn=!0;try{const e=await wi();if(bi(e)===fa)return;Aa(e),kt&&Ft()}catch(e){e instanceof ot&&Sa()}finally{kn=!1}}}function Sa(){Re+=1,Gr(),x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent="Mobile 短链接配置无效"}function bi(e){return JSON.stringify({defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,nativeAppLaunchUnavailableReason:e.nativeAppLaunchUnavailableReason})}function va(){if(!Nt){Q.account={authenticated:!1,avatar:"",nickname:"未登录"};return}Q.account={authenticated:!0,avatar:Qn??"",nickname:Yn||Fe||"已登录"}}function Ra(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Da(e){if(!!!e?.miniProgramId||!e){Q.miniProgram={bound:!1,iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}Q.miniProgram={bound:!0,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function bg(e){if(e===null)return null;if(!Ie(e))return;const t=G(e.miniProgramId)??G(e.mini_program_id);if(t)return{miniProgramId:t,...G(e.name)?{name:G(e.name)}:{},...G(e.iconUrl)??G(e.icon_url)?{iconUrl:G(e.iconUrl)??G(e.icon_url)}:{},...G(e.status)?{status:G(e.status)}:{},...G(e.version)?{version:G(e.version)}:{},...G(e.developerName)??G(e.developer_name)?{developerName:G(e.developerName)??G(e.developer_name)}:{}}}function G(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function zr(){const e=++Jt,t=Be,r=t?.diagnostics.storage;if(!r){Q.storage=[],Q.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(B||e!==Jt||t!==Be)return;Q.storage=n.map(i=>({area:i.area,key:i.key,serializedValue:i.serializedValue,bytes:i.bytes})),Q.storageError=""}catch(n){if(B||e!==Jt||t!==Be)return;Q.storage=[],Q.storageError=_i(n)}}function _g(e,t){re("host.message",{message:e,status:t})}function Ig(e){B||_g(_i(e),"error")}function re(e,t){ei(e,t)}function Ag(){B||(B=!0,window.removeEventListener("hb-sdk:restart-runtime",pa),window.removeEventListener("hb-sdk:refresh-storage",zr),window.removeEventListener("hb-sdk:qr-open-change",ga),jr+=1,yi.abort(new DOMException("Browser Dev Host disposed","AbortError")),it.dispose(),xe+=1,_a("Browser Dev Host disposed"),er?.close(),Ne?.dispose(),Ne=void 0,Xn.dispose(),Ot=void 0,tt!==void 0&&window.clearTimeout(tt),tt=void 0,Gr(),et!==void 0&&window.clearInterval(et),Hr.clear())}function Gr(){Zt!==void 0&&window.clearTimeout(Zt),Zt=void 0}function Ta(e,t){return t?AbortSignal.any([e,t]):e}function Pa(e){return!B&&e===jr}function Sg(){return ve.find(({id:e})=>e===x.mobileLanSelect.value)}function vg(e){return Ie(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 La(e){if(!(!Ie(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 Ca(e){return{networkRequest:{...e.networkRequest}}}function Rg(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function _i(e){return e instanceof Error&&e.message?e.message:"操作失败"}function Ie(e){return Object.prototype.toString.call(e)==="[object Object]"}function ft(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}