@heybox/hb-sdk 0.8.0-alpha.10 → 0.8.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +15 -9
- package/dist/cli-chunks/{build-aDJbiFqF.cjs → build-Bfm8_lwd.cjs} +5 -5
- package/dist/cli-chunks/{context-Dp36pZ9a.cjs → context-DKpo91h0.cjs} +2 -2
- package/dist/cli-chunks/{create-P3g0ricz.cjs → create-DaBc6N_y.cjs} +1 -1
- package/dist/cli-chunks/{dev-CisJkXuQ.cjs → dev-CQVme_RT.cjs} +17 -10
- package/dist/cli-chunks/{doctor-B-LF5-uj.cjs → doctor-Z28nbVwZ.cjs} +1 -1
- package/dist/cli-chunks/{index-CZGkk7fQ.cjs → index-BTtUJGMf.cjs} +2 -2
- package/dist/cli-chunks/{index-BDaeBI_B.cjs → index-CDyvjYvo.cjs} +15 -15
- package/dist/cli-chunks/{index.esm-NNLG29Tt.cjs → index.esm-D6VfG0x3.cjs} +7 -7
- package/dist/cli-chunks/{login-DTY5GolC.cjs → login-Ccwakey0.cjs} +2 -2
- package/dist/cli-chunks/{project-vite-DlCjHlu_.cjs → project-vite-Cw6AvXNS.cjs} +1 -1
- package/dist/cli-chunks/{remote-BBMr7j8W.cjs → remote-D51eSApF.cjs} +7 -7
- package/dist/cli-chunks/{runtime-gate-BppCl1r3.cjs → runtime-gate-DO9uSLbW.cjs} +1 -1
- package/dist/cli-chunks/{runtime-permission-env-CqsTHeas.cjs → runtime-permission-env-BJp9z8YR.cjs} +1 -1
- package/dist/cli-chunks/{session-CnGeZCRZ.cjs → session-2Y9_qjO5.cjs} +1 -1
- package/dist/cli-chunks/{skill-B0yAnPOJ.cjs → skill-D_ZY0m_b.cjs} +2 -2
- package/dist/cli-chunks/{version-DN5jrixS.cjs → version-DpF1KqoM.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-TzYf9L6C.js +99 -0
- package/dist/devtools/browser-dev-host/assets/{index-Dh9H1JOm.js → index-C5MZZDa5.js} +4 -4
- package/dist/devtools/browser-dev-host/assets/index-P-ra4m1y.css +1 -0
- package/dist/devtools/browser-dev-host/assets/{workbench-state-wHgWRb7I.js → workbench-state-BwV7bm4n.js} +2 -2
- package/dist/devtools/browser-dev-host/index.html +3 -3
- package/dist/index.cjs.js +85 -1
- package/dist/index.esm.js +85 -1
- package/dist/vite.cjs.js +54 -5
- package/dist/vite.esm.js +54 -5
- package/package.json +6 -6
- package/skill/SKILL.md +1 -1
- package/skill/references/api-protocol.md +1 -1
- package/skill/references/api-root.md +41 -13
- package/skill/references/cli.md +2 -2
- package/skill/references/examples.md +3 -3
- package/skill/references/recipes.md +7 -7
- package/skill/references/safety-boundaries.md +7 -1
- package/skill/skill.json +5 -5
- package/types/core/mini-dev-console.d.ts +36 -0
- package/types/vite/index.d.ts +3 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-BhZGUyYw.js +0 -97
- package/dist/devtools/browser-dev-host/assets/index-DJFB5ySU.css +0 -1
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
import{ah as va,aB as Ra,E as Da,an as Ta,ao as Pa,aI as Q,ae as ss,a8 as La,b as Ca}from"./workbench-state-wHgWRb7I.js";const er="auth.login",tr="user.getInfo",rr="user.revokeAuthorization",nr="user.getSteamGameList",ir="share.copyLink",or="share.showShareMenu",sr="share.screenshot",ar="viewport.getWindowInfo",cr="viewport.setNavigationBarStyle",At="storage.getStorage",St="storage.setStorage",dr="network.request",ur="network.download",lr="files.pickFiles",hr="files.pickDirectory",fr="files.saveFile",vt="file.create",Rt="file.remove",mr="file.exists",gr="file.readText",pr="file.writeText",yr="file.readBytes",wr="file.writeBytes",Er="file.stat",br="directory.create",Dt="directory.remove",_r="directory.exists",Ir="directory.list",Ar="ui.showToast",Sr="ui.showLoading",vr="ui.hideLoading",Rr="device.vibrate",Dr="device.setClipboard",Tr="navigation.close",Pr="navigation.reload",Lr="navigation.openAppPage",_e="cloud.leaderboard.submit",ce="cloud.leaderboard.getList",Te="cloud.leaderboard.getCurrentUserEntry",Be="cloud.leaderboard.deleteCurrentUserEntry",fe="cloud.leaderboard.getInfo",Pe=[{method:er,module:"auth",capability:er,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:tr,module:"user",capability:tr,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:rr,module:"user",capability:rr,requirement:{kind:"none"},risk:"high"},{method:nr,module:"user",capability:nr,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:ir,module:"share",capability:ir,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:or,module:"share",capability:or,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:sr,module:"share",capability:sr,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:ar,module:"viewport",capability:ar,requirement:{kind:"none"},risk:"low"},{method:cr,module:"viewport",capability:cr,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:dr,module:"network",capability:dr,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:ur,module:"network",capability:ur,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:lr,module:"files",capability:lr,requirement:{kind:"all",permissions:["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: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:mr,module:"file",capability:mr,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:"directory",capability:br,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dt,module:"directory",capability:Dt,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_r,module:"directory",capability:_r,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ir,module:"directory",capability:Ir,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ar,module:"ui",capability:Ar,requirement:{kind:"none"},risk:"low"},{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:"device",capability:Rr,requirement:{kind:"none"},risk:"low"},{method:Dr,module:"device",capability:Dr,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Tr,module:"navigation",capability:Tr,requirement:{kind:"none"},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:_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:Te,module:"cloud",capability:Te,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Be,module:"cloud",capability:Be,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:fe,module:"cloud",capability:fe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"}],Qe="heybox:miniprogram",as=2,Oa="hb_mini_bridge_nonce",ka="sdk.handshake",Vt="runtime.location.probe",Na="sdk.location.report",Ma="sdk.csp.violation",cs="operation.progress";function Ua(e){return!Ve(e)||e.namespace!==Qe||e.version!==1&&e.version!==2||!Y(e.nonce)?!1:e.type==="handshake"?Y(e.id)&&e.method===ka&&e.error===void 0&&xa(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||Ba(e.error)):e.type==="event"?!Y(e.method)||e.error!==void 0?!1:e.method===cs?e.version===2&&Y(e.id)&&Ha(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 Zn(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function ds(e){return Ve(e)?e.kind==="sandbox"?Fe(e,["kind"]):e.kind==="directory"&&Y(e.handleId)&&Fe(e,["kind","handleId"]):!1}function us(e){return!Ve(e)||e.kind!=="file"?!1:Y(e.handleId)?Fe(e,["kind","handleId"]):ds(e.root)&&Zn(e.relativePath)&&Fe(e,["kind","root","relativePath"])}function ls(e){return!Ve(e)||e.kind!=="directory"?!1:Y(e.handleId)?Fe(e,["kind","handleId"]):ds(e.root)&&Zn(e.relativePath)&&Fe(e,["kind","root","relativePath"])}function Ha(e){return!Ve(e)||!_i(e.loaded)||typeof e.lengthComputable!="boolean"||!Fe(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?_i(e.total)&&e.loaded<=e.total:e.total===void 0}function xa(e){return Ve(e)&&Y(e.href)&&typeof e.userAgent=="string"&&Y(e.sdkVersion)}function Ba(e){return Ve(e)&&Y(e.code)&&typeof e.message=="string"}function _i(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Y(e){return typeof e=="string"&&e.length>0}function Fe(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Hr=["identity","profile"],ei=["userInfo","steamLibrary","share","storage","filesystem","clipboard","leaderboard","network"];new Set(ei);const Fa=new Set(ei);function Va(e){return Fa.has(e)}function xr(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),!Va(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)}Pe.map(e=>e.method);function U(e,t,r){return{code:e,message:t,data:r}}function hs(e){return qa(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?U("RUNTIME_ERROR",e.message):U("UNKNOWN_ERROR","小程序运行时异常",e)}function qa(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}function $a(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const ja=1e3;function za(e,t=$a()){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<=ja}const Ga="runtime.gate.probe",fs=new Set(Pe.map(e=>e.method));class Wa{iframe;nonce;onReady;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;handleMessage;handleUserInteraction;dispatcher;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=as;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.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:Qe,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:Qe,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Qe,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Qe,version:2,nonce:this.nonce,type:"event",id:t,method:cs,payload:r})}onMessage(t){if(!this.started||!this.isTrustedMiniProgramMessage(t))return;const r=t.data;if(r.type==="handshake"){this.handleHandshake(r.payload,r.version,t.origin);return}if(r.type==="request"){let n=!1;try{n=za(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&&Ua(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,n){const i=!this.handshaken;if(i){if(this.onHandshake?.(t)===!1)return;this.bridgeVersion=r,r===1&&this.targetOrigin!=="*"&&n&&n!=="null"&&(this.targetOrigin=n),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.postEvent("ready",{timestamp:Date.now()}),i?this.onReady?.(t):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===Ga){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,U("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!fs.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=hs(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:Qe,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!Ka(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 Ka(e){return typeof e=="string"&&fs.has(e)}const ms="METHOD_FORBIDDEN";function pe(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=ms,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 Ii={[er]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[tr]:["account.getCurrentUserId","account.onChange","network.request"],[rr]:["account.getCurrentUserId","account.onChange","network.request"],[nr]:["account.getCurrentUserId","account.onChange","network.request"],[ir]:["presentation.setClipboard"],[or]:["presentation.showShareMenu"],[sr]:["presentation.getViewportMetrics","presentation.captureAndShare"],[ar]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[cr]:["presentation.setNavigationBarStyle"],[At]:["storage.getRaw"],[St]:["storage.setRaw"],[dr]:["network.request"],[ur]:["network.stream","files.transfer","files.access"],[lr]:["files.external"],[hr]:["files.external"],[fr]:["files.save"],[vt]:["files.access"],[Rt]:["files.removeFile"],[mr]:["files.access"],[gr]:["files.access"],[pr]:["files.access"],[yr]:["files.access"],[wr]:["files.access"],[Er]:["files.access"],[br]:["files.access"],[Dt]:["files.removeDirectory"],[_r]:["files.access"],[Ir]:["files.access"],[Ar]:["presentation.showToast"],[Sr]:["presentation.showLoading"],[vr]:["presentation.hideLoading"],[Rr]:["presentation.vibrate"],[Dr]:["presentation.setClipboard"],[Tr]:["presentation.close"],[Pr]:["presentation.reload"],[Lr]:["presentation.openAppPage"],[_e]:["account.getCurrentUserId","account.onChange","network.request"],[ce]:["account.onChange","network.request"],[Te]:["account.getCurrentUserId","account.onChange","network.request"],[Be]:["account.getCurrentUserId","account.onChange","network.request"],[fe]:["account.onChange","network.request"]};function Ya(e,t){if(t[e]!==!0)throw pe(e)}const Qa=32*1024*1024,Xa=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Ja(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:Qa},i);return Za(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Za(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:ec(t,rc(e,"content-type"))}}function ec(e,t){tc(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||!Xa.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function tc(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 rc(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function L(e){return typeof e=="function"}function Ai(e){return(...t)=>{throw pe(e)}}function K(e){return async(...t)=>{throw pe(e)}}const nc=(e,t)=>{},ic=()=>()=>{};function oc(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):ic},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):Ai("presentation.getViewportMetrics"),getNavigationBarHeight:L(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Ai("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):nc,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 sc(e){const t=ac(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 ac(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 Si(e,t){return t?.[e]!==!1}function cc(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")}function gs(e,t={}){const r={};for(const n of Object.keys(Ii)){const o=Ii[n].every(a=>e[a]),s=!cc(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=Si(n,t.callerCapabilities)&&Si(n,t.hostCapabilities)&&o&&s}return r}function ps(e={},t={}){const r=sc(e),n=gs(r,t);return{ports:oc(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function ti(e,t){if(!t||t===e.signal)return e;const r=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):dc(e.signal,t);return{...e,signal:r}}function dc(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 uc(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 lc(e){return typeof e=="object"&&e!==null}function ne(e,t){const r=e.data;if(!lc(r)||typeof r.status!="string")throw new Error(t);return r}const ys={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},hc={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 fc(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function mc(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=fc(r.consent_challenge)),{...t,result:n}}const gc={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,"小程序授权取消接口响应异常")},pc={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,"小程序授权撤销接口响应异常")},yc={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}}}},wc={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=>mc(e)},Ec={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}}}},bc=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],_c=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Ic=/authorization|cookie|pkey|password|secret|token/i,ws=/authorization|cookie|pkey|token|password|secret/i;function ue(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ac(e){for(const t of Object.keys(e))if(!_c.has(t))throw new q(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of bc)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))Ic.test(n)||(r[n]=pt(i));return r}function vi(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))ws.test(r)||(t[r]=n);return t}function Sc(e){if(!e)return;const t=Object.keys(e).find(r=>ws.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 Es(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,Es(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,Es(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function vc(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:vi(o),method:e.method,metadata:{endpointId:e.id},query:pt(n),timeout:e.timeout,url:r},data:pt(a.data),headers:vi(a.headers)||{},status:a.status,statusText:a.statusText}}async function Br(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(Ac(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;Sc(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=vc(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 Rc=new Set(Hr),Dc=1e3;function Tc(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 Pi(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 Pi(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 kn();return await Nc(Br(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):bs(T)?T:l("REQUEST_FAILED","授权请求失败")}}async function A(m,g){await y(gc,{runtimeContext:{miniProgramId:m},challenge:g}).catch(()=>{})}function v(m){const g=async()=>{const T=Di(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),Pc("REQUEST_FAILED","授权确认界面执行失败",J))}if(await b(T,k),Z.status!=="granted")throw await A(m,g.challenge),l("AUTHORIZATION_CANCELLED","用户取消授权");const se=Oc(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=Di(E),k=setTimeout(()=>T.abort(),Dc);try{const F=kc(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(hc,{mini_program_id:m,...E?{miniprogram_version:E}:{}},g),k=Ge(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(ys,void 0,m),E=Ge(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(wc,{runtimeContext:{miniProgramId:E},scopes:m});await b(T,k);const V=Ge(F,"小程序登录"),Z=Ti(V,"loginCode"),se=Ti(V,"consentChallenge");if(Z===se)throw l("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let J;if(Z)J=Ri(V.loginCode);else{const z=Lc(V.consentChallenge),ye=await P(E,z,g,T,k);await b(T,k);const Gr=await y(Ec,{runtimeContext:{miniProgramId:E},challenge:z.challenge,selectedScopes:ye});if(await b(T,k),J=Ri(Ge(Gr,"小程序登录确认")),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",Kr(i)),J}async function S(m,g){const E=o,T=await y(yc,{runtimeContext:{miniProgramId:g}});await b(m,E);const k=Cc(Ge(T,"用户本地身份"));for(const F of Hr)i.add(F);return h("user_info_authorization_change",Kr(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(pc,{runtimeContext:{miniProgramId:g}});await b(T,E),Ge(k,"用户授权撤销"),d(),h("user_info_authorization_change",{identity:"denied",profile:"denied"})}return{login:C,getOrCreateLocalIdentity:w,getAuthorization:()=>Kr(i),revoke:D,onEvent(m){return t.add(m),()=>t.delete(m)},dispose(){s||(s=!0,d(),u(),t.clear())}}}function Pc(e,t,r){const n=l(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function Ge(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 Ri(e){if(!M(e))throw l("INVALID_RESPONSE","login code 必须是对象");const t=Cr(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 Lc(e){if(!M(e))throw l("INVALID_RESPONSE","授权 challenge 必须是对象");const t=Cr(e.requestedScopes,"challenge requestedScopes"),r=Cr(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 Cc(e){if(!M(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw l("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");return{appUserId:e.appUserId.trim()}}function Oc(e,t){const r=Cr(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 kc(e){const t=Je(e?.name),r=Je(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Di(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 Nc(e,t){return t.aborted?Promise.reject(kn()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(kn()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function kn(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Cr(e,t){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!Rc.has(r))||new Set(e).size!==e.length)throw l("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Kr(e){return Object.fromEntries(Hr.map(t=>[t,e.has(t)?"granted":"not_requested"]))}function Ti(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function bs(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Pi(e,t,r){return t.aborted?l("RUNTIME_DESTROYED","小程序 Runtime 已终止"):bs(e)?e:l("REQUEST_FAILED",r)}const Mc=new Set(Hr);function Uc(e){return{[er]:async(t,r)=>e.authorization.login(Hc(t),r.trustedUserGesture)}}function Hc(e){if(e===void 0)return["identity"];if(!M(e)||Object.keys(e).some(t=>t!=="scopes"))throw Li();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Mc.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Li();return[...e.scopes]}function Li(){return l("INVALID_PARAMS","auth.login 参数不合法")}const xc={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,"排行榜记录删除接口响应异常")}},Bc={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,"当前排行榜记录接口响应异常")}},Fc={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,"排行榜信息接口响应异常")}},Vc={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,"排行榜列表接口响应异常")}},qc={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 Ci(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(Ci(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(Ci(u))))})}const $c="default",jc=/^[A-Za-z0-9_-]{1,64}$/,zc=300*1e3,Gc=250,Wc=3,Kc={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 Yc{constructor(t){this.options=t,this.unsubscribeAccountChange=Xc(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(qc,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=dt(i,_e);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),Yr(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(Vc,{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=>Yr(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(Bc,{miniProgramId:n,...t}),c=dt(a,Te);if(!me(c))throw j(`${Te} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Yr(c.entry,Te)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(xc,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=dt(i,Be);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!me(o)||typeof o.deleted!="boolean")throw j(`${Be} 返回的 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(Fc,{miniProgramId:r,...t}),o=dt(i,fe);if(!me(o)||typeof o.key!="string"||!jc.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>=Gc&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+zc,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>=Wc)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)ki(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){ki(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 Mi(n)?n:Ni()}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??$c)}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 $(()=>Br(n,t,r,{...this.options.operationContext,credentials:"heybox-session"}),this.options.operationContext.signal)}catch(i){throw Mi(i)||Nn(i,"REQUEST_UNSUPPORTED")?i:i instanceof q?ae("REQUEST_UNSUPPORTED","当前 Host 不支持该排行榜请求"):i instanceof nt&&Nn(i.cause,"INVALID_STATE")?i.cause:i instanceof rt&&(i.status===401||i.status===403)?ae("UNAUTHORIZED","当前用户未登录"):i instanceof nt||i instanceof rt?Ni():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 Qc(e){return new Yc(e)}function Xc(e,t){try{return e.onChange(t)}catch(r){if(Nn(r,ms))return()=>{};throw r}}function dt(e,t){if(!me(e)||typeof e.status!="string")throw j(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Jc(e);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw j(`${t} 响应缺少 result`);return e.result}function Yr(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 Jc(e){if(e.status==="login"||e.status==="relogin")throw ae("UNAUTHORIZED",mt(e.msg)||"当前用户未登录");const t=Oi(e.result)??Oi(e),r=mt(t?.user_message)||mt(e.msg)||mt(t?.developer_message)||"排行榜请求失败";throw t?ae(Zc(t),r,{status:e.status,sbe:t}):ae("HEYBOX_API_ERROR",r,{status:e.status})}function Oi(e){return me(e)&&me(e.sbe)?e.sbe:void 0}function Zc(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 Kc[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 ki(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 Nn(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 Ni(){return ae("REQUEST_FAILED","排行榜请求失败")}function Mi(e){return e instanceof Error&&e.name==="AbortError"}const ed=/^[A-Za-z0-9_-]{1,64}$/,Ui=20,td=100,Hi=2048;function rd(e){const t=Qc(e);return{handlers:{[_e]:async n=>t.submit(nd(n)),[ce]:async n=>t.getList(id(n)),[Te]:async n=>t.getCurrentUserEntry(Qr(n,Te)),[Be]:async n=>t.deleteCurrentUserEntry(Qr(n,Be)),[fe]:async n=>t.getInfo(Qr(n,fe))},dispose:()=>t.dispose()}}function nd(e){const t=ri(e,_e,!1);if(ni(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{...ii(t.key,_e),score:t.score,...t.extra===void 0?{}:{extra:od(t.extra)}}}function id(e){if(e===void 0)return{limit:Ui};const t=ri(e,ce,!0);ni(t,["key","limit","cursor"],ce);const r=t.limit===void 0?Ui:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>td)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{...ii(t.key,ce),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Qr(e,t){if(e===void 0)return{};const r=ri(e,t,!0);return ni(r,["key"],t),ii(r.key,t)}function ri(e,t,r){if(e===void 0&&r)return{};if(!_s(e))throw ge("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function ni(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw ge("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function ii(e,t){if(e===void 0)return{};if(typeof e!="string"||!ed.test(e))throw ge("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function od(e){if(!_s(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>Hi)throw ge("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${Hi} 字节`);return e}function _s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ge(e,t){return{code:e,message:t}}const xi=5e3,Bi=1e4;function Ne(e){throw{code:"INVALID_PARAMS",message:e}}function Is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function As(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Ne(`${r} 不支持字段: ${n.join(", ")}`)}function sd(e){if(e===void 0)return{intensity:"light",delay:0};if(!Is(e))return Ne("device.vibrate 参数必须是对象");As(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return Ne("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>xi?Ne(`device.vibrate delay 必须是 0-${xi} 的整数毫秒`):{intensity:r,delay:n}}function ad(e){return Is(e)?(As(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?Ne("device.setClipboard text 必须是非空字符串"):e.text.length>Bi?Ne(`device.setClipboard text 不能超过 ${Bi} 字符`):{text:e.text}):Ne("device.setClipboard 参数必须是对象")}function cd(e){return{[Rr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.vibrate(sd(t),e.operationContext),e.operationContext.signal)},[Dr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.setClipboard(ad(t),e.operationContext),e.operationContext.signal)}}}const dd=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"]),ud={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 oi(e){const t=Ss(e),r=t&&dd.has(t)?l(t,ud[t]??"文件操作失败"):l("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function be(e){try{return e()}catch(t){throw oi(t)}}function Ss(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 vs(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):Mn,remove:o?s=>e.remove(s):Ds,read:s=>e.read(s),write:i?(s,a)=>e.write(s,a):Mn,stat:s=>e.stat(s)})}function Rs(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=>vs(e.file(a),n,{allowRemove:o}),directory:a=>Rs(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Mn,remove:s?(a,c)=>e.remove(a,c):Ds,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Mn(){return Promise.reject(l("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Ds(){return Promise.reject(l("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Fi=1024;class ld{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>Fi)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 qi(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=fd(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.handle.file(i)),n.origin,n.handle.mode).handle;return{ref:r,handle:o,origin:n.origin}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=md(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.handle.directory(i)),n.origin,n.handle.mode,!0).handle;return{ref:r,handle:o,origin:n.origin}}describeFile(t,r){return ji(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,Vi(t.ref,n.handle.name))}if(M(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return qi(n.handle,hd(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.handle.file(n)),t.origin,t.handle.mode);return{ref:Vi(t.ref,n),handle:i.handle,origin:t.origin}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw l("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return be(()=>{ji(t);const i=n??t.mode;return $i(t.mode,i),{handle:vs(t,i,{allowRemove:r==="sandbox"}),origin:r}})}prepareDirectory(t,r,n,i=!1){return be(()=>{yd(t,i);const o=n??t.mode;return $i(t.mode,o),{handle:Rs(t,o,{allowRemove:r==="sandbox"}),origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Fi)throw l("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=gd();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(!pd(t))throw l("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw l("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.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(!Zn(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 Vi(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 hd(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 qi(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function $i(e,t){if(t==="readwrite"&&e!=="readwrite")throw l("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function fd(e){return us(e)||Ts(),e}function md(e){return ls(e)||Ts(),e}function Ts(){throw l("INVALID_PARAMS","文件引用不合法")}function gd(){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 pd(e){return/^[0-9a-f]{32}$/.test(e)}function ji(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 yd(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 zi=1e3,wd=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function Ed(e){const t=r=>ti(e.operationContext,r.signal);return{files:{[lr]:async(r,n)=>{Xr(n);const i=Jr(e.picker),o=bd(r),s=await ee(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[hr]:async(r,n)=>{Xr(n);const i=Jr(e.picker),o=_d(r),s=await ee(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[fr]:async(r,n)=>{Xr(n);const i=Jr(e.picker),o=Id(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);We(o.mode),await ee(()=>o.create(Gi(i),t(n)))},[Rt]:async(r,n)=>{const i=ie(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),We(o.handle.mode),!o.handle.remove)throw pe(Rt);await ee(()=>o.handle.remove(t(n)))},[mr]:async(r,n)=>{const i=ie(r);return Wi(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!M(o)||o.kind!=="file")throw Yi()})},[gr]:async(r,n)=>{const i=ie(r),o=Ki(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 文本")}},[pr]:async(r,n)=>{const i=ie(r,["content"]);typeof i.content!="string"&&oe("content 必须是字符串");const o=e.registry.resolveFile(i.target);We(o.mode),await ee(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[yr]:async(r,n)=>{const i=ie(r),o=await ee(()=>e.registry.resolveFile(i.target).read(t(n)));return Ki(o)},[wr]:async(r,n)=>{const i=ie(r,["content"]),o=e.registry.resolveFile(i.target);We(o.mode),await ee(()=>o.write(Sd(i.content),t(n)))},[Er]:async(r,n)=>{const i=ie(r),o=await ee(()=>e.registry.resolveFile(i.target).stat(t(n)));return vd(o)}},directory:{[br]:async(r,n)=>{const i=ie(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);We(o.mode),await ee(()=>o.create(Gi(i),t(n)))},[Dt]:async(r,n)=>{const i=ie(r,["recursive"]),o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),We(o.handle.mode),!o.handle.remove)throw pe(Dt);await ee(()=>o.handle.remove({recursive:i.recursive===void 0?!1:Or(i.recursive,"recursive")},t(n)))},[_r]:async(r,n)=>{const i=ie(r);return Wi(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!M(o)||o.kind!=="directory")throw Yi()})},[Ir]:async(r,n)=>{const i=ie(r,["limit"]),o=Ad(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 bd(e){if(e===void 0)return{mode:"read",multiple:!1};M(e)||oe("pickFiles 参数必须是对象"),Fr(e,["mode","accept","multiple"]);const t=Ps(e.mode,"read"),r=e.multiple===void 0?!1:Or(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 _d(e){return e===void 0?{mode:"read"}:(M(e)||oe("pickDirectory 参数必须是对象"),Fr(e,["mode"]),{mode:Ps(e.mode,"read")})}function Id(e){return M(e)||oe("saveFile 参数必须是对象"),Fr(e,["suggestedName"]),{suggestedName:Ht(e.suggestedName,"suggestedName")}}function ie(e,t=[]){return(!M(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&oe("文件操作参数必须包含 target"),Fr(e,["target",...t]),e}function Gi(e){return{recursive:e.recursive===void 0?!1:Or(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Or(e.exclusive,"exclusive")}}function Ps(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&oe("mode 必须是 read 或 readwrite"),e)}function Or(e,t){return typeof e!="boolean"&&oe(`${t} 必须是布尔值`),e}function Ad(e){if(e===void 0)return zi;if((!Number.isSafeInteger(e)||e<=0)&&oe("limit 必须是正整数"),e>zi)throw l("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Fr(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&oe(`不支持字段: ${r.join(", ")}`)}function We(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Xr(e){if(!e.trustedUserGesture)throw l("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Jr(e){if(!e)throw pe("files.external");return e}async function Wi(e){try{return await e(),!0}catch(t){if(wd.has(Ss(t)??""))return!1;throw oi(t)}}async function ee(e){try{return await e()}catch(t){throw oi(t)}}function Sd(e){return e instanceof Uint8Array||oe("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&oe("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Ki(e){if(!(e instanceof Uint8Array))throw l("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Yi(){return l("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function vd(e){if(!M(e)||e.kind!=="file"||!Rd(e.size))throw l("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Dd(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 Rd(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Dd(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function oe(e){throw l("INVALID_PARAMS",e)}const Td=["pc","console","mobile"],Pd=["game","wiki"];function kr(e){throw{code:"INVALID_PARAMS",message:e}}function Ld(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Me(e,t){return typeof e!="string"||!e.trim()?kr(t):e.trim()}function Qi(e,t,r){return typeof e!="string"||!t.includes(e)?kr(r):e}function Cd(e){const t={target:"game_detail",appId:Me(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Qi(e.gameType,Td,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Qi(e.page,Pd,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Me(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Me(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Od(e){return{target:"user_detail",userId:Me(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function kd(e){const t={target:"post_detail",linkId:Me(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Me(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Me(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Nd(e){return Ld(e)?e.target==="game_detail"?Cd(e):e.target==="user_detail"?Od(e):e.target==="post_detail"?kd(e):kr("navigation.openAppPage target 不支持"):kr("navigation.openAppPage options 必须是对象")}function Md(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 Ud(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Hd(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 xd(e){const t=Nd(e);return t.target==="game_detail"?Md(t):t.target==="user_detail"?Ud(t):Hd(t)}function Bd(e){throw{code:"INVALID_PARAMS",message:e}}function Xi(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Bd(`${t} 不支持参数`)}function Fd(e){return{[Tr]:async t=>{W(e.operationContext.signal),Xi(t,"navigation.close"),await $(()=>e.presentation.close(e.operationContext),e.operationContext.signal)},[Pr]:async t=>{W(e.operationContext.signal),Xi(t,"navigation.reload"),await $(()=>e.presentation.reload(e.operationContext),e.operationContext.signal)},[Lr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.openAppPage(xd(t),e.operationContext),e.operationContext.signal)}}}const Vd=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),qd=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),$d=new Set(["range","if-range","a-im"]),jd=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"]),zd=/^(?: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 Gd{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 Os()}normalizeHostError(t,r){return this.throwIfCancelled(),si(t,r,this.signal)}}async function Wd(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw pe("network.download");const o=ti(r.operationContext,t.signal),s=new Gd(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Xd(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=Zd(c);eu(c,d);const h=tu(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=Jd(e,a,d,i);let f=0;const _=Yd(h.expectedBytes,e.maxBytes);en(t,Zr(0,h));const b={...o,onProgress(A){!Number.isSafeInteger(A)||A<f||_!==void 0&&A>_||(f=A,en(t,Zr(f,h)))}};s.transition("transfer"),u=!0;let I;try{I=await n.files.writeResource(p.handle,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=Kd(I,h,f,e.maxBytes),en(t,Zr(f,h));const y=i.describeFile(p.handle,p.ref);return s.transition("completed"),y}finally{u||Qd(n.network,c.body)}}function Kd(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 Yd(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Qd(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Xd(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Un(i.handle.mode),await cu(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Un(n.handle.mode),await du(n.handle,r),{kind:"directory",...n}}function Jd(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,mode:"replace-existing"};const i=nu(e,r),o=n.deriveFile(t,i);return Un(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Zd(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()||!Vd.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 eu(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:au(t,qd)});if((t["content-range"]?.length??0)>0)throw l("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function tu(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=ru(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 ru(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Zr(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function en(e,t){try{e.postProgress(t)}catch{}}function nu(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=iu(i);if(o&&Yt(o))return o}for(const i of r){const o=ou(i);if(o&&Yt(o))return o}if(e.suggestedName!==void 0)return Ls(e.suggestedName);const n=su(e.url);return n&&Yt(n)?n:"download.bin"}function iu(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 ou(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 su(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Ls(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)||zd.test(e))}function au(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function cu(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Cs()}catch(r){throw si(r,"file",t.signal)}}async function du(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Cs()}catch(r){throw si(r,"file",t.signal)}}function Un(e){if(e!=="readwrite")throw l("FILE_ACCESS_DENIED","下载目标只允许读取")}const uu={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 si(e,t,r){if(r.aborted)return Os();const n=lu(e);if(n&&jd.has(n)){const o=l(n,uu[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 lu(e){return M(e)&&typeof e.code=="string"?e.code:void 0}function Cs(){return l("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Os(){return l("DOWNLOAD_CANCELLED","下载已取消")}function hu(e){if(!e)return;const t=Object.keys(e).find(r=>$d.has(r.trim().toLowerCase()));if(t)throw l("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const fu=4,mu=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],gu=["/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 pu(e,t){const r=yu(e);return r===null||Ji(r,mu)?!0:t&&Ji(r,gu)}function yu(e){let t=e;for(let r=0;r<fu;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Zi(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Zi(t)}function Ji(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Zi(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}const wu=new Set(["url","method","params","data","headers","timeout","withCredentials"]),Eu=new Set(["url","to","params","headers","timeout","withCredentials","suggestedName","overwrite","maxBytes"]),bu=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),eo=3e4,to=2*1024*1024,_u=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Iu=new Set(["authorization","connection","content-length","cookie","host","origin","proxy-authorization","referer","set-cookie","transfer-encoding","user-agent"]),Au=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Su="network.request 不支持 multipart/form-data,请使用专用上传能力";function vu(e){const t=Ru(e.runtimePermissions),r=Fu(e.allowedHttpOrigins);return{[ur]:async(n,i)=>{const o=Tu(n,{permission:t,allowedHttpOrigins:r});return Wd(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[dr]:async(n,i)=>{const o=ti(e.operationContext,i?.signal);W(o.signal);const s=Du(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await $(()=>e.network.request(s,o),o.signal)}catch(c){throw ju(c)?c:zu(c,"REQUEST_UNSUPPORTED")?N("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):N("REQUEST_FAILED","网络请求失败")}return $u(a)}}}function Ru(e){const t=xr(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Du(e,t){const r=Vr(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!wu.has(c));if(n.length>0)throw N("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);const i=ks(r,t,"network.request"),o=Lu(r.method),s=r.data;s!==void 0&&Nu(s),Uu(i.headers,s);const a=Hu(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 Tu(e,t){const r=Vr(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!Eu.has(c));if(n.length>0)throw N("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);const i=ks(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw N("INVALID_PARAMS","network.download timeout 必须是有限正数");hu(i.headers);const o=us(r.to),s=ls(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=Ls(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 ks(e,t,r){const n=Pu(e.url,t.allowedHttpOrigins,r),i=qu(n);if(i&&!t.permission.useOfficialDomain)throw N("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(pu(n.pathname,i))throw N("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,withCredentials:ku(e.withCredentials,`${r} withCredentials 必须是布尔值`),params:e.params===void 0?void 0:{...Vr(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Cu(e.headers,r),timeout:Ou(e.timeout,r)}}function Pu(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 Lu(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(!bu.has(t))throw N("INVALID_PARAMS","network.request method 不合法");return t}function Cu(e,t="network.request"){const r=Vr(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(Iu.has(s)||s.startsWith("x-heybox-")||s.startsWith("x-xhh-"))throw N("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[i]=o}return n}function Ou(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>eo)throw N("INVALID_PARAMS",`${t} timeout 不能超过 ${eo}ms`);return e}}function ku(e,t){if(e!==void 0){if(typeof e!="boolean")throw N("INVALID_PARAMS",t);return e}}function Nu(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(Mu(e)>to)throw N("INVALID_PARAMS",`network.request data 不能超过 ${to} 字节`)}function Mu(e){if(typeof e=="string")return tn(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return tn(e.toString());try{const t=JSON.stringify(e);return t?tn(t):0}catch{throw N("INVALID_PARAMS","network.request data 必须可序列化")}}function Uu(e,t){const r=Ns(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",Su)}function Hu(e,t,r){if(t===void 0)return;const n=Ns(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)||Bu(t))?"form":xu(t)?"json":void 0}function Ns(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function xu(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function Bu(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Fu(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&&Vu(n.hostname)&&t.add(n.origin)}catch{}return t}function Vu(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 qu(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return _u.some(r=>t===r||t.endsWith(`.${r}`))}function $u(e){return Object.keys(e.headers).some(ro)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!ro(t)))}:e}function ro(e){const t=e.trim().toLowerCase();return Au.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function ju(e){return e instanceof Error&&e.name==="AbortError"}function zu(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Vr(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw N("INVALID_PARAMS",t);return e}function tn(e){return new TextEncoder().encode(e).length}function N(e,t){return{code:e,message:t}}const jt=4294967296;function Gu(e){const t=new Wu;return t.write(e),t.finish()}class Wu{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=Ku(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 Ku(e){const t=new Uint8Array(Yu(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 Yu(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 Qu(e){Hn(e);const t=Gu(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 Hn(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)Hn(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)Hn(o,t+1,r);r.delete(e)}function Xu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ju(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 Zu(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=Ju(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function el(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 Ms(e,t){if(e==null)return{};if(!Xu(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=Zu(e.topicIds),n=el(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 tl(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function rl(e){try{if(tl(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 xn(e,t){return typeof e!="string"||!e.trim()?X(t):e}function nl(e,t){const r=xn(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?X(t):r}catch{return X(t)}}function il(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Us(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 ol(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&&!il(r))return X("share.showShareMenu channel 不合法");const n=Hs(e.extra,"share.showShareMenu");return{title:xn(e.title,"share.showShareMenu title 必须是非空字符串"),description:xn(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Us(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:nl(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Hs(e,t){if(e!==void 0)try{return Qu(e)}catch{return X(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function xs(e,t){return e.invalidMessage&&await $(()=>rl(t.environment),t.operationContext.signal)?X(e.invalidMessage):e.post}function no(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function sl(e){const t=e.getViewportMetrics();return{left:0,top:0,width:no(t.windowWidth,0),height:no(t.windowHeight,0)}}function Bn(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?X(t):r}function io(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?X(t):r}function al(e){return xt(e)?{left:Bn(e.left,"share.screenshot rect.left 必须是非负数字"),top:Bn(e.top,"share.screenshot rect.top 必须是非负数字"),width:io(e.width,"share.screenshot rect.width 必须是正数"),height:io(e.height,"share.screenshot rect.height 必须是正数")}:X("share.screenshot rect 必须是对象")}function cl(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?sl(t):al(r.rect),...r.delay===void 0?{}:{delay:Bn(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function dl(e,t){W(t.operationContext.signal);const r=ol(e,t);let n=Ms(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await xs(n,t);return $(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function ul(e,t){if(W(t.operationContext.signal),e!==void 0&&!xt(e))return X("share.copyLink 参数必须是对象");const r=Hs(e?.extra,"share.copyLink"),n=Us(t,"share.copyLink",r);return await $(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function ll(e,t){W(t.operationContext.signal);const r=cl(e,t.presentation),n=Ms(xt(e)?e.post:void 0,{method:"share.screenshot"}),i=await xs(n,t),o=t.identity.get()?.miniProgramId.trim()||void 0,s=hl();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 fl(t.presentation,s,t.operationContext.signal):void 0;if(c.status==="rejected")throw c.error;if(u)throw u;return c.value}function hl(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function fl(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 ml(e){return{[ir]:(t,r)=>ul(t,e),[or]:(t,r)=>dl(t,e),[sr]:(t,r)=>ll(t,e)}}const gl=128,pl=/^[A-Za-z0-9_-]+$/;function yl(e){const t=wl(e),r={[At]:async n=>{W(e.operationContext.signal);const i=oo(n,At,e.storageLimits?.maxKeyLength),o=await $(()=>e.storage.getRaw(rn(t(),i),e.operationContext),e.operationContext.signal);return{data:so(o)}},[St]:async n=>{W(e.operationContext.signal);const i=Bs(n,"storage.setStorage 参数必须是对象"),o=oo(i,St,e.storageLimits?.maxKeyLength),s=El(i.data,e.storageLimits?.maxValueBytes);await $(()=>e.storage.setRaw(rn(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 Le("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用")}const i=rn(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:so(a),serializedValue:a,bytes:Fs(a)}}).sort((s,a)=>s.key.localeCompare(a.key))}}}:{handlers:r}}function wl(e){let t=!1,r;return()=>{if(!t){const n=e.identity.get()?.miniProgramId.trim();if(n)r=`id_${ao(n)}`;else{const i=e.anonymousStorageScope?.trim();i&&(r=`anon_${ao(i)}`)}t=r!==void 0}if(!r)throw Le("INVALID_STATE","storage scope 只能在 canonical identity 绑定后使用");return r}}function rn(e,t){return`hb_miniprogram_${e}_${t}`}function oo(e,t,r=gl){const i=Bs(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Le("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!pl.test(i))throw Le("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function El(e,t){let r;try{r=JSON.stringify(e)}catch{throw Le("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw Le("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Fs(r)>t)throw Le("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function so(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Bs(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Le("INVALID_PARAMS",t);return e}function ao(e){return/^[A-Za-z0-9_-]{1,64}$/.test(e)?e:bl(e)}function bl(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 Fs(e){return new TextEncoder().encode(e).length}function Le(e,t){return{code:e,message:t}}const co=120;function Re(e){throw{code:"INVALID_PARAMS",message:e}}function ai(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vs(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Re(`${r} 不支持字段: ${n.join(", ")}`)}function _l(e){if(!ai(e))return Re("ui.showToast 参数必须是对象");if(Vs(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Re("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>co)return Re(`ui.showToast message 不能超过 ${co} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Re("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function Il(e){return e===void 0?{dismissible:!1}:ai(e)?(Vs(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Re("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Re("ui.showLoading 参数必须是对象")}function Al(e){e!==void 0&&(!ai(e)||Object.keys(e).length)&&Re("ui.hideLoading 不支持参数")}function Sl(e){return{[Ar]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.showToast(_l(t),e.operationContext),e.operationContext.signal)},[Sr]:async t=>{W(e.operationContext.signal),await $(()=>e.presentation.showLoading(Il(t),e.operationContext),e.operationContext.signal)},[vr]:async t=>{W(e.operationContext.signal),Al(t),await $(()=>e.presentation.hideLoading(e.operationContext),e.operationContext.signal)}}}const vl={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return ne(e,"当前用户首页资料接口响应异常")}},Rl=3e4;function Dl(e,t,r={}){const n=r.ttlMs??Rl;let i=0,o,s;async function a(){let u;try{u=await Br(e,vl,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):Pl(d)?d:l("REQUEST_FAILED","user home_v2 请求失败")}return Tl(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 Tl(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 Pl(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}const Ll={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 游戏库接口响应异常")}},qs=20,Cl=100,$s=0,js="weeks",Ol=100,kl=new Set(["weeks","all","achieved"]);function Nl(e){const t=Dl(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 已终止"):lo(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 Br(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):lo(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(ys,void 0).then(A=>{const v=uo(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=Ml(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=ci(v.steam_id_info);if(Object.keys(P).length===0)return{isLogin:!0,isBound:!1,data:null};const H=await h(Ll,{userId:A,...I,personalInformationOpen:zs(P.personal_infomation_open??P.personal_information_open)});await d(A,y);const R=uo(H,"Steam 游戏库");return{isLogin:!0,isBound:!0,data:Fl(R,I)}}return{getInfo:p,getSteamGameList:_,dispose(){i||(i=!0,n+=1,o(),s(),t.clear(),r.clear())}}}function Ml(e){if(e==null)return{limit:qs,offset:$s,sort:js,includeHidden:!1};if(!M(e))throw De("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw De(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Ul(e.limit),offset:Hl(e.offset),sort:xl(e.sort),includeHidden:Bl(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim())throw De("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw De("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Ol))}return r}function Ul(e){if(e===void 0)return qs;if(!Number.isInteger(e)||Number(e)<1)throw De("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Cl)}function Hl(e){if(e===void 0)return $s;if(!Number.isInteger(e)||Number(e)<0)throw De("user.getSteamGameList offset 必须是非负整数");return Number(e)}function xl(e){if(e===void 0)return js;if(typeof e!="string"||!kl.has(e))throw De("user.getSteamGameList sort 不支持");return e}function Bl(e){if(e===void 0)return!1;if(typeof e!="boolean")throw De("user.getSteamGameList includeHidden 必须是 boolean");return e}function Fl(e,t){if(!Array.isArray(e.game_list))throw l("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(Vl).filter(a=>a!==void 0),n=Nr(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=zs(e.is_me);return s!==void 0&&(o.isMe=s),o}function Vl(e){const t=ci(e),r=Nr(t.appid),n=Nr(t.steam_appid)??r,i=di(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=$l(t.external_tags??t.tags);s.length&&(o.tags=s);const a=ql(t.price);return a&&(o.price=a),o}function ql(e){const t=ci(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 uo(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 ci(e){return M(e)?e:{}}function di(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function $l(e){return Array.isArray(e)?e.map(di).filter(Boolean):[]}function Nr(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function zs(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=di(r);n&&Object.assign(e,{[t]:n})}function wt(e,t,r){const n=Nr(r);n!==void 0&&Object.assign(e,{[t]:n})}function De(e){return l("INVALID_PARAMS",e)}function lo(e){return M(e)&&typeof e.code=="string"&&typeof e.message=="string"}function jl(e){return{[tr]:async t=>(ho(t,"user.getInfo"),e.user.getInfo()),[rr]:async(t,r)=>{ho(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[nr]:async t=>e.user.getSteamGameList(t)}}function ho(e,t){if(e!==void 0)throw l("INVALID_PARAMS",`${t} 不接收入参`)}function fo(e){throw{code:"INVALID_PARAMS",message:e}}function lt(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Gs(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function zt(e,t,r){return Math.min(Gs(e,t),r)}async function zl(e){try{return Gs(await e.getNavigationBarHeight(),0)}catch{return 0}}function Gl(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 Wl(e){const t=e.getViewportMetrics(),r=lt(t.windowWidth,0),n=lt(t.windowHeight,0),i=await zl(e);return{pixelRatio:lt(t.pixelRatio,1),screenWidth:lt(t.screenWidth,r),screenHeight:lt(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:Gl(t,r,n,i),screenTop:i}}function Kl(e){return{[ar]:async()=>(W(e.operationContext.signal),Wl(e.presentation)),[cr]:async t=>{if(W(e.operationContext.signal),typeof t!="object"||t===null||Array.isArray(t))return fo("viewport.setNavigationBarStyle 参数必须是对象");const r=t.foregroundStyle;if(r!=="light"&&r!=="dark")return fo("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await $(()=>e.presentation.setNavigationBarStyle(r,e.operationContext),e.operationContext.signal)}}}const Yl=new Map(Pe.map(e=>[e.method,e]));function nn(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function Ql(e){const t=xr(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 Xl(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 Jl(e){const t=Ql(e.runtimePermissions);let r=0;return{async dispatch(n,i,o){const s=e.now??Zl,a=e.onTrace?s():0,c=e.onTrace?`cap_${++r}`:"";try{if(e.terminalSignal.aborted)throw nn("RUNTIME_DESTROYED","小程序 Runtime 已终止");Ya(n,e.effectiveCapabilities);const u=Yl.get(n);if(!u)throw new Error(`Capability method ${n} 缺少 protocol metadata`);const d=t(u);if(!d.allowed)throw nn(d.code,d.message,d.data);const h=e.handlers[n];if(!h)throw new Error(`Capability method ${n} 缺少 handler`);const p=await Xl(async()=>{for(const f of e.policies??[]){const _=await f.evaluate({method:n,payload:i,capability:u});if(e.terminalSignal.aborted)throw po();if(!_.allowed)throw nn(_.code,_.message,_.data)}if(e.terminalSignal.aborted)throw po();return h(i,o)},void 0,o,e.terminalSignal);return mo(e.onTrace,go(c,n,i,a,p),s),p}catch(u){throw mo(e.onTrace,go(c,n,i,a,{status:"error",error:u}),s),u}}}}function Zl(){return typeof performance>"u"?Date.now():performance.now()}function mo(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 go(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:eh(i.error)}:{},...th(t,r,i)}}function eh(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function th(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"&&rh(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 rh(e){return typeof e=="object"&&e!==null}function po(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function nh(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=new ld(e.files,e.miniProgramDetail),n=Ed({registry:r,picker:e.picker,operationContext:t}),i=Tc({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation});let o,s,a=()=>{};try{o=Nl({account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:i}),a=i.onEvent((f,_)=>e.eventSink.postEvent(f,_)),s=rd({account:e.account,identity:e.identity,network:e.network,operationContext:t});const c=yl({storage:e.storage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits}),u=[{name:"auth",handlers:Uc({authorization:i})},{name:"user",handlers:jl({user:o,authorization:i})},{name:"share",handlers:ml({environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:Kl({operationContext:t,presentation:e.hostPresentation})},{name:"storage",handlers:c.handlers},{name:"network",handlers:vu({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:Sl({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:cd({operationContext:t,presentation:e.hostPresentation})},{name:"navigation",handlers:Fd({operationContext:t,presentation:e.hostPresentation})},{name:"cloud",handlers:s.handlers}],d=ih(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 ih(e){const t=new Map(Pe.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=Pe.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==Pe.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const oh="heybox-mini-dev:";function yo(e){try{return sh(new URL(e))}catch{return!1}}function sh(e){return e.protocol===oh}function ah(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||ch(e)}function ch(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 dh=1,Ws="allow-scripts allow-same-origin",uh="",lh="no-referrer";function hh(e=Ws){return!e.split(/\s+/).includes("allow-same-origin")}function wo(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const fh=new Set(["javascript:","data:","blob:","file:"]),Eo="xiaoheihe.cn";function mh(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(fh.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!Eh(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function gh(e,t){const r=new URL(e);return r.searchParams.set(Oa,t),r.toString()}function ph(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=yh(r)??wh(n.pathname);return i.pathname.startsWith(o)}catch{return!1}}function yh(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function wh(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}function bo(e){const t=new URL(e);return ui(t)?"loopback":li(t)?"lan":"production"}function Eh(e,t,r){return bh(e)||ui(e)||li(e)&&Ih(t,r)}function bh(e){return e.protocol==="https:"&&vh(e.hostname)}function ui(e){return e.protocol==="http:"&&_h(e.hostname)}function _h(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function li(e){return e.protocol==="http:"&&Ah(e.hostname)}function Ih(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return ui(r)||li(r)}catch{return!1}}function Ah(e){const t=Sh(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Sh(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 vh(e){return e===Eo||e.endsWith(`.${Eo}`)}const Rh=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"]),Dh=new Set(["url","inline","eval","unknown"]),Th=/^\/(?:\:segment(?:\/\:segment)*)?$/,Ph=/^[a-f0-9]{64}$/,Lh=255,Ch=160,Oh=256;function kh(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!Rh.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>Oh||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!Dh.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=Nh(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>Ch||!Th.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!Ph.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 Nh(e){if(e!==void 0&&!(typeof e!="string"||e.length>Lh))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Mh=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 Uh(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:Hh(i.pathname),sanitizedPathnameHash:xh(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function Hh(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function xh(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&_)+Mh[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 Bh=/^(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 Fh(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(on(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(on(r,t)<0)throw U("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:on(r,gt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Vh(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=Bh.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 on(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 qh=1e4,sn=2e3,$h=2,jh="open-with-native-credential-policy",Ks="安全提示",Ys="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class zh{nonce=wo();runtimeId=wo();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;constructor(t){this.options=t,this.iframe=t.iframe;const r=ps(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??qh,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:(ef(),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()||(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=Fh(t.sdkVersionPolicy),this.miniProgramDetail=nf(t),this.effectiveCapabilities=gs(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),Yh(this.options.onLaunchConfigurationResolved,t,this.sdkVersionDecision),this.isInactive()))return;this.applyIframeDefaults(),this.startBridgeServer(),this.installSubscriptions();const r=await this.normalizeLaunchUrl(t.launchUrl);if(this.isInactive())return;const n=await this.confirmDevMiniProgramLaunch(r);if(!this.isInactive()){if(!n){await this.closeAfterDevLaunchCancellation();return}this.bridgeServer?.setTargetOrigin(Xh(r)),this.launchUrl=r,this.miniProgramSrc=gh(r,this.nonce),this.traceSecurityPolicy(r),this.setStatus("src_resolved"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"src_resolved"}),this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Ie(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=nh({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=Jl({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}:{}};Ie(this.options.onCapabilityTrace,h)}}:{}});this.bridgeServer=new Wa({iframe:this.iframe,nonce:this.nonce,dispatcher:r,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 Kh(t)?t:Qs(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 mh(t,r,{allowPrivateNetwork:yo(r)||_o(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??Zh)({message:Ys,title:Ks,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(bo(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!yo(r)&&!_o(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{Io(),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(()=>Io())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",uh),this.iframe.setAttribute("referrerpolicy",lh),this.iframe.setAttribute("sandbox",Ws)}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),Ie(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),Ie(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Vh(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>=$h)){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()},sn),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 文档再验证超时")))},sn))}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()},sn))}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===Ma){this.handleCspViolation(t.payload);return}if(t.method!==Na)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"||!ph(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=kh(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){Ie(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=Uh(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:dh,launchUrlType:bo(t),networkPolicy:jh})}failRuntime(t){const r=Gh(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),Ie(this.options.onError,Wh(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,Ie(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Ie(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 Gh(e){const t=hs(e);return Mr(e)&&"cause"in e&&Qs(t,e.cause),t}function Qs(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function Wh(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{}}}function Kh(e){return Mr(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Mr(e){return!!e&&typeof e=="object"}function Ie(e,t){try{e?.(t)}catch{}}function Yh(e,t,r){try{e?.(t,r)}catch{}}function _o(e){try{const t=new URL(e);return t.protocol==="http:"&&ah(t.hostname)}catch{return!1}}function Qh(e){try{return new URL(e).origin}catch{return}}function Xh(e){return hh()?"*":Qh(e)}function Jh(e){return`${Ks}
|
|
2
|
-
|
|
3
|
-
${Ys}
|
|
4
|
-
|
|
5
|
-
URL: ${e}`}function Zh(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(Jh(e.url))}function Io(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function ef(){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:as,knownMethodCount:Pe.length,supportsFileCreate:Pe.some(i=>i.method===vt),system:tf(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:Ke(e?.hardwareConcurrency),maxTouchPoints:Ke(e?.maxTouchPoints),screen:{width:Ke(t?.width),height:Ke(t?.height)},viewport:{width:Ke(r?.innerWidth),height:Ke(r?.innerHeight),devicePixelRatio:rf(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function tf(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 Ke(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function rf(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function nf(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 of(e){if(!Mr(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!Mr(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 zh(e)}const sf=/^(?: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 af(e,t,r){return Ja({mode:"request-only",request:(n,i={signal:t.signal})=>t.run(i.signal,async o=>{const s={...i,signal:o},a=uf(n),c=n.source==="public-sdk"&&n.withCredentials===!0?await cf(a,e,r(),s):await e.authenticatedRequest(a,s);return lf(c)})}).network}function cf(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,df(e.target.url,r),n)}function df(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 uf(e){const t=Xs(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function lf(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:Xs(e.headers)??{}}}function Xs(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!hf(t)))}function hf(e){const t=e.trim().toLowerCase();return sf.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function ff(e,t,r,n){const i=wf(e.presentation,t);return{account:pf(e,t,r),network:af(e,t,n),...e.storage===void 0?{}:{storage:yf(e,t)},...e.storage===void 0?{}:mf(e,t),...i===void 0?{}:{presentation:i}}}function mf(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 gf(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 pf(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 yf(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 wf(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)=>uc(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 Ef(){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 bf(e){const t=Ef(),r=new Set;let n=!1;const i=p=>{if(n||t.signal.aborted)return an(p),()=>{};let f=!0;const _=()=>{f&&(f=!1,r.delete(_),an(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&&an(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);let a;const c=ff(e,t,i,()=>a),u=ps(c,{hostCapabilities:e.hostCapabilities}),d=gf(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:_f(e.authPresentation,t)},hostCapabilities:u.effectiveCapabilities,dispose:s}}function an(e){try{e()}catch{}}function _f(e,t){return{confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}var Ye={},cn,Ao;function If(){return Ao||(Ao=1,cn=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),cn}var dn={},Ae={},So;function qe(){if(So)return Ae;So=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 Ae.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},Ae.getSymbolTotalCodewords=function(n){return t[n]},Ae.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Ae.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Ae.isKanjiModeEnabled=function(){return typeof e<"u"},Ae.toSJIS=function(n){return e(n)},Ae}var un={},vo;function hi(){return vo||(vo=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}}})(un)),un}var ln,Ro;function Af(){if(Ro)return ln;Ro=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++}},ln=e,ln}var hn,Do;function Sf(){if(Do)return hn;Do=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]},hn=e,hn}var fn={},To;function vf(){return To||(To=1,(function(e){const t=qe().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}})(fn)),fn}var mn={},Po;function Rf(){if(Po)return mn;Po=1;const e=qe().getSymbolSize,t=7;return mn.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},mn}var gn={},Lo;function Df(){return Lo||(Lo=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}})(gn)),gn}var Wt={},Co;function Js(){if(Co)return Wt;Co=1;const e=hi(),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 pn={},ht={},Oo;function Tf(){if(Oo)return ht;Oo=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 ko;function Pf(){return ko||(ko=1,(function(e){const t=Tf();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}})(pn)),pn}var yn,No;function Lf(){if(No)return yn;No=1;const e=Pf();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},yn=t,yn}var wn={},En={},bn={},Mo;function Zs(){return Mo||(Mo=1,bn.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),bn}var he={},Uo;function ea(){if(Uo)return he;Uo=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 Ho;function $e(){return Ho||(Ho=1,(function(e){const t=Zs(),r=ea();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}}})(En)),En}var xo;function Cf(){return xo||(xo=1,(function(e){const t=qe(),r=Js(),n=hi(),i=$e(),o=Zs(),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|_}})(wn)),wn}var _n={},Bo;function Of(){if(Bo)return _n;Bo=1;const e=qe(),t=1335,r=21522,n=e.getBCHDigit(t);return _n.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},_n}var In={},An,Fo;function kf(){if(Fo)return An;Fo=1;const e=$e();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))},An=t,An}var Sn,Vo;function Nf(){if(Vo)return Sn;Vo=1;const e=$e(),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)},Sn=r,Sn}var vn,qo;function Mf(){if(qo)return vn;qo=1;const e=$e();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)},vn=t,vn}var Rn,$o;function Uf(){if($o)return Rn;$o=1;const e=$e(),t=qe();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)}},Rn=r,Rn}var Dn={exports:{}},jo;function Hf(){return jo||(jo=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})(Dn)),Dn.exports}var zo;function xf(){return zo||(zo=1,(function(e){const t=$e(),r=kf(),n=Nf(),i=Mf(),o=Uf(),s=ea(),a=qe(),c=Hf();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()))}})(In)),In}var Go;function Bf(){if(Go)return dn;Go=1;const e=qe(),t=hi(),r=Af(),n=Sf(),i=vf(),o=Rf(),s=Df(),a=Js(),c=Lf(),u=Cf(),d=Of(),h=$e(),p=xf();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 Gr=new Uint8Array(R.buffer);for(let ze=0;ze<m;ze++){const Wr=ze<E?k:F;J[ze]=Gr.slice(se,se+Wr),z[ze]=Z.encode(J[ze]),se+=Wr,ye=Math.max(ye,Wr)}const at=new Uint8Array(S);let bi=0,we,Ee;for(we=0;we<ye;we++)for(Ee=0;Ee<m;Ee++)we<J[Ee].length&&(at[bi++]=J[Ee][we]);for(we=0;we<V;we++)for(Ee=0;Ee<m;Ee++)at[bi++]=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 dn.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)},dn}var Tn={},Pn={},Wo;function ta(){return Wo||(Wo=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}}})(Pn)),Pn}var Ko;function Ff(){return Ko||(Ko=1,(function(e){const t=ta();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)}})(Tn)),Tn}var Ln={},Yo;function Vf(){if(Yo)return Ln;Yo=1;const e=ta();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 Ln.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},Ln}var Qo;function qf(){if(Qo)return Ye;Qo=1;const e=If(),t=Bf(),r=Ff(),n=Vf();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 Ye.create=t.create,Ye.toCanvas=i.bind(null,r.render),Ye.toDataURL=i.bind(null,r.renderToDataURL),Ye.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),Ye}var $f=qf();const Pt=500,jf=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"]),zf=/(authorization|cookie|password|passwd|secret|token|pkey|private[_-]?key|access[_-]?key|client[_-]?secret|api[_-]?key|apikey|session|jwt|refresh[_-]?token|csrf)/i;function Xo(e){if(!e)return e;try{const t=new URL(e);if(t.username="",t.password="",Jo(t.searchParams),t.hash&&t.hash.length>1){const r=t.hash.slice(1);if(r.includes("=")){const n=new URLSearchParams(r);Jo(n)&&(t.hash=n.toString())}}return t.toString()}catch{return na(e)}}function Gf(e){return e?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Wf(t)?"[redacted]":r])):{}}function Fn(e){if(e!==void 0){if(typeof e=="string")return ra(e);if(typeof e=="number"||typeof e=="boolean"||e===null)return e;try{const t=Vn(e),r=JSON.stringify(t);return r===void 0?"[unserializable]":r.length<=Pt?t:fi(r,Pt)}catch{return"[unserializable]"}}}function Et(e){return Array.isArray(e)?e.slice(0,20).map(t=>Et(t)):typeof e=="string"?Kf(e)?Xo(e):ra(e):typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?e:qn(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>{const n=t.trim().toLowerCase();return st(t)?[t,"[redacted]"]:n==="headers"&&qn(r)?[t,Gf(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,Xo(r)]:[t,Et(r)]})):Fn(e)}function Wf(e){const t=e.trim().toLowerCase();return jf.has(t)||st(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function st(e){return zf.test(e.trim())}function ra(e){const t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return Fn(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 Fn(n)}}catch{}return fi(na(e),Pt)}function Vn(e){return Array.isArray(e)?e.slice(0,20).map(t=>Vn(t)):qn(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,st(t)?"[redacted]":Vn(r)])):typeof e=="string"?fi(e,Pt):e}function Jo(e){let t=!1;for(const r of[...e.keys()])st(r)&&(e.set(r,"[redacted]"),t=!0);return t}function na(e){return e.replace(/([?&#]|^|[?&])([^=&#\s]+)=([^&#\s]*)/g,(t,r,n,i)=>st(n)?`${r}${n}=[redacted]`:t)}function Kf(e){return/^https?:\/\//i.test(e.trim())||/^[a-z][a-z0-9+.-]*:\/\//i.test(e.trim())}function fi(e,t){return e.length<=t?e:`${e.slice(0,t)}…(truncated, total=${e.length})`}function qn(e){return Object.prototype.toString.call(e)==="[object Object]"}const Yf="/__hb_sdk__/dev-context";function Qf(e){if(!$n(e)||!Zo(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!$n(t)||!Zo(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const Xf={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Jf(e){const t=xr(e.runtimePermissions),r=t.permissions.network;return t.valid&&r?{networkRequest:{status:r.status,useOfficialDomain:r.config.useOfficialDomain===!0}}:tm()}function Zf(e,t){return ia(e,t,t.networkRequest.useOfficialDomain)}function em(e,t){return ia(e,t,!1)}function tm(){return{networkRequest:{...Xf.networkRequest}}}function ia(e,t,r){const n=xr(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of ei){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=$n(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 $n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Zo(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function rm(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 nm(e){return rm({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 im(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 om={identity:"小程序身份",profile:"昵称和头像"};function sm(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">${Cn(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
|
|
17
|
-
<ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(a=>`<li>${Cn(om[a]||a)}</li>`).join("")}</ul>
|
|
18
|
-
${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${Cn(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 Cn(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function am(e){return{launchUrl:e.launchUrl,sdkVersionPolicy:{minimumSdkVersion:"0.5.0",releaseChannel:"development"},runtimePermissions:e.runtimePermissions,...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const es="hb-sdk-action-dialog-style";function mi(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}lm();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>${ts(e.title)}</h2>
|
|
27
|
-
<pre class="hb-sdk-action-dialog__detail">${ts(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 cm(e,t){await mi({title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+Lt(e.params)].join(`
|
|
33
|
-
`),signal:t.signal})}async function dm(e,t){await mi({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 um(e,t){await mi({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 ts(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function lm(){if(document.getElementById(es))return;const e=document.createElement("style");e.id=es,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 hm(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 Pa({message:t,status:r})},showLoading:Ta,hideLoading:Da,vibrate:Ra,openAppPage:cm,showShareMenu:dm,captureAndShare:um,setScreenshotChromeHidden:va}}const fm=/^[A-Za-z0-9_-]{22}$/,mm="https://api.xiaoheihe.cn/open_inapp/";function gm(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(!fm.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 pm(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`${mm}#${r}`}const jn=1,rs=64*1024,ym=64,wm=/^[A-Za-z0-9_-]{22}$/;class te extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function Em(e,t=!1){const r=_m(e,t);switch(zn(r,"Server message"),Im(r),r.type){case"grant":return bt(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),_t(r.connectionEpoch,"connectionEpoch"),ke(r.nextClientSequence,"nextClientSequence"),ke(r.nextServerSequence,"nextServerSequence"),ns(r.snapshot),r;case"event":return bt(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),_t(r.connectionEpoch,"connectionEpoch"),ke(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&Ce("event must be account.changed or status.changed"),ns(r.snapshot),r;case"heartbeat":return bt(r,["version","type","connectionEpoch","sequence"],"heartbeat"),_t(r.connectionEpoch,"connectionEpoch"),ke(r.sequence,"sequence"),r;default:return Ce("Unknown server message type")}}function bm(e){const t=e.connectionEpoch;_t(t,"connectionEpoch"),ke(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(_t(n.connectionEpoch,"connectionEpoch"),ke(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 _m(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>rs)throw new te("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>rs)throw new te("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return Am(e),JSON.parse(e)}catch(r){throw r instanceof te?r:new te("INVALID_JSON","Channel frame must contain strict JSON")}}function ns(e){zn(e,"snapshot"),bt(e,["account","permissions"],"snapshot"),zn(e.account,"snapshot.account"),bt(e.account,["revision"],"snapshot.account"),ke(e.account.revision,"snapshot.account.revision"),Qf(e.permissions)||Ce("snapshot.permissions is invalid")}function Im(e){e.version!==jn&&Ce("version must be 1")}function zn(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Ce(`${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)))&&Ce(`${r} fields are invalid`)}function ke(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Ce(`${t} must be a non-negative safe integer`)}function _t(e,t){(typeof e!="string"||!wm.test(e))&&Ce(`${t} must be a 22-character base64url value`)}function Ce(e){throw new te("INVALID_MESSAGE",e)}function Am(e){new Sm(e).scan()}class Sm{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>=ym)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 is=[1e3,2e3,4e3,8e3,15e3];function vm(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=is[Math.min(p,is.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=Dm(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:jn,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=Em(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=bm({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:jn,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 Rm(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 Dm(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=Rm(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}const Tm="/__hb_sdk_bootstrap__",Pm="/__hb_sdk__/mobile-launch-redirect",Lm="/__hb_sdk__/network",Cm="/session/status",Om="/session/request",km="/session/events",Nm=320,Mm=1e3,Um=1e3,Hm=15e3,oa=new URL(location.href).searchParams,sa=oa.get("mini_url"),qr=oa.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(!sa&&!qr)throw x.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const xm=sa??"about:blank",de=await pi();let Se=de.lanAddresses,Qt=de.defaultLanAddressId,Xe=de.mobileLaunchRedirect,aa=wi(de),Ze=de.devContext,Ct=Jf(Ze),B=!1,$r=0;const gi=new AbortController;let Ue=0,tt,Ot,Xt=0,He,Gn,Wn,ve=0,kt=!1,Jt,et,On=!1,os=Promise.resolve(),It=-1,Nt=!1,xe,Kn,Yn,Zt,Oe;const Ur=new Set,it=nm({applyStatus:e=>ha(e,!0),fetchStatus:e=>la(_a(gi.signal,e)),getCanonicalRevision:()=>It,onError:sg,reconcile:()=>Wm($r)}),Qn=im({connectEvents:fa,invalidate:()=>it.invalidate(),isDisposed:()=>B,maxDelayMs:Hm,minDelayMs:Um,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});await Xn(!1);wa();ba(Ea(de));qr&&Vm();jr();await Bt("initial");qr||(fa(),zm());Bm();function Bm(){window.addEventListener("beforeunload",ag),window.addEventListener("hb-sdk:restart-runtime",da),window.addEventListener("hb-sdk:refresh-storage",jr),window.addEventListener("hb-sdk:qr-open-change",ca)}function ca(e){const t=e.detail?.open===!0;t!==kt&&(kt=t,ve+=1,zr(),et!==void 0&&window.clearInterval(et),et=void 0,t&&(x.mobileLanSelect.addEventListener("change",Fm),ga(),Ft(),de.devContext.source==="remote"&&(et=window.setInterval(()=>{ng()},Mm))))}function Fm(){kt&&Ft()}function da(){ua("manual restart")}function ua(e){B||tt!==void 0||(re("runtime.restart",{boundary:Ue+1}),tt=window.setTimeout(()=>{tt=void 0,B||Bt(e)},0))}async function Bt(e){const t=++Ue;if(Ot=void 0,ma(e),Q.runtimeStatus="loading",Sa(Ct),x.device.replaceChildren(),qr){x.device.innerHTML=`
|
|
93
|
-
<div class="browser-mock-preview">
|
|
94
|
-
<span class="browser-mock-preview__icon">UI</span>
|
|
95
|
-
<strong>Browser Mock</strong>
|
|
96
|
-
<small>mp_preview</small>
|
|
97
|
-
</div>`,Q.runtimeStatus="idle";return}const r=document.createElement("iframe");r.dataset.testid="device-iframe",r.title="小程序预览",r.allow="clipboard-read; clipboard-write",x.device.appendChild(r);const n=new AbortController;Gn=n;try{const i=await bf(qm(n.signal,t));if(B||t!==Ue){i.dispose();return}Wn=i.dispose;const o=of({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=>$m(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"&&jr()}});He=o,await o.start()}catch(i){if(B||t!==Ue||n.signal.aborted)return;Q.runtimeStatus="error",re("runtime.start.failed",Et(i))}}function Vm(){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 qm(e,t){return{signal:e,account:{async getCurrentUserId(){return(await Xn(!1,e)).user_id},async ensureAuthenticated({signal:r}){await Xn(!1,r)},onChange(r){return Ur.add(r),()=>Ur.delete(r)}},authenticatedRequest:jm,storage:{area:"local",storage:localStorage},presentation:hm({close:async()=>{ss(),He?.destroy(),Q.runtimeStatus="closed"},reload:()=>{!B&&t===Ue&&(Ot=t)},pushLog:re,getDeviceMetrics:()=>Ca.value}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:r=>{document.title=r}},resolveLaunch:async()=>({configuration:am({launchUrl:xm,runtimePermissions:Zf(Ze.runtimePermissions,Ct),...Ze.miniProgramId?{miniProgramId:Ze.miniProgramId}:{}}),hostHints:{launchKind:Ze.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:r=>sm(r)}}}function $m(e,t){t.type!=="bridge_response"||t.method!=="navigation.reload"||t.outcome!=="success"||Ot!==e||e!==Ue||(Ot=void 0,ua("navigation.reload"))}async function jm(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 yi(n?Lm:Om,{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 Xn(e,t){const r=$r,n=await la(_a(gi.signal,t));return Ia(r)?ha(n,e).status:Jn()}async function la(e){return await(await fetch(Cm,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function ha(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<It)return{changed:!1,status:Jn()};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!==xe||n!==Kn||i!==Yn;return It=e.revision,Nt=e.authenticated,xe=r,Kn=n,Yn=i,wa(),t&&o&&Ur.forEach(s=>s(xe)),{changed:o,status:Jn()}}function Jn(){return{authenticated:Nt,revision:It,...Nt&&xe?{user_id:xe}:{}}}function zm(){if(!(!de.csrfToken||B))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Oe=vm({csrfToken:de.csrfToken,onDiagnostic:t=>re("channel.diagnostic",t),url:e.toString()}),Oe.subscribeUpdates((t,r)=>Gm(t,r)),Oe.connect()}catch{Oe?.dispose(),Oe=void 0}}function Gm(e,t){it.invalidate(e.account.revision),ug(Ct,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Bt("status changed"):(Ct=Sa(e.permissions),Km())}function fa(){if(Zt?.close(),Zt=void 0,!xe||B)return;const e=new EventSource(km,{withCredentials:!0});Zt=e,e.addEventListener("account-invalidated",()=>{it.invalidate()}),e.addEventListener("account-revision",()=>{it.invalidate()}),e.onopen=()=>{Qn.reset()},e.onerror=()=>{e.close(),Qn.schedule()}}async function Wm(e){Ia(e)&&await Bt("account revision changed")}function ma(e){Xt+=1,ss(),He?.destroy(),He=void 0,Gn?.abort(new DOMException(e,"AbortError")),Gn=void 0,Wn?.(),Wn=void 0}async function Km(){B||(await Bt("permission changed"),!B&&await Ft())}async function pi(){const e=await fetch(Tm,{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(!je(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Aa(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:Ym(t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(dg):[],loginAvailable:t.loginAvailable===!0,miniProgram:ig(t.miniProgram),mobileLaunchRedirect:r,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0}}function Ym(e,t){return je(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 yi(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 ga(e=x.mobileLanSelect.options.length>0?x.mobileLanSelect.value:void 0){x.mobileLanSelect.replaceChildren();for(const t of Se){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,x.mobileLanSelect.appendChild(r)}e&&Se.some(({id:t})=>t===e)?x.mobileLanSelect.value=e:Qt&&Se.some(({id:t})=>t===Qt)?x.mobileLanSelect.value=Qt:Se[0]&&(x.mobileLanSelect.value=Se[0].id),x.mobileLanSelect.disabled=Se.length===0}async function Ft(){if(B)return;const e=++ve;zr();const t=cg();if(!t?.mobileAppQrPayload){x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent="未发现可用的局域网地址";return}x.mobileQrStatus.textContent="正在生成二维码...";try{const r=await eg(t);if(e!==ve||B)return;const n=await Qm(r.address,r.expiresAt);if(e!==ve||B)return;const i=await $f.toDataURL(n.payload,{width:Nm,margin:1});if(e!==ve||B)return;x.mobileQrImage.src=i,x.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,rg(n.expiresAt,e)}catch(r){if(e!==ve||B)return;if(r instanceof ot){ya();return}x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent=Ei(r)}}async function Qm(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await Xm(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:pm(gm({host:e.address,port:location.port,token:n.token}))}}catch{throw new ot}}async function Xm(e,t){if(Xe?.addressId===e.id)return Xe;if(!Xe)return;const r=await yi(Pm,{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=je(n)?Aa({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 Jm(e){const t=await pi(),r=Zm(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return pa(t),{...r,mobileAppQrPayload:n}}function Zm(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function pa(e){aa=wi(e),Se=e.lanAddresses,Qt=e.defaultLanAddressId,Xe=e.mobileLaunchRedirect,ba(Ea(e)),ga()}class ot extends Error{}async function eg(e){const t=os.then(()=>tg(e));return os=t.then(()=>{},()=>{}),t}async function tg(e){const t=new URL(e.appUrl),r=new URL(Yf,location.origin),n=await yi(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:em(Ze.runtimePermissions,Ct)})}),i=await n.json();if(!n.ok||!je(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await Jm(e.id),expiresAt:i.expires_at}}function rg(e,t){Jt=window.setTimeout(()=>{!B&&kt&&t===ve&&Ft()},Math.max(1e3,e-Date.now()-3e4))}async function ng(){if(!(On||B)){On=!0;try{const e=await pi();if(wi(e)===aa)return;pa(e),kt&&Ft()}catch(e){e instanceof ot&&ya()}finally{On=!1}}}function ya(){ve+=1,zr(),x.mobileQrImage.removeAttribute("src"),x.mobileQrStatus.textContent="Mobile 短链接配置无效"}function wi(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 wa(){if(!Nt){Q.account={authenticated:!1,avatar:"",nickname:"未登录"};return}Q.account={authenticated:!0,avatar:Yn??"",nickname:Kn||xe||"已登录"}}function Ea(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function ba(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 ig(e){if(e===null)return null;if(!je(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 jr(){const e=++Xt,t=He,r=t?.diagnostics.storage;if(!r){Q.storage=[],Q.storageError=t?"当前 Host 不支持 Storage 诊断":"";return}try{const n=await r.getSnapshot();if(B||e!==Xt||t!==He)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!==Xt||t!==He)return;Q.storage=[],Q.storageError=Ei(n)}}function og(e,t){re("host.message",{message:e,status:t})}function sg(e){B||og(Ei(e),"error")}function re(e,t){La(e,t)}function ag(){B||(B=!0,window.removeEventListener("hb-sdk:restart-runtime",da),window.removeEventListener("hb-sdk:refresh-storage",jr),window.removeEventListener("hb-sdk:qr-open-change",ca),$r+=1,gi.abort(new DOMException("Browser Dev Host disposed","AbortError")),it.dispose(),Ue+=1,ma("Browser Dev Host disposed"),Zt?.close(),Oe?.dispose(),Oe=void 0,Qn.dispose(),Ot=void 0,tt!==void 0&&window.clearTimeout(tt),tt=void 0,zr(),et!==void 0&&window.clearInterval(et),Ur.clear())}function zr(){Jt!==void 0&&window.clearTimeout(Jt),Jt=void 0}function _a(e,t){return t?AbortSignal.any([e,t]):e}function Ia(e){return!B&&e===$r}function cg(){return Se.find(({id:e})=>e===x.mobileLanSelect.value)}function dg(e){return je(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 Aa(e){if(!(!je(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 Sa(e){return{networkRequest:{...e.networkRequest}}}function ug(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function Ei(e){return e instanceof Error&&e.message?e.message:"操作失败"}function je(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}
|