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