@heybox/hb-sdk 0.10.0-alpha.3 → 0.10.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/cli-chunks/{build-DJvUpgCG.cjs → build-wguxGJim.cjs} +4 -4
  2. package/dist/cli-chunks/{create-CKFbAKsd.cjs → create-mJhWyXDG.cjs} +1 -1
  3. package/dist/cli-chunks/{dev-DkQ3XT4g.cjs → dev-CyfaFkKn.cjs} +9 -9
  4. package/dist/cli-chunks/{doctor-CrDV0t0X.cjs → doctor-De8pnp13.cjs} +1 -1
  5. package/dist/cli-chunks/{game-binding-guide-Du9jYSv0.cjs → game-binding-guide-C9ICs9zj.cjs} +2 -2
  6. package/dist/cli-chunks/{game-bindings-DyUsgTvm.cjs → game-bindings-Bg2xoKZY.cjs} +3 -3
  7. package/dist/cli-chunks/{games-60o0JlU1.cjs → games-CAhkA4nh.cjs} +1 -1
  8. package/dist/cli-chunks/{index-B3bDDBnX.cjs → index-B8rzkV1n.cjs} +1 -1
  9. package/dist/cli-chunks/{index-oQnW71g6.cjs → index-pGP_FOkj.cjs} +18 -18
  10. package/dist/cli-chunks/{index.esm-C5mTEO5-.cjs → index.esm-BqyU_JCg.cjs} +8 -8
  11. package/dist/cli-chunks/{login-81EUI3Tp.cjs → login-BYLNpsQ1.cjs} +1 -1
  12. package/dist/cli-chunks/{project-vite-BL7txpEs.cjs → project-vite-BRUA9Vng.cjs} +1 -1
  13. package/dist/cli-chunks/{remote-BaistJfP.cjs → remote-BAf86E8n.cjs} +4 -4
  14. package/dist/cli-chunks/{runtime-permission-env-ChCGtenG.cjs → runtime-permission-env-XMA-YAuB.cjs} +2 -2
  15. package/dist/cli-chunks/{skill-BQUjMV7k.cjs → skill-D6kR1-g0.cjs} +2 -2
  16. package/dist/cli-chunks/{version-CUuM16X6.cjs → version-SUKtha-_.cjs} +1 -1
  17. package/dist/cli.cjs +1 -1
  18. package/dist/devtools/browser-dev-host/assets/browser-dev-host-C2-qtvqp.js +224 -0
  19. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-CIC_pBdX.js → desktop-app-launch-DVnZ7dFB.js} +1 -1
  20. package/dist/devtools/browser-dev-host/assets/{index-D1Iqs-0N.js → index-DCPdAyuJ.js} +3 -3
  21. package/dist/devtools/browser-dev-host/index.html +2 -2
  22. package/dist/index.cjs.js +1 -1
  23. package/dist/index.esm.js +1 -1
  24. package/dist/vite.cjs.js +1 -1
  25. package/dist/vite.esm.js +1 -1
  26. package/package.json +5 -5
  27. package/skill/skill.json +4 -4
  28. package/types/index.d.ts +5 -3
  29. package/dist/devtools/browser-dev-host/assets/browser-dev-host-Dho-QHhS.js +0 -224
@@ -1,224 +0,0 @@
1
- import{m as e0,H as hu,a_ as t0,bA as r0,a3 as n0,bh as i0,bi as s0,n as kt,bK as ie,ba as Fl,l as zl,aM as a0,e as mu,aR as o0,aD as c0,k as u0,aN as d0,bE as Rn,aY as si,aX as Do,aZ as Xi,b2 as jl,b4 as l0,f as hs,v as f0,ap as ms,Z as Sc,aQ as h0,j as So,at as Oo,h as m0,be as Vl,aI as E0,G as g0,b0 as Gl,U as p0,z as _0,aF as T0,y as A0,bb as I0,bC as Yl,bB as ql,b6 as b0,g as Mo,aH as y0,b as Mr,c as N0}from"./desktop-app-launch-CIC_pBdX.js";function w0(){return{targetId:"ui-preview-target",ownerId:"ui-preview-owner",adapterId:"browser-dev-host",kind:"browser",capabilities:{storage:!0,presentation:!0,sandboxList:!0,sandboxRead:!0},state:"attached",currentInstanceId:"ui-preview-instance",cdpTargetId:"ui-preview-browser-target",metadata:{displayName:"UI 预览(模拟)",browser:"Chrome",os:"macOS"},updatedAt:Date.now(),stale:!1}}function D0(){return[{key:"network",label:"网络请求",state:"approved",facts:{platformApproval:!0,temporary:!1,effective:!0,online:"enabled"}},{key:"companion",label:"桌面辅助应用",state:"temporary",facts:{platformApproval:!1,temporary:!0,effective:!0,online:"disabled"},releaseDifference:"发布前需要获得平台批准。"},{key:"network.useOfficialDomain",label:"官方域名",state:"unavailable",facts:{platformApproval:!1,temporary:!1,effective:!1,online:"disabled"},reason:"不支持本地临时授权,获得平台批准后才能使用。"}]}const vi={device:'[data-preview-target="device"]',screen:'[data-preview-target="screen"]',app:"#device iframe",workbench:'[data-testid="workbench-root"]'},Eu=15e3,S0=32*1024*1024,gu="data-hb-preview-capture-device",qa="data-hb-preview-capture-ancestor",pu="data-hb-preview-capture-surface",_u=64,O0=1024;function M0(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??Eu;if(!Number.isFinite(n)||n<=0||n>Eu)throw ut("INVALID_CAPTURE_LEASE","截图租约无效");let i;function s(d,l,h){d.attributes.push({element:l,name:h,previous:l.getAttribute(h)}),l.setAttribute(h,d.token)}function a(d){const l=i;if(!l||l.token!==d)return!1;const h=c(l),f=!!l.style?.isConnected;i=void 0,clearTimeout(l.timer),l.removeAbort?.(),l.removeResize?.(),l.observer?.disconnect(),l.style?.remove(),l.bounds?.remove();for(const{element:_,name:p,previous:y}of l.attributes)_.getAttribute(p)===d&&(y===null?_.removeAttribute(p):_.setAttribute(p,y));return l.overlay.remove(),f&&(r.scrollX!==l.scroll.x||r.scrollY!==l.scroll.y)&&r.scrollTo(l.scroll.x,l.scroll.y),h}function c(d){const{viewport:l,target:h,rect:f}=d;if(!h?.isConnected||!f||Date.now()>=d.expiresAt||r.innerWidth!==l.width||r.innerHeight!==l.height||r.devicePixelRatio!==l.devicePixelRatio)return!1;const _=h.getBoundingClientRect();return["left","top","width","height"].every(p=>Math.abs(_[p]-f[p])<.01)}async function u(d,l){if(l?.throwIfAborted(),!Number.isFinite(d.deadlineAt)||Date.now()>=d.deadlineAt)throw ut("PREVIEW_TIMEOUT","截图操作已超时");if(d.scope==="workbench"||!Object.hasOwn(vi,d.scope))throw ut("INVALID_CAPTURE_SCOPE","设备像素截图仅支持 device、screen 或 app");if(!d.operationId||d.operationId.length>128)throw ut("INVALID_OPERATION","截图操作标识无效");if(!d.previewImage.startsWith("data:image/png;base64,")||d.previewImage.length>S0)throw ut("INVALID_CAPTURE_IMAGE","共享窗口冻结图无效或过大");if(i)throw ut("PREVIEW_BUSY","已有设备截图正在执行");const h=t.querySelectorAll(vi.device);if(h.length!==1)throw ut("DEVICE_NOT_UNIQUE","设备画面不唯一或尚未创建");const f=h[0],_=d.scope==="device"?f:t.querySelector(vi[d.scope]);if(!_||_!==f&&!f.contains(_))throw ut("CAPTURE_TARGET_UNAVAILABLE","截图内容尚未创建");const p=f.getBoundingClientRect();if(!(p.width>0&&p.height>0))throw ut("CAPTURE_TARGET_UNAVAILABLE","设备画面当前不可见");const y=t.createElement("img");y.alt="",y.setAttribute("aria-hidden","true"),y.setAttribute("data-hb-preview-capture-freeze",""),y.style.cssText=`position:fixed;left:0;top:0;width:${r.innerWidth}px;height:${r.innerHeight}px;max-width:none;max-height:none;margin:0;border:0;padding:0;z-index:2147483647;pointer-events:auto;user-select:none;`,y.addEventListener("wheel",Q=>Q.preventDefault(),{passive:!1}),y.addEventListener("touchmove",Q=>Q.preventDefault(),{passive:!1});const w=Math.min(Date.now()+n,d.deadlineAt),N={operationId:d.operationId,token:r.crypto.randomUUID(),overlay:y,attributes:[],scroll:{x:r.scrollX,y:r.scrollY},viewport:{width:r.innerWidth,height:r.innerHeight,devicePixelRatio:r.devicePixelRatio},expiresAt:w};i=N,N.timer=setTimeout(()=>a(N.token),Math.max(0,w-Date.now()));const O=()=>a(N.token);l?.addEventListener("abort",O,{once:!0}),N.removeAbort=()=>l?.removeEventListener("abort",O);const I=()=>{const{viewport:Q}=N;(r.innerWidth!==Q.width||r.innerHeight!==Q.height||r.devicePixelRatio!==Q.devicePixelRatio)&&a(N.token)};r.addEventListener("resize",I),N.removeResize=()=>r.removeEventListener("resize",I);const H=()=>{if(l?.throwIfAborted(),i!==N||Date.now()>=w)throw ut("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{y.src=d.previewImage,await y.decode(),H();const Q=N.token,M=`[${gu}="${Q}"]`,x=r.getComputedStyle(f),v=new r.DOMMatrixReadOnly(x.transform==="none"?void 0:x.transform),W=Math.atan2(v.b,v.a),q=f.querySelector(".desktop-window__surface"),te=q?q.offsetWidth:Number.parseFloat(x.width),F=q?q.offsetHeight:Number.parseFloat(x.height),G=x.backgroundColor,j=r.getComputedStyle(t.body).backgroundColor,z=ce=>!ce||ce==="transparent"||ce==="rgba(0, 0, 0, 0)",V=z(G)?z(j)?"#fff":j:G;if(!(te>0&&F>0))throw ut("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");H(),t.body.append(y),s(N,f,gu),q&&s(N,q,pu);for(let ce=f.parentElement;ce;ce=ce.parentElement)s(N,ce,qa);const U=t.createElement("style");N.style=U;const k=`
2
- [${qa}="${Q}"] {overflow:visible!important;scrollbar-width:none!important;}
3
- [${qa}="${Q}"]::-webkit-scrollbar {display:none!important;}
4
- [${pu}="${Q}"] {transform:none!important;transition:none!important;}
5
- `,Y=(ce,_e,ye=0,Ee=0)=>`${M} {position:absolute!important;left:${ce}px!important;top:${_e}px!important;width:${te}px!important;height:${F}px!important;transform:translate(${ye}px,${Ee}px) rotate(${W}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${V}!important;}`;U.textContent=k+Y(0,0),H(),t.head.append(U);const R=f.getBoundingClientRect(),K=t.querySelector(vi.app),Z=K&&f.contains(K)?K.getBoundingClientRect():void 0,ee=Z&&Z.width>0&&Z.height>0?Z:void 0,se=ee?Math.floor(r.innerWidth-1-(ee.left-R.left)):r.innerWidth+64,fe=ee?Math.floor(r.innerHeight-1-(ee.top-R.top)):32,we=se-R.left,Pe=fe-R.top;H(),U.textContent=k+Y(we,Pe);const E=f.getBoundingClientRect();U.textContent=k+Y(we,Pe,se-E.left,fe-E.top),H();const m=_.getBoundingClientRect(),S=Math.floor(qr(m.left+r.scrollX)),D=Math.floor(qr(m.top+r.scrollY)),P={x:S,y:D,width:Math.ceil(qr(m.right+r.scrollX))-S,height:Math.ceil(qr(m.bottom+r.scrollY))-D};if(!(P.width>0&&P.height>0)||P.x<0||P.y<0)throw ut("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(ee&&K){const ce=K.getBoundingClientRect();if(!(ce.left<r.innerWidth&&ce.top<r.innerHeight&&ce.right>0&&ce.bottom>0))throw ut("CAPTURE_LAYOUT_INVALID","无法保持 iframe 的最小绘制区域");const _e=f.getBoundingClientRect(),ye=Math.floor(qr(_e.left))-1,Ee=Math.floor(qr(_e.top))-1,Ce=r.innerWidth-ye,De=r.innerHeight-Ee;if(ye<0||Ee<0||Ce<=0||De<=0||Ce>_u||De>_u||Ce*De>O0)throw ut("CAPTURE_LAYOUT_INVALID","无法在有界角部保持完整设备绘制,请改用 --scale css");y.style.clipPath=`polygon(0 0,100% 0,100% ${Ee}px,${ye}px ${Ee}px,${ye}px 100%,0 100%)`,y.setAttribute("data-hb-preview-capture-corner",JSON.stringify({x:ye,y:Ee,width:Ce,height:De}))}const X=t.createElement("div");if(X.setAttribute("aria-hidden","true"),X.style.cssText=`position:absolute;left:${P.x+P.width+2}px;top:${P.y+P.height+2}px;width:1px;height:1px;pointer-events:none;opacity:0;`,N.bounds=X,H(),t.body.append(X),N.target=_,N.rect=m,await R0(r,l),H(),!c(N))throw ut("CAPTURE_LAYOUT_INVALID","截图准备期间布局发生变化,请重新截图");N.observer=new r.ResizeObserver(()=>{i===N&&!c(N)&&a(N.token)});for(const{element:ce}of N.attributes)N.observer.observe(ce);return{token:Q,clip:P,devicePixelRatio:r.devicePixelRatio,expiresAt:w}}catch(Q){throw a(N.token),Q}}return{prepare:u,restore:a,cancel:d=>i?.operationId!==d?!1:(a(i.token),!0),dispose:()=>{i&&a(i.token)}}}function R0(e,t){return new Promise((r,n)=>{let i=e.requestAnimationFrame(()=>{i=e.requestAnimationFrame(a)});const s=()=>{e.cancelAnimationFrame(i),t?.removeEventListener("abort",s),n(t?.reason)};function a(){t?.removeEventListener("abort",s),r()}t?.addEventListener("abort",s,{once:!0}),t?.aborted&&s()})}function ut(e,t){return Object.assign(new Error(t),{name:"PreviewError",code:e})}function qr(e){const t=Math.round(e);return Math.abs(e-t)<.001?t:e}const ga=["post.get","post.comments.list","post.watch"],ai=["post.setLiked","post.setFavorited","post.comments.openEditor","post.comments.delete","post.comments.setLiked"],Ro="cloud.rooms.list",Co="cloud.rooms.create",Lo="cloud.rooms.join",Po="cloud.rooms.send",vo="cloud.rooms.leave",ko="cloud.rooms.dispose",xo="cloud.rooms.lifecycle",Oc="user.games.getOverview",Es="user.data.query",Qn="user.data.sync",gs="user.data.file",Mc="user.dataPermission.request",Rc="user.dataPermission.get",Cc="user.dataPermission.set",Lc="user.dataPermission.openSettings",Pc="user.dataPermission.revokeSession",Ql=[Oc,Es,Qn,gs,Mc,Rc,Cc,Lc,Pc],ps="workspaceCards.requestRefresh",_s="auth.getAccountState",Ts="auth.login",As="user.getFollowStatus",Is="user.requestFollowAuthor",C0="gameSaves.list",L0="gameSaves.sync",P0="gameSaves.getFile",v0="gameSaves.readParsedData",bs="user.getInfo",ys="user.revokeAuthorization",Ns="user.getSteamGameList",oi="user.showAppreciation",ws="share.copyLink",Ds="share.showShareMenu",Ss="share.screenshot",Os="share.screenshotLong",Br="viewport.setDisplay",Ms="viewport.getWindowInfo",Rs="viewport.setNavigationBarStyle",ci="storage.getStorage",ui="storage.setStorage",Cs="network.request",Ls="network.download",Ps="network.upload",vs="files.pickFiles",ks="files.pickDirectory",xs="files.saveFile",di="file.create",li="file.remove",Us="file.exists",fi="file.readText",Bs="file.writeText",hi="file.readBytes",Hs="file.writeBytes",mi="file.stat",Fs="directory.create",Ei="directory.remove",zs="directory.exists",js="directory.list",gi="media.pick",Vs="ui.showToast",Gs="ui.showLoading",Ys="ui.hideLoading",qs="device.vibrate",Qs="device.setClipboard",Ws="device.executeProtocol",$s="navigation.close",Ks="navigation.reload",Zs="navigation.openAppPage",tr="cloud.leaderboard.submit",vt="cloud.leaderboard.getList",gr="cloud.leaderboard.getCurrentUserEntry",Hr="cloud.leaderboard.deleteCurrentUserEntry",qt="cloud.leaderboard.getInfo",fn="cloud.storage.getStorage",hn="cloud.storage.setStorage",mn="cloud.storage.removeItem",Fr="cloud.storage.getKeys",pa="companion.getInfo",_a="companion.getPreparationStatus",Ta="companion.prepare",Aa="companion.cancelPreparation",Ia="companion.getActiveSession",ba="companion.launch",ya="companion.session.write",Na="companion.session.closeStdin",wa="companion.session.terminate",Da="companion.session.ackOutput",Sa="companion.openAttachment",Oa="companion.showNotification",pr=[...ga.map(e=>({method:e,module:"post",capability:e,requirement:{kind:"all",permissions:["post"]},risk:"medium"})),...ai.map(e=>({method:e,module:"post",capability:e,requirement:{kind:"all",permissions:["post"]},risk:"high"})),...[C0,L0,P0,v0].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),...Ql.map(e=>({method:e,module:"userGameData",capability:e,requirement:{kind:"all",permissions:["user_game_data"]},risk:"high"})),{method:ps,module:"workspaceCards",capability:ps,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:_s,module:"auth",capability:_s,requirement:{kind:"none"},risk:"low"},{method:Ts,module:"auth",capability:Ts,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:As,module:"user",capability:As,requirement:{kind:"none"},risk:"low"},{method:Is,module:"user",capability:Is,requirement:{kind:"none"},risk:"high"},{method:bs,module:"user",capability:bs,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:ys,module:"user",capability:ys,requirement:{kind:"none"},risk:"high"},{method:Ns,module:"user",capability:Ns,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:oi,module:"user",capability:oi,requirement:{kind:"none"},risk:"medium"},{method:ws,module:"share",capability:ws,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Ds,module:"share",capability:Ds,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Ss,module:"share",capability:Ss,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Os,module:"share",capability:Os,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Ms,module:"viewport",capability:Ms,requirement:{kind:"none"},risk:"low"},{method:Rs,module:"viewport",capability:Rs,requirement:{kind:"none"},risk:"low"},{method:Br,module:"viewport",capability:Br,requirement:{kind:"none"},risk:"low"},{method:ci,module:"storage",capability:ci,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:ui,module:"storage",capability:ui,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Cs,module:"network",capability:Cs,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Ls,module:"network",capability:Ls,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Ps,module:"network",capability:Ps,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:vs,module:"files",capability:vs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ks,module:"files",capability:ks,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:xs,module:"files",capability:xs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:di,module:"file",capability:di,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:li,module:"file",capability:li,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Us,module:"file",capability:Us,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:fi,module:"file",capability:fi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Bs,module:"file",capability:Bs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:hi,module:"file",capability:hi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Hs,module:"file",capability:Hs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:mi,module:"file",capability:mi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Fs,module:"directory",capability:Fs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ei,module:"directory",capability:Ei,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:zs,module:"directory",capability:zs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:js,module:"directory",capability:js,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:gi,module:"media",capability:gi,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:Vs,module:"ui",capability:Vs,requirement:{kind:"none"},risk:"low"},{method:Gs,module:"ui",capability:Gs,requirement:{kind:"none"},risk:"low"},{method:Ys,module:"ui",capability:Ys,requirement:{kind:"none"},risk:"low"},{method:qs,module:"device",capability:qs,requirement:{kind:"none"},risk:"low"},{method:Qs,module:"device",capability:Qs,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Ws,module:"device",capability:Ws,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:$s,module:"navigation",capability:$s,requirement:{kind:"none"},risk:"medium"},{method:Ks,module:"navigation",capability:Ks,requirement:{kind:"none"},risk:"medium"},{method:Zs,module:"navigation",capability:Zs,requirement:{kind:"none"},risk:"medium"},{method:Ro,module:"cloud",capability:Ro,requirement:{kind:"all",permissions:["cloud_rooms"]},risk:"medium"},{method:Co,module:"cloud",capability:Co,requirement:{kind:"all",permissions:["cloud_rooms"]},risk:"medium"},{method:Lo,module:"cloud",capability:Lo,requirement:{kind:"all",permissions:["cloud_rooms"]},risk:"medium"},{method:Po,module:"cloud",capability:Po,requirement:{kind:"all",permissions:["cloud_rooms"]},risk:"medium"},{method:vo,module:"cloud",capability:vo,requirement:{kind:"all",permissions:["cloud_rooms"]},risk:"medium"},{method:ko,module:"cloud",capability:ko,requirement:{kind:"all",permissions:["cloud_rooms"]},risk:"medium"},{method:xo,module:"cloud",capability:xo,requirement:{kind:"all",permissions:["cloud_rooms"]},risk:"medium"},{method:tr,module:"cloud",capability:tr,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:vt,module:"cloud",capability:vt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:gr,module:"cloud",capability:gr,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Hr,module:"cloud",capability:Hr,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:qt,module:"cloud",capability:qt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:fn,module:"cloud",capability:fn,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:hn,module:"cloud",capability:hn,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:mn,module:"cloud",capability:mn,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Fr,module:"cloud",capability:Fr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[pa,_a,Ta,Aa,Ia,ba,ya,Na,wa,Da,Sa,Oa].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],Nr="heybox:miniprogram",Wl=2,$l="hb_mini_bridge_nonce",Kl="sdk.handshake",ki="runtime.location.probe",k0="sdk.location.report",x0="sdk.csp.violation",Zl="operation.progress",U0="companion.session.output",B0="companion.session.exit",H0="companion.session.ownershipLost";function F0(e){return!Rt(e)||e.namespace!==Nr||e.version!==1&&e.version!==2||!We(e.nonce)?!1:e.type==="handshake"?We(e.id)&&e.method===Kl&&e.error===void 0&&W0(e.payload):e.type==="request"?We(e.id)&&We(e.method)&&e.error===void 0:e.type==="response"?We(e.id)&&(e.method===void 0||We(e.method))&&(e.error===void 0||$0(e.error)):e.type==="event"?!We(e.method)||e.error!==void 0?!1:e.method===Zl?e.version===2&&We(e.id)&&Q0(e.payload):e.id===void 0||We(e.id):e.type==="cancel"?e.version===2&&We(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function vc(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function Xl(e){return Rt(e)?e.kind==="sandbox"?bt(e,["kind"]):e.kind==="directory"&&We(e.handleId)&&bt(e,["kind","handleId"]):!1}function kr(e){return!Rt(e)||e.kind!=="file"?!1:We(e.handleId)?bt(e,["kind","handleId"]):Xl(e.root)&&vc(e.relativePath)&&bt(e,["kind","root","relativePath"])}function Jl(e){return!Rt(e)||e.kind!=="directory"?!1:We(e.handleId)?bt(e,["kind","handleId"]):Xl(e.root)&&(e.relativePath==="."||vc(e.relativePath))&&bt(e,["kind","root","relativePath"])}function z0(e){return Rt(e)&&e.kind==="file"&&We(e.name)&&K0(e.mode)&&kr(e.ref)&&bt(e,["kind","name","mode","ref"])}const ef=20,Tu=["type","mimeType","size","width","height","previewUrl","file"];function j0(e){return e===void 0?!0:!(!Rt(e)||!bt(e,["source","mediaType","maxCount"])||e.source!==void 0&&e.source!=="album"&&e.source!=="camera"||e.mediaType!==void 0&&e.mediaType!=="image"&&e.mediaType!=="video"&&e.mediaType!=="all"||e.maxCount!==void 0&&(!Z0(e.maxCount,1,ef)||e.source==="camera"&&e.maxCount!==1))}function tf(e){if(!Rt(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!bt(e,t?[...Tu,"durationMs"]:Tu)||!We(e.mimeType)||!fr(e.size)||!Au(e.width)||!Au(e.height)||!We(e.previewUrl)||!G0(e.file)?!1:t?fr(e.durationMs):!0}function V0(e){if(!Array.isArray(e)||e.length<1||e.length>ef)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!tf(e[t]))return!1;return!0}function G0(e){return!z0(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&We(e.ref.handleId)}function rf(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function Y0(e){return!Rt(e)||!fr(e.loaded)||typeof e.lengthComputable!="boolean"||!bt(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?fr(e.total)&&e.loaded<=e.total:e.total===void 0}function q0(e){return Rt(e)?e.phase==="downloading"?fr(e.loaded)&&(e.total===void 0||fr(e.total)&&e.loaded<=e.total)&&bt(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:fr(e.processed)&&fr(e.total)&&e.processed<=e.total&&bt(e,["phase","processed","total"]):!1}function Q0(e){return Y0(e)||q0(e)||Rt(e)&&bt(e,["watching"])&&e.watching===!0}function W0(e){return Rt(e)&&We(e.href)&&typeof e.userAgent=="string"&&We(e.sdkVersion)}function $0(e){return Rt(e)&&We(e.code)&&typeof e.message=="string"}function K0(e){return e==="read"||e==="readwrite"}function fr(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Au(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Z0(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function We(e){return typeof e=="string"&&e.length>0}function bt(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const nf={ark:"明日方舟",black_myth_wukong:"黑神话悟空",task_bar_hero:"任务栏英雄",phantom_blade_zero:"影之刃零"},sf=Object.keys(nf),Ji=[{key:"game.ark.profile",game:"ark",family:"profile",name:"明日方舟角色与养成资料",disclosureRevision:1,queries:{get:{schema:"ark.profile",version:1}},sync:!1,file:!1},{key:"game.ark.gacha",game:"ark",family:"gacha",name:"明日方舟抽卡记录与分析",disclosureRevision:1,queries:{get:{schema:"ark.gacha-analysis",version:1},list:{schema:"ark.gacha-record-page",version:1,page:{defaultSize:50,maxSize:100}}},sync:!1,file:!1},{key:"game.black_myth_wukong.save_analysis",game:"black_myth_wukong",family:"save_analysis",name:"黑神话悟空存档解析结果",disclosureRevision:1,queries:{get:{schema:"black_myth_wukong.save",version:1}},sync:!0,file:!1},{key:"game.black_myth_wukong.save_files",game:"black_myth_wukong",family:"save_files",name:"黑神话悟空云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.task_bar_hero.save_analysis",game:"task_bar_hero",family:"save_analysis",name:"任务栏英雄存档解析结果",disclosureRevision:1,queries:{get:{schema:"task_bar_hero.save",version:1}},sync:!0,file:!1},{key:"game.task_bar_hero.save_files",game:"task_bar_hero",family:"save_files",name:"任务栏英雄云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.phantom_blade_zero.save_analysis",game:"phantom_blade_zero",family:"save_analysis",name:"影之刃零存档解析结果",disclosureRevision:1,queries:{get:{schema:"phantom_blade_zero.save",version:1}},sync:!0,file:!1},{key:"game.phantom_blade_zero.save_files",game:"phantom_blade_zero",family:"save_files",name:"影之刃零云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0}],ar="account.pc_hardware",Ma=[...Ji,{key:ar,game:null,family:"pc_hardware",name:"PC 硬件档案",disclosureRevision:1,queries:{get:{schema:"account.pc_hardware",version:1}},sync:!1,file:!1}],Rr=Ma.map(e=>e.key),X0=new Set(Rr),J0=new Set(sf);function dr(e){return X0.has(e)}function Iu(e){return J0.has(e)}function kc(e){const t=Ma.find(i=>i.key===e);if(!t)return;const r=t.queries,n=Object.keys(r);return t.sync&&n.push("sync"),t.file&&n.push("file"),{key:t.key,game:t.game,name:t.name,family:t.family,disclosureRevision:t.disclosureRevision,queries:r,operations:n}}const eE="同步时,原始存档将上传至小黑盒;向小程序提供原始文件仍需单独许可。",zr=["userInfo","steamLibrary","share","storage","cloud_storage","cloud_rooms","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards","user_game_data","post"],xc=[{key:"gameSaves",name:"游戏存档",description:"已废弃,将在 SDK 0.10.0 移除;新接入使用 user.games。",access:"declaration",risk:"high",config:{},methods:["gameSaves.list","gameSaves.sync","gameSaves.getFile","gameSaves.readParsedData"],conditions:["SDK < 0.10.0-0 保留兼容入口,保留原合同,不增加本版逐资源确认;需要有效 Steam 登录和宿主支持。"]},{key:"userInfo",name:"用户信息",description:"登录小程序并读取当前用户的授权信息。",access:"declaration",risk:"medium",config:{},methods:["auth.login","user.getInfo"],conditions:["继续执行黑盒登录、用户授权和可信手势规则。"]},{key:"steamLibrary",name:"Steam 游戏库",description:"读取当前用户授权的 Steam 游戏库。",access:"declaration",risk:"high",config:{},methods:["user.getSteamGameList"],conditions:["继续执行账号绑定和数据可用性规则。"]},{key:"share",name:"分享",description:"使用小程序分享、分享菜单和截图能力。",access:"declaration",risk:"medium",config:{},methods:["share.copyLink","share.showShareMenu","share.screenshot","share.screenshotLong"],conditions:["继续执行分享参数校验和 Host 支持检查。"]},{key:"storage",name:"键值存储",description:"读写按小程序隔离的简单键值数据。",access:"declaration",risk:"medium",config:{},methods:["storage.getStorage","storage.setStorage"],conditions:["仅用于简单键值存储,不包含文件系统。"]},{key:"cloud_storage",name:"云端存储",description:"读写按小程序和当前登录用户隔离的云端键值数据。",access:"declaration",risk:"medium",config:{},methods:["cloud.storage.getStorage","cloud.storage.setStorage","cloud.storage.removeItem","cloud.storage.getKeys"],conditions:["云端存储按登录用户隔离并受容量配额限制。"]},{key:"filesystem",name:"文件系统",description:"访问小程序沙盒文件和用户选择的外部文件。",access:"declaration",risk:"high",config:{},methods:["network.download","network.upload","files.pickFiles","files.pickDirectory","files.saveFile","file.create","file.remove","file.exists","file.readText","file.writeText","file.readBytes","file.writeBytes","file.stat","directory.create","directory.remove","directory.exists","directory.list"],conditions:["外部文件继续要求有效的用户选择、会话句柄和匹配的读写模式。"]},{key:"media",name:"媒体",description:"通过系统图库或相机选择图片、视频。",access:"declaration",risk:"high",config:{},methods:["media.pick"],conditions:["图库授权范围仅限本次用户选择的媒体,不包含任意文件或沙盒访问权;继续执行可信手势、Host 能力与会话资源规则。"]},{key:"clipboard",name:"剪贴板",description:"向系统剪贴板写入文本。",access:"declaration",risk:"medium",config:{},methods:["device.setClipboard"],conditions:["继续执行文本长度和 Host 支持限制。"]},{key:"leaderboard",name:"排行榜",description:"读写小程序云排行榜。",access:"declaration",risk:"medium",config:{},methods:["cloud.leaderboard.submit","cloud.leaderboard.getList","cloud.leaderboard.getCurrentUserEntry","cloud.leaderboard.deleteCurrentUserEntry","cloud.leaderboard.getInfo"],conditions:["排行榜必须已创建,用户和资源规则保持不变。"]},{key:"network",name:"网络",description:"通过 network 模块请求或下载外部资源。",access:"platform-approval",risk:"high",config:{useOfficialDomain:{type:"boolean",required:!1,default:!1,description:"是否申请访问小黑盒官方域名。"}},methods:["network.request","network.download","network.upload"],conditions:["声明后仍需平台批准,并继续执行网络安全策略。"]},{key:"companion",name:"桌面辅助应用",description:"下载、准备并运行随当前小程序版本发布的受管桌面程序。",access:"platform-approval",risk:"high",config:{},methods:["companion.getInfo","companion.getPreparationStatus","companion.prepare","companion.cancelPreparation","companion.getActiveSession","companion.launch","companion.session.write","companion.session.closeStdin","companion.session.terminate","companion.session.ackOutput","companion.openAttachment","companion.showNotification"],conditions:["声明后仍需平台批准,并继续执行可信用户手势、Host 能力和当前版本 Manifest 校验。"]},{key:"appProtocol",name:"应用协议执行",description:"执行任意小黑盒客户端协议。",access:"platform-approval",risk:"high",config:{},methods:["device.executeProtocol"],conditions:["最高危险权限:批准后该入口可执行任意协议,并绕过其他 SDK 能力权限及专用授权流程。"]},{key:"workspaceCards",name:"工作区卡片",description:"在已绑定游戏的桌面工作区展示受审核卡片。",access:"platform-approval",risk:"high",config:{},methods:["workspaceCards.requestRefresh"],conditions:["需平台批准、Host 支持与有效执行租约;不隐式授予网络或存储权限。"]},{key:"cloud_rooms",name:"实时动作房间",description:"在少人数房间内交换随包声明的结构化动作。",access:"platform-approval",risk:"medium",config:{},methods:["cloud.rooms.list","cloud.rooms.create","cloud.rooms.join","cloud.rooms.send","cloud.rooms.leave","cloud.rooms.dispose","cloud.rooms.lifecycle"],conditions:["仅允许当前版本房间协议中的动作和受限参数,不提供自由文字、文件或媒体传输。"]},{key:"user_game_data",name:"游戏资料",description:"在精确资源声明范围内读取当前用户的游戏资料:明日方舟角色/养成与抽卡,以及黑神话悟空、任务栏英雄、影之刃零的云存档解析结果与文件,以及账号已保存的 PC 硬件档案。",access:"declaration",risk:"high",config:{resources:{type:"resource-map",required:!0,items:Rr,description:"精确资源声明对象;每项必须填写 1~30 个 Unicode 码点的 purpose,不接受通配符或未开放资源。"}},methods:Ql,conditions:["逐项声明资源与用途,读取前需用户许可;未取得许可不查询个人来源。","文件与解析结果分别许可;本次许可仅当前实例有效,持久许可保存在本机。","同步会将原存档上传至小黑盒,向小程序交付原文件仍需 `save_files` 许可。","平台取数不授予小程序 `network` 权限;已交付的数据副本无法撤回。"]},{key:"post",name:"关联帖子",description:"读取关联帖子与评论,或以当前用户身份互动并打开社区原生编辑器。",access:"declaration",risk:"high",config:{read:{type:"boolean",required:!1,default:!1,description:"读取帖子、评论和订阅变化。"},write:{type:"boolean",required:!1,default:!1,description:"点赞、收藏、删除评论及打开社区原生编辑器。"}},methods:[...ga,...ai],conditions:["显式声明 read / write,省略时为 false;写操作须由用户明确触发,继续执行社区审核和权限校验。"]}];new Set(zr);const tE=30;function rE(e){if(typeof e!="string")throw new Error("purpose 必须是字符串");const t=e.trim(),r=Array.from(t);if(r.length<1||r.length>tE)throw new Error("purpose 去除首尾空白后必须为 1~30 个 Unicode 码点");if(r.some(n=>{const i=n.codePointAt(0);return i>=55296&&i<=57343}))throw new Error("purpose 包含非法 Unicode 字符");return t}function pi(e){return af(e,!1)}function nE(e){return af(e,!0)}function af(e,t){if(!bu(e))throw new Error("resources 必须是资源声明对象;每项资源必须填写 purpose");const r={};for(const n of Object.keys(e).sort()){const i=e[n];if(!bu(i)||Object.keys(i).length!==1||!Object.prototype.hasOwnProperty.call(i,"purpose"))throw new Error(`resources.${n} 必须且只能包含 purpose`);let s;try{s=rE(i.purpose)}catch(a){throw new Error(`resources.${n}: ${a.message}`)}if(!dr(n)){if(t&&/^(?:game\.[a-z0-9_]+|account)\.[a-z0-9_.]+$/.test(n))continue;throw new Error(`resources 包含未开放资源:${n}`)}r[n]={purpose:s}}return r}function iE(e){return Rr.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function bu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function of(e,t,r,n){return JSON.stringify(["user-game-data-purpose-v1",e,t,r,n])}const sE=new Set(zr);function aE(e){return sE.has(e)}function ft(e){if(!Qr(e)||e.schema_version!==1||!Array.isArray(e.entries))return{valid:!1,permissions:{}};if(e.revision!==void 0&&(typeof e.revision!="number"||!Number.isInteger(e.revision)||e.revision<0))return{valid:!1,permissions:{}};const t=new Set,r={};for(const n of e.entries){if(!Qr(n)||typeof n.key!="string"||!n.key.trim())return{valid:!1,permissions:{}};const i=n.key.trim(),s=i==="network.request"?"network":i;if(t.has(s)||n.status!=="enabled"&&n.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(s),!!aE(s)){if(s==="network"){const a=n.config;if(!Qr(a)||typeof a.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{useOfficialDomain:a.useOfficialDomain}};continue}if(s==="post"){const a=n.config;if(!Qr(a)||typeof a.read!="boolean"||typeof a.write!="boolean")return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{read:a.read,write:a.write}};continue}if(s==="user_game_data"){const a=n.config;if(!Qr(a))return{valid:!1,permissions:{}};try{const c=nE(a.resources);r[s]={key:s,status:n.status,config:{resources:c}}}catch{return{valid:!1,permissions:{}}}continue}if(n.config!==null&&n.config!==void 0&&(!Qr(n.config)||Object.keys(n.config).length>0))return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{}}}}return{valid:!0,permissions:r}}function Qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const es=["network","companion","appProtocol"];function cf(e){if(!Cn(e,["schema_version","revision","entries"])||e.schema_version!==1||typeof e.revision!="number"||!Number.isSafeInteger(e.revision)||e.revision<0||!Array.isArray(e.entries)||e.entries.length>es.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Cn(n,["key","status","config"])||n.status!=="enabled")return{valid:!1};if(typeof n.key!="string"||r.has(n.key))return{valid:!1};if(r.add(n.key),n.key==="network"){if(!Cn(n.config,["useOfficialDomain"])||n.config.useOfficialDomain!==!1)return{valid:!1};t.push({key:"network",status:"enabled",config:{useOfficialDomain:!1}})}else if(n.key==="companion"){if(!Cn(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Cn(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>es.indexOf(n.key)-es.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function oE(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=ft(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of es)!r.has(i)||e.declaredPermissions[i]?.enabled!==!0||t.valid&&t.permissions[i]?.status==="enabled"||n.push(i==="network"?{key:i,status:"enabled",config:{useOfficialDomain:!1}}:{key:i,status:"enabled",config:{}});return{schema_version:1,revision:e.revision,entries:n}}function Uc(e){const t=ft(e.runtimePermissions),r=cf(e.localDevGrant),n=t.valid?t.permissions:{};for(const a of zr)e.declaredPermissions[a]?.enabled!==!0?delete n[a]:xc.some(c=>c.key===a&&c.access==="declaration")?n[a]={key:a,status:"enabled",config:cE(a,e.declaredPermissions)}:a==="network"&&n.network&&(n.network.config.useOfficialDomain=n.network.status==="enabled"&&n.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(r.valid)for(const a of r.grant.entries)e.declaredPermissions[a.key]?.enabled!==!0||n[a.key]?.status==="enabled"||(n[a.key]=a,i.push(a.key));const s=uf(e.runtimePermissions)&&typeof e.runtimePermissions.revision=="number"&&Number.isSafeInteger(e.runtimePermissions.revision)&&e.runtimePermissions.revision>=0?e.runtimePermissions.revision:void 0;return{runtimePermissions:{schema_version:1,...s===void 0?{}:{revision:s},entries:zr.flatMap(a=>n[a]?[n[a]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function cE(e,t){const r=xc.find(i=>i.key===e);if(!r)return{};const n={};for(const[i,s]of Object.entries(r.config)){if(e==="post"&&s.type==="boolean"){n[i]=t.post?.[i]===!0;continue}s.type==="resource-map"&&(n[i]=i==="resources"?pi(t[e]?.resources):{})}return n}function uf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cn(e,t){return uf(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const En=["identity","profile","steam_account"],uE=/^[a-z][a-z0-9-]{0,31}$/,df=["COMPANION_UNSUPPORTED","COMPANION_PREVIEW_UNSUPPORTED","COMPANION_NOT_DECLARED","COMPANION_TARGET_UNSUPPORTED","COMPANION_NOT_PREPARED","COMPANION_PREPARATION_CANCELLED","COMPANION_DOWNLOAD_FAILED","COMPANION_DESCRIPTOR_UNAVAILABLE","COMPANION_ARCHIVE_INVALID","COMPANION_INTEGRITY_FAILED","COMPANION_ENTRYPOINT_INVALID","COMPANION_USER_CANCELLED","COMPANION_ELEVATION_DENIED","COMPANION_OS_BLOCKED","COMPANION_LAUNCH_FAILED","COMPANION_SESSION_VERSION_MISMATCH","COMPANION_SESSION_OWNERSHIP_LOST","COMPANION_SESSION_EXITED","COMPANION_PIPE_CLOSED","COMPANION_OUTPUT_LIMIT","COMPANION_PROCESS_CRASHED","COMPANION_ATTACHMENT_NOT_FOUND","COMPANION_NOTIFICATION_UNAVAILABLE","COMPANION_TERMINATE_FAILED"];var yu;function Be(e,t,r){function n(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const d=a.prototype,l=Object.keys(d);for(let h=0;h<l.length;h++){const f=l[h];f in c||(c[f]=d[f].bind(c))}}const i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function a(c){var u;const d=r?.Parent?new s:this;n(d,c),(u=d._zod).deferred??(u.deferred=[]);for(const l of d._zod.deferred)l();return d}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class Wn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(yu=globalThis).__zod_globalConfig??(yu.__zod_globalConfig={});const Nu=globalThis.__zod_globalConfig;function Sn(e){return e&&Object.assign(Nu,e),Nu}function dE(e,t){return typeof t=="bigint"?t.toString():t}function lE(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function lf(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const wu=Symbol("evaluating");function gt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==wu)return n===void 0&&(n=wu,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}const ff="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function fE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Du(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hE(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ct(e){return{}}function mE(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const EE={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function jn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function gE(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function hf(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function xi(e){return typeof e=="string"?e:e?.message}function wi(e,t,r){const n=e.message?e.message:xi(e.inst?._zod.def?.error?.(e))??xi(t?.error?.(e))??xi(r.customError?.(e))??xi(r.localeError?.(e))??"Invalid input",{inst:i,continue:s,input:a,...c}=e;return c.path??(c.path=[]),c.message=n,t?.reportInput&&(c.input=a),c}const mf=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,dE,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},pE=Be("$ZodError",mf),Ra=Be("$ZodError",mf,{Parent:Error}),_E=e=>(t,r,n,i)=>{const s=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Wn;if(a.issues.length){const c=new(i?.Err??e)(a.issues.map(u=>wi(u,s,Sn())));throw ff(c,i?.callee),c}return a.value},TE=_E(Ra),AE=e=>async(t,r,n,i)=>{const s=n?{...n,async:!0}:{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const c=new(i?.Err??e)(a.issues.map(u=>wi(u,s,Sn())));throw ff(c,i?.callee),c}return a.value},IE=AE(Ra),bE=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Wn;return s.issues.length?{success:!1,error:new(e??pE)(s.issues.map(a=>wi(a,i,Sn())))}:{success:!0,data:s.value}},Ef=bE(Ra),yE=e=>async(t,r,n)=>{const i=n?{...n,async:!0}:{async:!0};let s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>wi(a,i,Sn())))}:{success:!0,data:s.value}},gf=yE(Ra),NE=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},wE=/^-?\d+$/,DE=/^-?\d+(?:\.\d+)?$/,SE=/^null$/i,Ca=Be("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),pf={number:"number",bigint:"bigint",object:"date"},OE=Be("$ZodCheckLessThan",(e,t)=>{Ca.init(e,t);const r=pf[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ME=Be("$ZodCheckGreaterThan",(e,t)=>{Ca.init(e,t);const r=pf[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),RE=Be("$ZodCheckNumberFormat",(e,t)=>{Ca.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=EE[t.format];e._zod.onattach.push(a=>{const c=a._zod.bag;c.format=t.format,c.minimum=i,c.maximum=s,r&&(c.pattern=wE)}),e._zod.check=a=>{const c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}c<i&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),c>s&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),CE=Be("$ZodCheckStringFormat",(e,t)=>{var r,n;Ca.init(e,t),e._zod.onattach.push(i=>{const s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),LE=Be("$ZodCheckRegex",(e,t)=>{CE.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),PE={major:4,minor:4,patch:3},Ut=Be("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=PE;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const i of n)for(const s of i._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(a,c,u)=>{let d=jn(a),l;for(const h of c){if(h._zod.def.when){if(gE(a)||!h._zod.def.when(a))continue}else if(d)continue;const f=a.issues.length,_=h._zod.check(a);if(_ instanceof Promise&&u?.async===!1)throw new Wn;if(l||_ instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await _,a.issues.length!==f&&(d||(d=jn(a,f)))});else{if(a.issues.length===f)continue;d||(d=jn(a,f))}}return l?l.then(()=>a):a},s=(a,c,u)=>{if(jn(a))return a.aborted=!0,a;const d=i(c,n,u);if(d instanceof Promise){if(u.async===!1)throw new Wn;return d.then(l=>e._zod.parse(l,u))}return e._zod.parse(d,u)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){const d=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(l=>s(l,a,c)):s(d,a,c)}const u=e._zod.parse(a,c);if(u instanceof Promise){if(c.async===!1)throw new Wn;return u.then(d=>i(d,n,c))}return i(u,n,c)}}gt(e,"~standard",()=>({validate:i=>{try{const s=Ef(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return gf(e,i).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),vE=Be("$ZodString",(e,t)=>{Ut.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??NE(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),_f=Be("$ZodNumber",(e,t)=>{Ut.init(e,t),e._zod.pattern=e._zod.bag.pattern??DE,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}}),kE=Be("$ZodNumberFormat",(e,t)=>{RE.init(e,t),_f.init(e,t)}),xE=Be("$ZodNull",(e,t)=>{Ut.init(e,t),e._zod.pattern=SE,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),UE=Be("$ZodNever",(e,t)=>{Ut.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Su(e,t,r){e.issues.length&&t.issues.push(...hf(r,e.issues)),t.value[r]=e.value}const BE=Be("$ZodArray",(e,t)=>{Ut.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const s=[];for(let a=0;a<i.length;a++){const c=i[a],u=t.element._zod.run({value:c,issues:[]},n);u instanceof Promise?s.push(u.then(d=>Su(d,r,a))):Su(u,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function Xs(e,t,r,n,i,s){const a=r in n;if(e.issues.length){if(i&&s&&!a)return;t.issues.push(...hf(r,e.issues))}if(!a&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?a&&(t.value[r]=void 0):t.value[r]=e.value}function HE(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=mE(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function FE(e,t,r,n,i,s){const a=[],c=i.keySet,u=i.catchall._zod,d=u.def.type,l=u.optin==="optional",h=u.optout==="optional";for(const f in t){if(f==="__proto__"||c.has(f))continue;if(d==="never"){a.push(f);continue}const _=u.run({value:t[f],issues:[]},n);_ instanceof Promise?e.push(_.then(p=>Xs(p,r,f,t,l,h))):Xs(_,r,f,t,l,h)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}const zE=Be("$ZodObject",(e,t)=>{if(Ut.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...c};return Object.defineProperty(t,"shape",{value:u}),u}})}const n=lE(()=>HE(t));gt(e._zod,"propValues",()=>{const c=t.shape,u={};for(const d in c){const l=c[d]._zod;if(l.values){u[d]??(u[d]=new Set);for(const h of l.values)u[d].add(h)}}return u});const i=fE,s=t.catchall;let a;e._zod.parse=(c,u)=>{a??(a=n.value);const d=c.value;if(!i(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const l=[],h=a.shape;for(const f of a.keys){const _=h[f],p=_._zod.optin==="optional",y=_._zod.optout==="optional",w=_._zod.run({value:d[f],issues:[]},u);w instanceof Promise?l.push(w.then(N=>Xs(N,c,f,d,p,y))):Xs(w,c,f,d,p,y)}return s?FE(l,d,c,u,n.value,e):l.length?Promise.all(l).then(()=>c):c}});function Ou(e,t,r,n){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const i=e.filter(s=>!jn(s));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(a=>wi(a,n,Sn())))}),t)}const jE=Be("$ZodUnion",(e,t)=>{Ut.init(e,t),gt(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),gt(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),gt(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),gt(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>lf(i.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let s=!1;const a=[];for(const c of t.options){const u=c._zod.run({value:n.value,issues:[]},i);if(u instanceof Promise)a.push(u),s=!0;else{if(u.issues.length===0)return u;a.push(u)}}return s?Promise.all(a).then(c=>Ou(c,n,e,i)):Ou(a,n,e,i)}}),VE=Be("$ZodLiteral",(e,t)=>{if(Ut.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Du(n):n?Du(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,i)=>{const s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}});function Mu(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const GE=Be("$ZodOptional",(e,t)=>{Ut.init(e,t),e._zod.optin="optional",e._zod.optout="optional",gt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),gt(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${lf(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const i=r.value,s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(a=>Mu(a,i)):Mu(s,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),YE=Be("$ZodLazy",(e,t)=>{Ut.init(e,t),gt(e._zod,"innerType",()=>{const r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),gt(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),gt(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),gt(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),gt(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)});function qE(e,t){return new e({type:"string",...Ct()})}function QE(e,t){return new e({type:"number",checks:[],...Ct()})}function WE(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Ct()})}function $E(e,t){return new e({type:"null",...Ct()})}function KE(e,t){return new e({type:"never",...Ct()})}function Te(e,t){return new OE({check:"less_than",...Ct(),value:e,inclusive:!0})}function Ae(e,t){return new ME({check:"greater_than",...Ct(),value:e,inclusive:!0})}function Ie(e,t){return new LE({check:"string_format",format:"regex",...Ct(),pattern:e})}Sn({jitless:!0});function Tf(e){if(e.schema_version!==1||!/^[a-f0-9]{32}$/.test(e.session_id)||!Number.isSafeInteger(e.revision)||e.revision<1||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(e.sdk_version)||!e.declared_permissions||typeof e.declared_permissions!="object"||Array.isArray(e.declared_permissions)||!Array.isArray(e.platforms)||e.platforms.some(r=>!["android","ios","ohos","windows","macos","linux"].includes(r))||new Set(e.platforms).size!==e.platforms.length)throw new Error("开发快照无效");const t={};for(const r of zr){const n=e.declared_permissions[r];if(n){if(typeof n.enabled!="boolean")throw new Error("开发权限声明无效");if(r==="network"){t[r]={enabled:n.enabled,useOfficialDomain:n.useOfficialDomain===!0};continue}if(r==="post"){for(const i of["read","write"])if(n[i]!==void 0&&typeof n[i]!="boolean")throw new Error("开发权限声明无效");t.post={enabled:n.enabled,read:n.read===!0,write:n.write===!0};continue}if(r==="user_game_data"){t[r]={enabled:n.enabled,resources:pi(n.resources)};continue}t[r]={enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!zr.includes(r)))throw new Error("开发权限声明无效");if(e.companion_manifest_sha256!==void 0&&!/^[a-f0-9]{64}$/.test(e.companion_manifest_sha256))throw new Error("开发产物摘要无效");return JSON.stringify({schema_version:1,session_id:e.session_id,revision:e.revision,sdk_version:e.sdk_version,declared_permissions:t,platforms:[...e.platforms].sort(),...e.companion_manifest_sha256?{companion_manifest_sha256:e.companion_manifest_sha256}:{}})}function ZE(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return Tf(t)===e?t:void 0}catch{return}}const Zt=Be("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ut.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>TE(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Ef(e,r,n),e.parseAsync=async(r,n)=>IE(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>gf(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>hE(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),XE=Be("ZodMiniString",(e,t)=>{vE.init(e,t),Zt.init(e,t)});function C(e){return qE(XE)}const Af=Be("ZodMiniNumber",(e,t)=>{_f.init(e,t),Zt.init(e,t)});function re(e){return QE(Af)}const JE=Be("ZodMiniNumberFormat",(e,t)=>{kE.init(e,t),Af.init(e,t)});function be(e){return WE(JE)}const eg=Be("ZodMiniNull",(e,t)=>{xE.init(e,t),Zt.init(e,t)});function ge(e){return $E(eg)}const tg=Be("ZodMiniNever",(e,t)=>{UE.init(e,t),Zt.init(e,t)});function rg(e){return KE(tg)}const ng=Be("ZodMiniArray",(e,t)=>{BE.init(e,t),Zt.init(e,t)});function he(e,t){return new ng({type:"array",element:e,...Ct()})}const ig=Be("ZodMiniObject",(e,t)=>{zE.init(e,t),Zt.init(e,t),gt(e,"shape",()=>t.shape)});function me(e,t){return new ig({type:"object",shape:e,catchall:rg(),...Ct()})}const sg=Be("ZodMiniUnion",(e,t)=>{jE.init(e,t),Zt.init(e,t)});function L(e,t){return new sg({type:"union",options:e,...Ct()})}const ag=Be("ZodMiniLiteral",(e,t)=>{VE.init(e,t),Zt.init(e,t)});function Ne(e,t){return new ag({type:"literal",values:Array.isArray(e)?e:[e],...Ct()})}const og=Be("ZodMiniOptional",(e,t)=>{GE.init(e,t),Zt.init(e,t)});function J(e){return new og({type:"optional",innerType:e})}const cg=Be("ZodMiniLazy",(e,t)=>{YE.init(e,t),Zt.init(e,t)});function ue(e){return new cg({type:"lazy",getter:e})}const de={PcHardwareInfo:me({updatedAt:re(),cpu:J(me({name:C()})),gpu:J(me({name:C()})),memory:J(me({name:J(C()),capacityGiB:J(re())})),motherboard:J(me({name:C()})),disks:J(he(me({name:C()})))}),ArkProfile:me({uid:C(),name:C(),level:re(),avatar:J(ue(()=>de.ArkPlayerAvatar)),characterCount:re(),totalCharacterCount:re(),mainStageProgress:C(),rogueLevel:re(),campaignFullKillCount:re(),tag:C(),observedAt:J(L([C(),re()])),lastOnlineTs:J(L([C(),re()])),registerTs:J(L([C(),re()])),changeTime:J(L([C(),re()])),operators:J(he(ue(()=>de.ArkOperator)))}),ArkPlayerAvatar:me({url:C(),type:C(),id:C()}),ArkOperator:me({characterId:C(),name:C(),profession:C(),evolvePhase:re(),potentialRank:re()}),ArkGachaAnalysis:me({uid:C(),year:re(),total:re(),srCount:re(),upCount:re(),missCount:re(),careerEvaluation:C(),careerIsLucky:L([Ne(!1),Ne(!0)]),pools:he(ue(()=>de.ArkGachaPoolStat)),records:he(ue(()=>de.ArkGachaAnalysisRecord)),luckyLottery:he(re())}),ArkGachaPoolStat:me({poolId:C(),totalCost:re(),ssrCount:re(),ssrCost:re(),records:he(ue(()=>de.ArkGachaAnalysisRecord))}),ArkGachaAnalysisRecord:me({name:C(),timestamp:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),diff:re(),negativeDiff:re(),tag:C(),missUp:L([Ne(!1),Ne(!0)])}),GachaRecord:me({id:C(),name:C(),pool:C(),rarity:re(),timestamp:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),BlackMythWukongSave:me({level:J(re()),newGamePlusCount:J(re()),gameTotalTime:J(re()),playerDeathCount:J(re()),totalMoney:J(C()),meditationList:J(L([ge(),he(re())])),monsterCollectionList:J(L([ge(),he(re())])),returnPointList:J(L([ge(),he(re())])),activatedWeaponIdList:J(L([ge(),he(C())])),activatedEquipIdList:J(L([ge(),he(re())])),magicArtifactList:J(L([ge(),he(re())])),soulSkillIdList:J(L([ge(),he(re())])),huluIdLits:J(L([ge(),he(re())])),wineIdList:J(L([ge(),he(re())])),wineIdPartnerList:J(L([ge(),he(re())])),cropIdList:J(L([ge(),he(re())])),recipeIdList:J(L([ge(),he(re())])),wearedWaeponId:J(C()),wearedMagicArtifact:J(re()),wearedSoulSkill:J(re()),wearedHead:J(re()),wearedUpware:J(re()),wearedArm:J(re()),wearedFoot:J(re()),wearedHulu:J(re()),wearedAccessoryList:J(L([ge(),he(re())])),spellQishu:J(L([ge(),he(re())])),spellShenfa:J(L([ge(),he(re())])),spellHaomao:J(L([ge(),he(re())])),spellBianshen:J(L([ge(),he(re())])),bossRushBossgroup:J(ue(()=>de.BlackMythWukongBossRushData)),bossRushRefight:J(ue(()=>de.BlackMythWukongBossRefightData))}),BlackMythWukongBossRushData:me({bossGroups:J(L([ge(),he(ue(()=>de.BlackMythWukongBossRushRecord))]))}),BlackMythWukongBossRushRecord:me({bossGroupId:J(re()),isPassed:J(L([Ne(!1),Ne(!0)])),bestRecords:J(L([ge(),he(ue(()=>de.BlackMythWukongBattleRecord))])),encounterBossIndex:J(re()),battleCount:J(re())}),BlackMythWukongBattleRecord:me({battleId:J(C()),battleData:J(ue(()=>de.BlackMythWukongBattleData))}),BlackMythWukongBattleData:me({totalTime:J(re()),score:J(re()),debuffList:J(L([ge(),he(re())])),targetId:J(re()),archiveTime:J(C()),roleBase:J(ue(()=>de.BlackMythWukongRoleBase)),battleStyleInfo:J(ue(()=>de.BlackMythWukongBattleStyleInfo)),damageInfo:J(ue(()=>de.BlackMythWukongDamageInfo))}),BlackMythWukongRoleBase:me({level:J(re()),atk:J(re()),hpMax:J(re()),staminaMax:J(re()),mpMax:J(re())}),BlackMythWukongBattleStyleInfo:me({spellList:J(L([ge(),he(ue(()=>de.BlackMythWukongCast))])),fabaoInfo:J(ue(()=>de.BlackMythWukongCast)),soulInfo:J(ue(()=>de.BlackMythWukongCast)),itemCount:J(re()),wineCount:J(re()),rollCount:J(re()),defuseCount:J(re()),fourPeCount:J(re())}),BlackMythWukongCast:me({castId:J(re()),castCount:J(re())}),BlackMythWukongDamageInfo:me({totalDamage:J(L([C(),re()])),hightestDamage:J(L([C(),re()])),criticalDmgRate:J(re()),totalBeDamaged:J(L([C(),re()])),criticalDmgTotal:J(L([C(),re()])),elemDotDmgTotal:J(L([C(),re()])),elemDotDmgRate:J(re())}),BlackMythWukongBossRefightData:me({bossList:J(L([ge(),he(ue(()=>de.BlackMythWukongBossRefightRecord))]))}),BlackMythWukongBossRefightRecord:me({bossId:J(re()),passedMaxLevel:J(re()),lastChallengeLevel:J(re()),bestRecords:J(L([ge(),he(ue(()=>de.BlackMythWukongBattleRecord))])),refightStatisticsList:J(L([ge(),he(ue(()=>de.BlackMythWukongRefightStatistic))]))}),BlackMythWukongRefightStatistic:me({challengeLevel:J(re()),battleCount:J(re())}),TaskBarHeroSave:me({update_time:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),game_version:C(),account_version:C(),play_time:re(),last_saved_time:C(),common:ue(()=>de.TaskBarHeroCommon),summary:ue(()=>de.TaskBarHeroSummary),heroes:L([ge(),he(ue(()=>de.TaskBarHeroHero))]),rune_save_data:L([ge(),he(ue(()=>de.TaskBarHeroRune))]),pets:L([ge(),he(ue(()=>de.TaskBarHeroPet))]),attributes:L([ge(),he(ue(()=>de.TaskBarHeroAttribute))]),inventory_slots:L([ge(),he(ue(()=>de.TaskBarHeroItemSlot))]),stash_slots:L([ge(),he(ue(()=>de.TaskBarHeroItemSlot))]),item_instances:L([ge(),he(ue(()=>de.TaskBarHeroItemInstance))]),values:ue(()=>de.TaskBarHeroValueSummary)}),TaskBarHeroCommon:me({max_completed_stage:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_key:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_wave:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),arranged_hero_keys:L([ge(),he(L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),arranged_pet_key:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroSummary:me({max_hero_level:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),learned_rune_count:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unlocked_hero:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total_hero:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_count:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inventory_slots:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stash_slots:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroHero:me({hero_key:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),hero_level:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:L([Ne(!1),Ne(!0)]),hero_exp:re(),ability_point:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),allocated_hero_ability_point:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),equipped_item_ids:L([ge(),he(C())]),equipped_skill_keys:L([ge(),he(L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),unlocked_attribute_group_keys:L([ge(),he(L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]))])}),TaskBarHeroRune:me({rune_key:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroPet:me({pet_key:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:L([Ne(!1),Ne(!0)])}),TaskBarHeroAttribute:me({key:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroItemSlot:me({index:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_unique_id:C(),is_unlock:L([Ne(!1),Ne(!0)]),is_unlocked_by_rune:L([Ne(!1),Ne(!0)])}),TaskBarHeroItemInstance:me({item_key:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unique_id:C(),is_chaotic:L([Ne(!1),Ne(!0)]),is_blocked:L([Ne(!1),Ne(!0)]),is_server_pending_item:L([Ne(!1),Ne(!0)]),enchant_count:L([ge(),he(L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),enchant_data:L([ge(),he(ue(()=>de.TaskBarHeroEnchantData))]),item_get_source_type:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),decoration_applied_total_count:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),engraving_applied_total_count:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inscription_applied_total_count:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroEnchantData:me({stat_mod_key:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),tier:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),value:re(),recipe_type:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),mod_type:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),material_key:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stat_type:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroValueSummary:me({market_value:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),price_state:C(),currency:C()}),PhantomBladeZeroSave:me({defaultSlot:C(),slots:he(ue(()=>de.PhantomBladeZeroSaveSlot))}),PhantomBladeZeroSaveSlot:me({slot:C(),head:ue(()=>de.PhantomBladeZeroSlotHead),firstClear:ue(()=>de.PhantomBladeZeroSlotFirstClear),progress:ue(()=>de.PhantomBladeZeroSlotProgress),combat:ue(()=>de.PhantomBladeZeroSlotCombat),achievements:ue(()=>de.PhantomBladeZeroSlotAchievementSummary),bosses:ue(()=>de.PhantomBladeZeroSlotBossSummary),collectibles:ue(()=>de.PhantomBladeZeroSlotCollectibles),quest_details:L([ge(),ue(()=>de.PhantomBladeZeroQuestDetails)]),inventory_details:L([ge(),he(ue(()=>de.PhantomBladeZeroInventoryItem))]),detail:ue(()=>de.PhantomBladeZeroSlotDetail)}),PhantomBladeZeroSlotHead:me({saveTime:C(),currentLevel:C(),cycle:C(),difficulty:ue(()=>de.PhantomBladeZeroSlotDifficulty)}),PhantomBladeZeroSlotDifficulty:me({raw:re(),name:C()}),PhantomBladeZeroSlotFirstClear:me({clearDate:ue(()=>de.PhantomBladeZeroUnavailableValue),cycles:L([ge(),he(ue(()=>de.PhantomBladeZeroClearanceRecord))])}),PhantomBladeZeroUnavailableValue:me({value:ge(),reason:C()}),PhantomBladeZeroClearanceRecord:me({Cycle:J(L([ge(),re()])),Ending:re(),Difficulty:re(),GameTime:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),Completion:re(),DiedTimes:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotProgress:me({playTimeSeconds:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),playTime:C(),lastLaunch:ue(()=>de.PhantomBladeZeroUnavailableValue),narrativePercentage:re(),chapter:C(),remainingDays:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCombat:me({loadout:J(ue(()=>de.PhantomBladeZeroSlotLoadout)),totalDeaths:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),cycleDeaths:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bossKillTotal:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),currentMainWeapon:J(L([ge(),ue(()=>de.PhantomBladeZeroNamedItem)])),mainWeapon:ue(()=>de.PhantomBladeZeroCollectionCount),currentShaqi:J(L([ge(),ue(()=>de.PhantomBladeZeroNamedItem)])),shaqi:ue(()=>de.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroSlotLoadout:me({states:J(L([ge(),he(ue(()=>de.PhantomBladeZeroLoadoutState))])),main_weapons:L([ge(),he(C())]),shaqi_weapons:L([ge(),he(C())]),accessory_ids:L([ge(),he(C())]),top_medicine:C(),bottom_medicine:C(),current_weapon_index:re(),current_shaqi_weapon_index:re()}),PhantomBladeZeroLoadoutState:me({category:C(),id:C(),level:J(re()),soul_forged:J(L([Ne(!1),Ne(!0)])),reincarnation_count:J(re())}),PhantomBladeZeroNamedItem:me({id:C(),name:C()}),PhantomBladeZeroCollectionCount:me({unknown:J(L([C(),re()])),done:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotAchievementSummary:me({unlocked:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:C()}),PhantomBladeZeroSlotBossSummary:me({groups:L([ge(),he(ue(()=>de.PhantomBladeZeroBossGroup))])}),PhantomBladeZeroBossGroup:me({map:C(),mapName:C(),count:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bosses:L([ge(),he(ue(()=>de.PhantomBladeZeroBoss))])}),PhantomBladeZeroBoss:me({id:C(),classPath:C(),map:C(),mapName:C(),encountered:L([Ne(!1),Ne(!0)]),killed:L([Ne(!1),Ne(!0)]),kill:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),records:L([ge(),he(ue(()=>de.PhantomBladeZeroBossRecord))])}),PhantomBladeZeroBossRecord:me({cycle:C(),diff:C(),diffName:C(),kill:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCollectibles:me({overall:ue(()=>de.PhantomBladeZeroCollectionSummary),craneBellCount:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),byBigMap:L([ge(),he(ue(()=>de.PhantomBladeZeroBigMapProgress))]),currentChapter:ue(()=>de.PhantomBladeZeroChapterProgress)}),PhantomBladeZeroCollectionSummary:me({bell:ue(()=>de.PhantomBladeZeroCollectionCount),weapon:ue(()=>de.PhantomBladeZeroCollectionCount),shaqi:ue(()=>de.PhantomBladeZeroCollectionCount),accessory:ue(()=>de.PhantomBladeZeroCollectionCount),medicine:ue(()=>de.PhantomBladeZeroCollectionCount),challenge:ue(()=>de.PhantomBladeZeroCollectionCount),hupo:ue(()=>de.PhantomBladeZeroCollectionCount),heishi:ue(()=>de.PhantomBladeZeroCollectionCount),flower:ue(()=>de.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroBigMapProgress:me({unknown:J(L([C(),re()])),mapID:C(),name:C(),pct:re(),done:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),subMaps:L([ge(),he(C())])}),PhantomBladeZeroChapterProgress:me({unknown:J(L([C(),re()])),mapID:C(),pct:re(),done:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:C()}),PhantomBladeZeroQuestDetails:me({CurrentMainQuestPath:C(),CurrentTutorialQuestPath:C(),TrackedQuestPath:C(),TrackedBranchID:C(),TrackedTaskPointID:C(),ManualTrackingOptOut:L([Ne(!1),Ne(!0)]),NarrativeSavedQuests:L([ge(),he(ue(()=>de.PhantomBladeZeroQuest))])}),PhantomBladeZeroQuest:me({QuestClass:C(),QuestCompletion:C(),QuestBranches:L([ge(),he(ue(()=>de.PhantomBladeZeroQuestBranch))]),CompletedBranches:L([ge(),he(C())]),ReachedStateNames:L([ge(),he(C())])}),PhantomBladeZeroQuestBranch:me({BranchID:C(),TasksProgress:L([ge(),he(L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),BranchType:C()}),PhantomBladeZeroInventoryItem:me({id:C(),amount:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotDetail:me({bell:L([ge(),he(ue(()=>de.PhantomBladeZeroBellDetail))]),weapon:L([ge(),he(ue(()=>de.PhantomBladeZeroItemDetail))]),shaqi:L([ge(),he(ue(()=>de.PhantomBladeZeroItemDetail))]),accessory:L([ge(),he(ue(()=>de.PhantomBladeZeroItemDetail))]),medicine:L([ge(),he(ue(()=>de.PhantomBladeZeroItemDetail))]),challenge:L([ge(),he(ue(()=>de.PhantomBladeZeroChallengeDetail))]),hupo:L([ge(),he(ue(()=>de.PhantomBladeZeroWorldItemDetail))]),heishi:L([ge(),he(ue(()=>de.PhantomBladeZeroWorldItemDetail))]),flower:L([ge(),he(ue(()=>de.PhantomBladeZeroItemDetail))]),achievements:L([ge(),he(ue(()=>de.PhantomBladeZeroAchievementDetail))])}),PhantomBladeZeroBellDetail:me({unknown:J(L([Ne(!1),Ne(!0)])),id:C(),done:L([Ne(!1),Ne(!0)]),equip:L([Ne(!1),Ne(!0)])}),PhantomBladeZeroItemDetail:me({level:J(re()),soul_forged:J(L([Ne(!1),Ne(!0)])),reincarnation_count:J(re()),unknown:J(L([Ne(!1),Ne(!0)])),id:C(),name:C(),done:L([Ne(!1),Ne(!0)]),equip:L([Ne(!1),Ne(!0)]),locs:L([ge(),he(ue(()=>de.PhantomBladeZeroLocation))])}),PhantomBladeZeroLocation:me({map:C(),mapName:C(),x:re(),y:re(),z:re()}),PhantomBladeZeroChallengeDetail:me({key:J(C()),unknown:J(L([Ne(!1),Ne(!0)])),index:L([be().check(Ae(-9007199254740991),Te(9007199254740991)),C().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),guids:L([ge(),he(C())]),done:L([Ne(!1),Ne(!0)]),locs:L([ge(),he(ue(()=>de.PhantomBladeZeroLocation))])}),PhantomBladeZeroWorldItemDetail:me({key:J(C()),unknown:J(L([Ne(!1),Ne(!0)])),id:C(),saveGuid:C(),mobDomain:C(),done:L([Ne(!1),Ne(!0)]),locs:L([ge(),he(ue(()=>de.PhantomBladeZeroLocation))])}),PhantomBladeZeroAchievementDetail:me({id:C(),name:C(),desc:C(),grade:C(),hidden:L([Ne(!1),Ne(!0)]),done:L([Ne(!1),Ne(!0)])}),UserGameDataSaveFilePage:me({items:he(ue(()=>de.UserGameDataSaveInfo)),hasMore:Ne(!1)}),UserGameDataSaveInfo:me({saveId:C(),createdAt:C(),files:he(ue(()=>de.UserGameDataSaveFileInfo))}),UserGameDataSaveFileInfo:me({fileId:C(),name:C(),sizeBytes:re(),modifiedAt:C()})},ug=new Map([["account.pc_hardware",ue(()=>de.PcHardwareInfo)],["ark.profile",ue(()=>de.ArkProfile)],["ark.gacha-analysis",ue(()=>de.ArkGachaAnalysis)],["ark.gacha-record-page",me({items:he(ue(()=>de.GachaRecord)),nextCursor:J(C()),hasMore:L([Ne(!1),Ne(!0)]),total:J(re())})],["black_myth_wukong.save",ue(()=>de.BlackMythWukongSave)],["task_bar_hero.save",ue(()=>de.TaskBarHeroSave)],["phantom_blade_zero.save",ue(()=>de.PhantomBladeZeroSave)],["save-file-page",ue(()=>de.UserGameDataSaveFilePage)]]);function dg(e,t){return ug.get(e)?.safeParse(t).success??!1}pr.map(e=>e.method);function ts(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function ve(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:ts()}function If(e){if(e.source!=="runtime-private"||e.credentials!=="omit"||e.route!=="game-save"||e.target.kind!=="absolute-url"||e.method!=="GET"||e.redirectPolicy!=="error"||e.data!==void 0||e.params!==void 0||e.headers!==void 0)return!1;try{const t=new URL(e.target.url);return t.protocol==="https:"&&t.hostname==="heybox-beijing-1251007209.cos.ap-beijing.myqcloud.com"&&!t.port&&!t.username&&!t.password&&!t.hash&&/^\/cloud_archive\/[0-9]{1,20}\.zip$/.test(t.pathname)&&t.searchParams.has("q-signature")}catch{return!1}}const bf="METHOD_FORBIDDEN";function Ot(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=bf,t}class Je extends Error{code="HOST_REQUEST_UNSUPPORTED";constructor(t="当前 Host 不支持该请求形状",r){super(t),this.name="HostRequestUnsupportedError",r&&"cause"in r&&Object.defineProperty(this,"cause",{configurable:!0,enumerable:!1,value:r.cause}),Object.setPrototypeOf(this,new.target.prototype)}}const lg=/^[A-Za-z0-9_-]{1,64}$/,Ru=1e3;function yf(e){return lg.test(e)?e:Eg(e)}function fg(e){return`id_${yf(e.trim())}`}function Wr(e,t){return`hb_miniprogram_${e}_${t}`}function Ui(e){return`hb_miniprogram_keys_${e}`}const hg="hb_user_game_data_consent_";function mg(e){return`${hg}${e}`}function Eg(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}const gg=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 Bc(e){const t=new TextEncoder().encode(e),r=Math.ceil((t.length+9)/64)*64,n=new Uint8Array(r);n.set(t),n[t.length]=128,new DataView(n.buffer).setUint32(r-4,t.length*8,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),s=new Uint32Array(64),a=new DataView(n.buffer);for(let c=0;c<r;c+=64){for(let w=0;w<16;w+=1)s[w]=a.getUint32(c+w*4,!1);for(let w=16;w<64;w+=1){const N=s[w-15],O=s[w-2],I=Ht(N,7)^Ht(N,18)^N>>>3,H=Ht(O,17)^Ht(O,19)^O>>>10;s[w]=s[w-16]+I+s[w-7]+H>>>0}let[u,d,l,h,f,_,p,y]=i;for(let w=0;w<64;w+=1){const N=y+(Ht(f,6)^Ht(f,11)^Ht(f,25))+(f&_^~f&p)+gg[w]+s[w]>>>0,O=(Ht(u,2)^Ht(u,13)^Ht(u,22))+(u&d^u&l^d&l);y=p,p=_,_=f,f=h+N>>>0,h=l,l=d,d=u,u=N+O>>>0}[u,d,l,h,f,_,p,y].forEach((w,N)=>{i[N]=i[N]+w>>>0})}return Array.from(i,c=>c.toString(16).padStart(8,"0")).join("")}function Ht(e,t){return e>>>t|e<<32-t}const pg=Object.freeze({upload:"你允许读取的数据可能会被上传至开发者服务器。",no_network:"此小程序未获准将你允许读取的数据上传至开发者服务器。"});function _g(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null||Array.isArray(t))return;const r=t;if(r.schema_version!==1||typeof r.records!="object"||r.records===null||Array.isArray(r.records))return;const n={};for(const[i,s]of Object.entries(r.records)){if(typeof s!="object"||s===null||Array.isArray(s))return;const a=s;if(a.decision!=="ask"&&a.decision!=="allow"&&a.decision!=="deny"||typeof a.revision!="number"||!Number.isSafeInteger(a.revision)||a.revision<1||a.consentFingerprint!==void 0&&!Ig(a.consentFingerprint))return;n[i]={decision:a.decision,revision:a.revision,...a.decision==="allow"&&a.consentFingerprint!==void 0?{consentFingerprint:a.consentFingerprint}:{}}}return{schema_version:1,records:n}}function Tg(e){return Bc(`${e.miniProgramId}\0${e.userId}\0${e.environment}`).slice(0,32)}function Ag(e){const t=e.miniProgramId?.trim(),r=e.userId?.trim(),n=e.environment?.trim();if(!t||!r||!n)throw Object.assign(new Error("无法确定用户数据许可作用域"),{code:"INVALID_STATE"});return Object.freeze({miniProgramId:t,userId:r,environment:n})}function Ig(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function ke(e,t,r){return{code:e,message:t,data:r}}function Js(e){return bg(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?ke("RUNTIME_ERROR",e.message):ke("UNKNOWN_ERROR","小程序运行时异常",e)}function bg(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}const wr=["account.getCurrentUserId","account.onChange","storage.getRaw","storage.setRaw"],Qa=[...wr,"network.request"],Ir=["roomSocket.connect","account.getCurrentUserId","account.onChange"],Cu={"post.get":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.list":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.delete":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.setLiked":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.openEditor":["account.getCurrentUserId","account.onChange","network.request","presentation.openPostCommentEditor"],"post.watch":["account.getCurrentUserId","account.onChange","network.request"],"post.setLiked":["account.getCurrentUserId","account.onChange","network.request"],"post.setFavorited":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.list":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.sync":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.readParsedData":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.getFile":["account.getCurrentUserId","account.onChange","network.request","network.stream","files.transfer","files.access"],[ps]:["workspaceCards.requestRefresh"],[_s]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[Ts]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[As]:["account.getCurrentUserId","account.onChange","network.request"],[Is]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[bs]:["account.getCurrentUserId","account.onChange","network.request"],[ys]:["account.getCurrentUserId","account.onChange","network.request"],[Ns]:["account.getCurrentUserId","account.onChange","network.request"],[ws]:["presentation.setClipboard"],[Ds]:["presentation.showShareMenu"],[Ss]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Os]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Br]:["presentation.applyOrientation"],[Ms]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Rs]:["presentation.setNavigationBarStyle"],[ci]:["storage.getRaw"],[ui]:["storage.setRaw"],[Cs]:["network.request"],[Ls]:["network.stream","files.transfer","files.access"],[Ps]:["network.upload","files.access"],[vs]:["files.external"],[ks]:["files.external"],[xs]:["files.save"],[di]:["files.access"],[li]:["files.removeFile"],[Us]:["files.access"],[fi]:["files.access"],[Bs]:["files.access"],[hi]:["files.access"],[Hs]:["files.access"],[mi]:["files.access"],[Fs]:["files.access"],[Ei]:["files.removeDirectory"],[zs]:["files.access"],[js]:["files.access"],[gi]:["media.pick"],[oi]:["presentation.showAppreciation"],[Vs]:["presentation.showToast"],[Gs]:["presentation.showLoading"],[Ys]:["presentation.hideLoading"],[qs]:["presentation.vibrate"],[Qs]:["presentation.setClipboard"],[Ws]:["protocol.invoke"],[$s]:["presentation.close"],[Ks]:["presentation.reload"],[Zs]:["presentation.openAppPage"],[tr]:["account.getCurrentUserId","account.onChange","network.request"],[vt]:["account.onChange","network.request"],[gr]:["account.getCurrentUserId","account.onChange","network.request"],[Hr]:["account.getCurrentUserId","account.onChange","network.request"],[qt]:["account.onChange","network.request"],[Ro]:Ir,[Co]:Ir,[Lo]:Ir,[Po]:Ir,[vo]:Ir,[ko]:Ir,[xo]:Ir,[fn]:["account.getCurrentUserId","account.onChange","network.request"],[hn]:["account.getCurrentUserId","account.onChange","network.request"],[mn]:["account.getCurrentUserId","account.onChange","network.request"],[Fr]:["account.getCurrentUserId","account.onChange","network.request"],[pa]:["companion.getInfo"],[_a]:["companion.getPreparationStatus"],[Ta]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[Aa]:["companion.cancelPreparation"],[Ia]:["companion.getActiveSession"],[ba]:["companion.getInfo","companion.launch"],[ya]:["companion.session.write"],[Na]:["companion.session.closeStdin"],[wa]:["companion.session.terminate"],[Da]:["companion.session.ackOutput"],[Sa]:["companion.openAttachment"],[Oa]:["companion.showNotification"],[Oc]:wr,[Es]:Qa,[Qn]:Qa,[gs]:[...Qa,"files.sandbox","files.removeFile","network.stream","files.transfer"],[Mc]:[...wr,"presentation.confirmDataPermission"],[Rc]:wr,[Cc]:wr,[Lc]:[...wr,"presentation.openDataPermissions"],[Pc]:wr},yg=new Set([oi]);function Nf(e,t){if(t[e]!==!0)throw yg.has(e)?ke("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):Ot(e)}const Ng=32*1024*1024,wg=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Dg(e){if(e.mode==="request-only")return{network:{request:(n,i)=>e.request(n,i)}};if(e.mode==="override-request")return{network:{request:(n,i)=>e.request(n,i)},...e.stream===void 0?{}:{stream:e.stream}};const{consume:t,stream:r}=e;return{stream:r,network:{async request(n,i){const s=await r.open(n,i);let a;try{const c=await t(s.body,{maxBytes:Ng},i);return Sg(s,c)}catch(c){throw a=c,c}finally{try{await r.release(s.body)}catch(c){if(a===void 0)throw c}}}}}}function Sg(e,t){const r=Object.fromEntries(Object.entries(e.headers).map(([n,i])=>[n,i.join(", ")]));return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:r,data:Og(t,Rg(e,"content-type"))}}function Og(e,t){Mg(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new Je("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!wg.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function Mg(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new Je(`Host network response 不支持 charset=${t}`)}function Rg(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function le(e){return typeof e=="function"}function Lu(e){return(...t)=>{throw Ot(e)}}function Ze(e){return async(...t)=>{throw Ot(e)}}const Cg=(e,t)=>{},Lg=()=>()=>{};function Pg(e){const t={request:le(e.network?.request)?e.network.request.bind(e.network):Ze("network.request")},r={...le(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:le(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):Ze("account.getCurrentUserId"),ensureAuthenticated:le(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Ze("account.ensureAuthenticated"),onChange:le(e.account?.onChange)?e.account.onChange.bind(e.account):Lg},n={...e.storage?.withLock?{withLock:e.storage.withLock.bind(e.storage)}:{},getRaw:le(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Ze("storage.getRaw"),setRaw:le(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Ze("storage.setRaw")},i={...le(e.presentation?.showSteamLoginRequired)?{showSteamLoginRequired:e.presentation.showSteamLoginRequired.bind(e.presentation)}:{},...le(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...le(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:le(e.presentation?.close)?e.presentation.close.bind(e.presentation):Ze("presentation.close"),reload:le(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Ze("presentation.reload"),openAppPage:le(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Ze("presentation.openAppPage"),openWindow:le(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Ze("presentation.openWindow"),getViewportMetrics:le(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):Lu("presentation.getViewportMetrics"),getNavigationBarHeight:le(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):Lu("presentation.getNavigationBarHeight"),setNavigationBarStyle:le(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Ze("presentation.setNavigationBarStyle"),showShareMenu:le(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Ze("presentation.showShareMenu"),setScreenshotChromeHidden:le(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):Cg,supportsLongScreenshot:e.presentation?.supportsLongScreenshot===!0,captureAndShare:le(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Ze("presentation.captureAndShare"),openPostCommentEditor:le(e.presentation?.openPostCommentEditor)?e.presentation.openPostCommentEditor.bind(e.presentation):void 0,showAppreciation:le(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw ke("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:le(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Ze("presentation.showToast"),showLoading:le(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Ze("presentation.showLoading"),hideLoading:le(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Ze("presentation.hideLoading"),vibrate:le(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Ze("presentation.vibrate"),setClipboard:le(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Ze("presentation.setClipboard")},s=le(e.storageDiagnostics?.listRaw)?{listRaw:e.storageDiagnostics.listRaw.bind(e.storageDiagnostics)}:void 0,a=Object.fromEntries(["getInfo","getPreparationStatus","prepare","cancelPreparation","getActiveSession","launch","write","closeStdin","terminate","ackOutput","openAttachment","showNotification"].map(u=>[u,le(e.companion?.[u])?e.companion[u].bind(e.companion):Ze(`companion.${u}`)]));le(e.companion?.onSessionEvent)&&(a.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const c={invoke:le(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):Ze("protocol.invoke")};return{network:t,roomSocket:e.roomSocket,...e.workspaceCards?{workspaceCards:e.workspaceCards}:{},account:r,storage:n,presentation:i,companion:a,protocol:c,...e.files===void 0?{}:{files:e.files},...e.picker===void 0?{}:{picker:e.picker},...e.media===void 0?{}:{media:e.media},...e.transfer===void 0?{}:{transfer:e.transfer},...e.scopedStorage?{scopedStorage:e.scopedStorage}:{},...s?{storageDiagnostics:s}:{}}}function vg(e,t={}){const r=kg(e.files?.sandbox),n=le(e.picker?.pickFiles)&&le(e.picker?.pickDirectory),i=le(e.picker?.saveFile),s=r||n||i||le(e.companion?.openAttachment),a=r?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":le(e.account?.getAccountKey),"account.getCurrentUserId":le(e.account?.getCurrentUserId),"account.ensureAuthenticated":le(e.account?.ensureAuthenticated),"account.onChange":le(e.account?.onChange),"roomSocket.connect":le(e.roomSocket?.connect),"network.request":le(e.network?.request),"network.stream":le(e.transfer?.network.open)&&le(e.transfer?.network.release),"network.upload":le(e.transfer?.upload?.upload),"files.sandbox":r,"files.external":n,"files.save":i,"files.access":s,"files.removeFile":le(a?.remove),"files.removeDirectory":le(e.files?.sandbox.remove),"files.transfer":le(e.transfer?.files.writeResource),"media.pick":le(e.media?.pick),"storage.getRaw":le(e.scopedStorage?.get)||le(e.storage?.getRaw),"storage.setRaw":le(e.scopedStorage?.set)||le(e.storage?.setRaw),"presentation.close":le(e.presentation?.close),"presentation.reload":le(e.presentation?.reload),"presentation.openAppPage":le(e.presentation?.openAppPage),"presentation.applyOrientation":le(e.presentation?.applyOrientation),"presentation.openWindow":le(e.presentation?.openWindow),"presentation.getViewportMetrics":le(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":le(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":le(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":le(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":le(e.presentation?.captureAndShare),"presentation.openPostCommentEditor":le(e.presentation?.openPostCommentEditor),"presentation.showAppreciation":le(e.presentation?.showAppreciation),"presentation.showToast":le(e.presentation?.showToast),"presentation.showLoading":le(e.presentation?.showLoading),"presentation.hideLoading":le(e.presentation?.hideLoading),"presentation.vibrate":le(e.presentation?.vibrate),"presentation.setClipboard":le(e.presentation?.setClipboard),"workspaceCards.requestRefresh":le(e.workspaceCards?.requestRefresh),"companion.getInfo":le(e.companion?.getInfo),"companion.getPreparationStatus":le(e.companion?.getPreparationStatus),"companion.prepare":le(e.companion?.prepare),"companion.cancelPreparation":le(e.companion?.cancelPreparation),"companion.getActiveSession":le(e.companion?.getActiveSession),"companion.launch":le(e.companion?.launch),"companion.session.write":le(e.companion?.write),"companion.session.closeStdin":le(e.companion?.closeStdin),"companion.session.terminate":le(e.companion?.terminate),"companion.session.ackOutput":le(e.companion?.ackOutput),"companion.openAttachment":le(e.companion?.openAttachment),"companion.showNotification":le(e.companion?.showNotification),"protocol.invoke":le(e.protocol?.invoke),"presentation.confirmDataPermission":t.hasUserDataPresentation===!0,"presentation.openDataPermissions":t.hasUserDataSettings===!0}}function kg(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&le(t.file)&&le(t.directory)&&le(t.create)&&le(t.stat)&&le(t.list)}function Pu(e,t){return t?.[e]!==!1}function xg(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function Ug(e,t={}){const r={};for(const n of Object.keys(Cu)){const s=Cu[n].every(c=>e[c]),a=!xg(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=Pu(n,t.callerCapabilities)&&Pu(n,t.hostCapabilities)&&s&&a}return r}function wf(e={},t={}){const r=vg(e,t),n=Ug(r,t);return{ports:Pg(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function Ue(e,t,r){if(!t||t===e.signal)return r===void 0?e:{...e,requestId:r};const n=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):Bg(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function Bg(e,t){const r=new AbortController,n=()=>{e.removeEventListener("abort",s),t.removeEventListener("abort",a)},i=c=>{r.signal.aborted||(n(),r.abort(c.reason))},s=()=>i(e),a=()=>i(t);return e.aborted?i(e):t.aborted?i(t):(e.addEventListener("abort",s,{once:!0}),t.addEventListener("abort",a,{once:!0})),r.signal}function Hg(e){if(!e||typeof e!="object"||e.lifecycle!=="cleanup")return!1;const t=e.signal;return!!t&&typeof t=="object"&&typeof t.aborted=="boolean"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"}const Fg=4,zg=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],jg=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),Vg=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1","/user_miniprogram/cloud/rooms"],Gg=["/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 Yg(e,t){const r=Wg(e);return r===null||vu(r,Vg)?!0:t&&vu(r,Gg)}function qg(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return zg.some(r=>t===r||t.endsWith(`.${r}`))}function Qg(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||jg.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Wg(e){let t=e;for(let r=0;r<Fg;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return ku(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return ku(t)}function vu(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function ku(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function $g(e){if(typeof e!="string"||e!==e.trim()||e.length>253)return;const t=e.toLowerCase();if(!(!t.includes(".")||/^\d+(?:\.\d+)*$/.test(t))&&t.split(".").every(r=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(r))&&!(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")))return t}function Df(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw Wa("网络策略格式无效");const t=e,r=t.entries===void 0?[]:t.entries;if(!Number.isSafeInteger(t.revision)||t.revision<1||t.enforcement!=="approved_domains"&&t.enforcement!=="restricted"||!Array.isArray(r)||r.length>20)throw Wa("网络策略格式无效");const n=new Set;for(const i of r){const s=$g(i&&typeof i=="object"?i.domain:void 0);if(!s)throw Wa("网络策略包含无效域名");n.add(s)}return Object.freeze({revision:t.revision,enforcement:t.enforcement,entries:Object.freeze([...n].sort().map(i=>Object.freeze({domain:i})))})}function Wa(e){return Object.assign(new TypeError(e),{code:"NETWORK_POLICY_INVALID"})}function xu(e){return e instanceof Je?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function Se(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(ts());let n;try{n=e()}catch(i){return Promise.reject(xu(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(ts())):new Promise((i,s)=>{let a=!1;const c=d=>{a||(a=!0,t.removeEventListener("abort",u),d())},u=()=>c(()=>s(ts()));t.addEventListener("abort",u,{once:!0}),Promise.resolve(n).then(d=>c(()=>i(d)),d=>c(()=>s(xu(d))))})}async function Kg(e,t,r){ve(r);const i=e.ownerDocument.defaultView;if(!i||!e.isConnected)throw new Error("长图容器不可用");const s=e.getAttribute("style"),a=i.scrollX,c=i.scrollY,u=e.getBoundingClientRect().width,d=()=>{s===null?e.removeAttribute("style"):e.setAttribute("style",s),i.scrollTo(a,c)};try{e.style.setProperty("width",`${u}px`,"important"),e.style.setProperty("height",`${t.top+t.height}px`,"important"),e.style.setProperty("min-height","0","important"),e.style.setProperty("max-height","none","important"),i.scrollTo(0,0),await Se(()=>new Promise(h=>i.requestAnimationFrame(()=>i.requestAnimationFrame(()=>h()))),r);const l=e.getBoundingClientRect();if(l.height+1<t.top+t.height||l.width+1<t.left+t.width||l.left<0||l.top<0)throw new Error("宿主布局无法容纳长图");for(let h=e.parentElement;h;h=h.parentElement){const f=i.getComputedStyle(h),_=h.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(f.overflowY)&&(l.top+t.top<_.top-1||l.top+t.top+t.height>_.bottom+1))throw new Error("宿主布局无法容纳长图:祖先容器存在纵向裁剪")}return{rect:{...t,left:t.left+l.left,top:t.top+l.top},restore:d}}catch(l){throw d(),l}}function Zg(e,t,r,n=1e4){const i=new AbortController;return new Promise((s,a)=>{let c=!1;const u=h=>{c||(c=!0,clearTimeout(l),r.signal.removeEventListener("abort",d),i.abort(h),a(h))},d=()=>{i.abort(),u({code:"NETWORK_POLICY_CHANGED",message:"网络策略初始化已取消"})},l=setTimeout(()=>u({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 网络策略初始化超时"}),n);if(r.signal.addEventListener("abort",d,{once:!0}),r.signal.aborted){d();return}Promise.resolve().then(()=>e.activate(t,{signal:i.signal})).then(h=>{if(typeof h!="function"){u({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 未完成严格网络策略初始化"});return}if(c){try{h()}catch{}return}c=!0,clearTimeout(l),s(()=>{r.signal.removeEventListener("abort",d),i.abort(),h()})},u)})}function Sf(e,t){return Xg(t)??Jg(e.pathname)}function Xg(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Jg(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const ep=2,Of="allow-scripts allow-same-origin allow-pointer-lock",tp="",rp="no-referrer";function np(e=Of){return!e.split(/\s+/).includes("allow-same-origin")}function Uu(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const ip=new Set(["javascript:","data:","blob:","file:"]),Bu="xiaoheihe.cn";function sp(e,t=window.location.href,r={}){const n=e.trim();if(!n)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(n)}catch{throw new Error("小程序链接必须是绝对 URL")}if(ip.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!op(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function ap(e,t){const r=new URL(e);return r.searchParams.set($l,t),r.toString()}function Mf(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const s=Sf(n,r);return i.pathname.startsWith(s)}catch{return!1}}function Hu(e){const t=new URL(e);return Hc(t)?"loopback":Fc(t)?"lan":"production"}function op(e,t,r){return cp(e)||Hc(e)||Fc(e)&&dp(t,r)}function cp(e){return e.protocol==="https:"&&hp(e.hostname)}function Hc(e){return e.protocol==="http:"&&up(e.hostname)}function up(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Fc(e){return e.protocol==="http:"&&lp(e.hostname)}function dp(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Hc(r)||Fc(r)}catch{return!1}}function lp(e){const t=fp(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function fp(e){const t=e.split(".");if(t.length!==4)return;const r=t.map(n=>{if(!/^\d+$/.test(n))return;const i=Number(n);return Number.isInteger(i)&&i>=0&&i<=255?i:void 0});return r.every(n=>n!==void 0)?r:void 0}function hp(e){return e===Bu||e.endsWith(`.${Bu}`)}function mp(e){let t,r=!1,n=!1;const i=new URL(e.launchUrl).origin,s=a=>{const c=a.data;if(n||!e.iframe.contentWindow||a.source!==e.iframe.contentWindow||a.origin!==i||c?.type!=="hb-sdk:dev-document"||c.nonce!==e.nonce||typeof c.documentId!="string"||!/^[a-f0-9]{32}$/.test(c.documentId)||typeof c.href!="string"||c.href.length>8192||!Mf(e.launchUrl,c.href,e.locationBasePath))return;const u=new URL(c.href);if(!(u.username||u.password||u.searchParams.get($l)!==e.nonce)){if(c.phase==="leaving"){c.documentId===t&&!r&&(r=!0,e.onLeaving());return}if(c.phase==="boot"){if(t!==void 0&&t!==c.documentId&&c.navigationType==="reload"){n=!0,e.onReload(u.href);return}r&&t===c.documentId&&e.onResume(),t=c.documentId,r=!1}}};return window.addEventListener("message",s),()=>{window.removeEventListener("message",s)}}function Rf(e){const t=ft(e);return(r,n)=>{if(r.kind==="none")return{allowed:!0};for(const i of r.permissions){const s=t.valid?t.permissions[i]:void 0;if(!s)return{allowed:!1,code:"PERMISSION_NOT_IN_SNAPSHOT",message:`当前运行快照不包含权限: ${i};正式入口需发布包含该声明的新版本,开发入口请重新打开调试`,data:{permission:i,method:n}};if(s.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${i}`,data:{permission:i,method:n}};if(i==="post"){const a=ga.includes(n)?"read":ai.includes(n)?"write":void 0;if(!a||s.config[a]!==!0)return{allowed:!1,code:"PERMISSION_DENIED",message:`关联帖子未声明 ${a??n} 权限`,data:{permission:i,method:n}}}}return{allowed:!0}}}function Ep(e){const t=ft(e),r=Object.values(t.permissions).map(i=>Object.freeze({...i,config:Object.freeze({...i.config})})),n=e&&typeof e=="object"&&"revision"in e?e.revision:void 0;return Object.freeze({schema_version:1,...typeof n=="number"?{revision:n}:{},entries:Object.freeze(r)})}function gp(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const pp=1e3;function _p(e,t=gp()){if(t.userActivation)return t.userActivation.isActive===!0;const r=t.lastUserInteractionAt,n=t.now??Date.now();return t.activeElement===e&&r!==void 0&&n>=r&&n-r<=pp}const Tp="runtime.gate.probe",Cf=new Set(pr.map(e=>e.method));class Ap{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=Wl;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.getWorkspaceCardLaunchContext=t.getWorkspaceCardLaunchContext,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,this.onDevUploadSession=t.onDevUploadSession,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:Nr,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:"unload",payload:{timestamp:Date.now()}})}catch{}finally{window.removeEventListener("message",this.handleMessage);for(const r of["pointerdown","touchend","mousedown","keydown"])window.removeEventListener(r,this.handleUserInteraction,!0);this.lastUserInteractionAt=void 0;for(const r of this.operations.values())r.abort("bridge destroyed");this.operations.clear()}}postEvent(t,r){this.destroyed||this.postMessage({namespace:Nr,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Nr,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Nr,version:2,nonce:this.nonce,type:"event",id:t,method:Zl,payload:r})}onMessage(t){if(!this.started||this.destroyed)return;if(this.onDevUploadSession&&this.iframe.contentWindow&&t.source===this.iframe.contentWindow&&t.data?.type==="hb-sdk:dev-upload-session"){const n=t.data.deviceSessionId;if(typeof n=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(n))try{this.onDevUploadSession(n)}catch{}return}if(!this.isTrustedMiniProgramMessage(t))return;const r=t.data;if(r.type==="handshake"){this.handleHandshake(r,t.origin);return}if(r.type==="request"){let n=!1;try{const i=navigator.userActivation;if(i==null){this.handleRequest(r,this.iframe.isConnected&&document.visibilityState==="visible");return}n=_p(this.iframe,{activeElement:document.activeElement,userActivation:i,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{n=!1}this.handleRequest(r,n);return}if(r.type==="cancel"&&this.handshaken&&r.id){this.operations.get(r.id)?.abort();return}r.type==="event"&&this.handshaken&&this.onInternalEvent?.(r)}onUserInteraction(t){const r=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||r.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&F0(t.data)&&(!this.handshaken||t.data.version===this.bridgeVersion)&&((this.handshaken?this.bridgeVersion:t.data.version)===1||this.targetOrigin==="*"||t.origin===this.targetOrigin)&&t.data.nonce===this.nonce}handleHandshake(t,r){const n=t.payload,i=t.version,s=!this.handshaken;if(s){if(this.onHandshake?.(n)===!1)return;this.bridgeVersion=i,i===1&&this.targetOrigin!=="*"&&r&&r!=="null"&&(this.targetOrigin=r),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.environmentInfo&&t.id&&this.postMessage({namespace:Nr,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:Kl,payload:{environment:this.environmentInfo,...this.getWorkspaceCardLaunchContext?{workspaceCardLaunchContext:this.getWorkspaceCardLaunchContext()}:{}}}),this.postEvent("ready",{timestamp:Date.now()}),s?this.onReady?.(n):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===Tp){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,ke("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Cf.has(t.method)){this.postResponse(t,void 0,ke("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,ke("INVALID_PARAMS","bridge request id 重复"));return}const n=new AbortController;this.operations.set(t.id,n);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{requestId:t.id,postEvent:this.postEvent.bind(this),postProgress:s=>{this.operations.get(t.id)===n&&this.postProgress(t.id,s)},signal:n.signal,trustedUserGesture:r});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==n)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==n)return;const s=Js(i);this.postResponse(t,void 0,s),this.postEvent("error",s)}finally{this.operations.get(t.id)===n&&(this.operations.delete(t.id),n.signal.aborted||n.abort("operation terminal"))}}postResponse(t,r,n){if(!(!this.postMessage({namespace:Nr,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!Ip(t.method)))try{this.onResponsePosted?.({method:t.method,outcome:n?"error":"success",...n?{errorCode:n.code}:{}})}catch{}}postMessage(t){const r=this.iframe.contentWindow;return r?(r.postMessage(t,this.targetOrigin),!0):!1}}function Ip(e){return typeof e=="string"&&Cf.has(e)}function T(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function pe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zc(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw T("FILE_IO_FAILED","当前环境缺少安全随机数能力");try{const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}catch{throw T("FILE_IO_FAILED","无法生成安全文件标识")}}function Lf(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",s=r.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:n,create:i?(a,c)=>e.create(a,c):Uo,remove:s?a=>e.remove(a):vf,read:a=>e.read(a),...typeof e.readPrefix=="function"?{readPrefix:(a,c)=>e.readPrefix(a,c)}:{},write:i?(a,c)=>e.write(a,c):Uo,stat:a=>e.stat(a)})}function Pf(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",s=r.allowRemove!==!1,a=s&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:n,file:c=>Lf(e.file(c),n,{allowRemove:s}),directory:c=>Pf(e.directory(c),n,{allowRemove:s}),create:i?(c,u)=>e.create(c,u):Uo,remove:a?(c,u)=>e.remove(c,u):vf,stat:c=>e.stat(c),list:(c,u)=>e.list(c,u)})}function Uo(){return Promise.reject(T("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function vf(){return Promise.reject(T("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const bp=new Set(["REQUEST_CANCELLED","REQUEST_TIMEOUT","RUNTIME_DESTROYED","USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","USER_DATA_PERMISSION_STATE_INVALID","USER_DATA_SOURCE_NOT_LINKED","USER_DATA_SOURCE_LOGIN_REQUIRED","USER_GAME_DATA_UNAVAILABLE","USER_GAME_DATA_INVALID_RESPONSE","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"]),yp={REQUEST_CANCELLED:"文件操作已取消",REQUEST_TIMEOUT:"文件操作超时",RUNTIME_DESTROYED:"小程序已关闭",USER_DATA_PERMISSION_STORAGE_UNAVAILABLE:"无法读取本地用户数据许可",USER_DATA_PERMISSION_STATE_INVALID:"本地用户数据许可状态异常,已停止访问",USER_DATA_SOURCE_NOT_LINKED:"请先在小黑盒关联对应游戏账号",USER_DATA_SOURCE_LOGIN_REQUIRED:"请先在小黑盒更新游戏来源登录",USER_GAME_DATA_UNAVAILABLE:"游戏资料暂不可用,请稍后重试",USER_GAME_DATA_INVALID_RESPONSE:"游戏资料响应异常,请稍后重试",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 gn(e){const t=jc(e),r=t&&bp.has(t)?T(t,yp[t]??"文件操作失败"):T("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Xt(e){try{return e()}catch(t){throw gn(t)}}function jc(e){try{if(!pe(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Fu=1024;class Vc{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new Vc(void 0,this.miniProgramDetail)}dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareFile(t,r,n),[s]=this.registerMany([i]);return Bi(i.handle,{kind:"file",handleId:s})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const s=Xt(()=>{if(!Array.isArray(t))throw T("FILE_IO_FAILED","Host 返回了无效文件选择结果");const c=t.length;if(i!==void 0&&c>i)throw T("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+c>Fu)throw T("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const u=[];for(let d=0;d<c;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw T("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");u.push(this.prepareFile(t[d],r,n))}return u}),a=this.registerMany(s);return s.map((c,u)=>Bi(c.handle,{kind:"file",handleId:a[u]}))}revokeFiles(t){for(const r of t)this.handles.get(r)?.handle.kind==="file"&&this.handles.delete(r)}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[s]=this.registerMany([i]);return ju(i.handle,{kind:"directory",handleId:s})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!kr(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!kr(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}isUserDataDownloadRef(t){return!kr(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="download"}resolveFileEntry(t){this.assertCanonicalDetail();const r=wp(t);if("handleId"in r){const a=this.readDirect(r.handleId,"file");return{ref:r,...a}}const n=this.resolveRoot(r.root),i=_i(r.relativePath);$a(n.origin,i);const s=this.prepareFile(Xt(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...s}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Dp(t);if("handleId"in r){const a=this.readDirect(r.handleId,"directory");return{ref:r,...a}}const n=this.resolveRoot(r.root),i=r.relativePath==="."?".":_i(r.relativePath);$a(n.origin,i);const s=this.prepareDirectory(i==="."?n.hostHandle:Xt(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...s}}describeFile(t,r){return Gu(t),Bi(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Xt(()=>{if(!Array.isArray(r))throw T("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw T("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const s=[];for(let a=0;a<i;a+=1){if(!Object.prototype.hasOwnProperty.call(r,a))throw T("FILE_IO_FAILED","Host 返回了稀疏目录列表");const c=r[a];t.origin==="sandbox"&&pe(c)&&typeof c.name=="string"&&kf(c.name)||s.push(this.describeListedEntry(t,c))}return this.assertCanonicalDetail(),s})}describeListedEntry(t,r){return Xt(()=>{if(pe(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Bi(n.handle,zu(t.ref,n.handle.name))}if(pe(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return ju(n.handle,Np(t.ref,n.handle.name))}throw T("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Di(r);$a(t.origin,n);const i=this.prepareFile(Xt(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:zu(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw T("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Xt(()=>{Gu(t);const i=n??t.mode;return Vu(t.mode,i),{handle:Lf(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Xt(()=>{Mp(t,i);const s=n??t.mode;return Vu(t.mode,s),{handle:Pf(t,s,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Fu)throw T("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const s=zc();if(!this.handles.has(s)&&!r.has(s))return r.add(s),s}throw T("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,s)=>this.handles.set(n[s],i)),n}readDirect(t,r){if(!Sp(t))throw T("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw T("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw T("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Ot("files.sandbox");return this.prepareDirectory(Xt(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw T("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Ot("files")}}function _i(e){if(!vc(e))throw T("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function $a(e,t){if(e==="sandbox"&&kf(t))throw T("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function kf(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function Di(e,t="文件名"){const r=_i(e);if(r.includes("/"))throw T("INVALID_PARAMS",`${t} 只能是 basename`);return r}function zu(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:_i(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Np(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:_i(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Bi(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function ju(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Vu(e,t){if(t==="readwrite"&&e!=="readwrite")throw T("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function wp(e){return kr(e)||xf(),e}function Dp(e){return Jl(e)||xf(),e}function xf(){throw T("INVALID_PARAMS","文件引用不合法")}function Sp(e){return/^[0-9a-f]{32}$/.test(e)}function Op(e){return pe(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"}function Gu(e){if(!Op(e))throw T("FILE_IO_FAILED","Host 返回了无效 File handle");Di(e.name,"Host File name")}function Mp(e,t=!1){if(!pe(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 T("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw T("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&Di(e.name,"Host Directory name")}const Rp=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Cp=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Lp=new Set(["range","if-range","a-im"]),Pp=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"]),vp=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Hi={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class kp{constructor(t){this.signal=t}phase="initial";transition(t){if(Hi[t]<=Hi[this.phase])throw T("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Hi[this.phase]<Hi.committed&&this.signal.aborted)throw Hf()}normalizeHostError(t,r){return this.throwIfCancelled(),Yc(t,r,this.signal)}}async function Uf(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Ot("network.download");const s=Ue(r.operationContext,t.signal),a=new kp(s.signal);a.transition("target"),a.throwIfCancelled();let c;try{c=await Hp(e,i,s)}catch(l){throw a.normalizeHostError(l,"file")}a.throwIfCancelled();let u;a.transition("open");try{u=await n.network.open(e.request,s)}catch(l){throw a.normalizeHostError(l,"network")}let d=!1;try{a.throwIfCancelled(),a.transition("validate");const l=zp(u);jp(u,l);const h=Vp(u.status,l);if(e.maxBytes!==void 0&&h.expectedBytes!==void 0&&h.expectedBytes>e.maxBytes)throw T("FILE_TOO_LARGE","下载响应超过 maxBytes");a.throwIfCancelled();const f=Fp(e,c,l,i);let _=0;const p=Up(h.expectedBytes,e.maxBytes);Za(t,Ka(0,h));const y={...s,onProgress(O){!Number.isSafeInteger(O)||O<_||p!==void 0&&O>p||(_=O,Za(t,Ka(_,h)))}};a.transition("transfer"),d=!0;let w;try{w=await n.files.writeResource(f.hostHandle,u.body,{mode:f.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...h.expectedBytes===void 0?{}:{expectedBytes:h.expectedBytes}},y)}catch(O){throw a.normalizeHostError(O,"transfer")}a.transition("committed"),_=xp(w,h,_,e.maxBytes),Za(t,Ka(_,h));const N=i.describeFile(f.handle,f.ref);return a.transition("completed"),N}finally{d||Bp(n.network,u.body)}}function xp(e,t,r,n){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=n===void 0?r:Math.min(r,n);try{const s=e?.committedBytes;if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=i&&(n===void 0||s<=n))return s}catch{}return i}function Up(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Bp(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Hp(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Bo(i.handle.mode),await Kp(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Bo(n.handle.mode),await Zp(n.handle,r),{kind:"directory",...n}}function Fp(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Yp(e,r),s=n.deriveFile(t,i);return Bo(s.handle.mode),{...s,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function zp(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 T("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!pe(e.headers))throw T("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!Rp.has(r)||!Array.isArray(n)||n.length===0)throw T("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw T("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function jp(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw T("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:$p(t,Cp)});if((t["content-range"]?.length??0)>0)throw T("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Vp(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw T("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw T("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw T("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,s=i!==void 0&&Number.isSafeInteger(i)?i:void 0,a=Gp(t["content-encoding"]),c=e===204||e===205?0:n.length===0&&a?s:void 0,u=c!==void 0;return{...c===void 0?{}:{expectedBytes:c},...u?{total:c}:{},lengthComputable:u}}function Gp(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Ka(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Za(e,t){try{e.postProgress(t)}catch{}}function Yp(e,t){const r=t["content-disposition"]??[];for(const i of r){const s=qp(i);if(s&&rs(s))return s}for(const i of r){const s=Qp(i);if(s&&rs(s))return s}if(e.suggestedName!==void 0)return Gc(e.suggestedName);const n=Wp(e.url);return n&&rs(n)?n:"download.bin"}function qp(e){const t=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(e);if(!t)return;const r=t[1].trim().replace(/^"|"$/g,""),n=/^utf-8'[^']*'(.*)$/i.exec(r);if(n)try{return decodeURIComponent(n[1])}catch{return}}function Qp(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 Wp(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Gc(e){try{Di(e,"suggestedName")}catch{throw T("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!rs(e))throw T("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function rs(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||vp.test(e))}function $p(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Kp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Bf()}catch(r){throw Yc(r,"file",t.signal)}}async function Zp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Bf()}catch(r){throw Yc(r,"file",t.signal)}}function Bo(e){if(e!=="readwrite")throw T("FILE_ACCESS_DENIED","下载目标只允许读取")}const Xp={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 Yc(e,t,r){if(r.aborted)return Hf();const n=Jp(e);if(n&&Pp.has(n)){const s=T(n,Xp[n]??"下载失败");return Object.defineProperty(s,"cause",{value:e,enumerable:!1}),s}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?T("DOWNLOAD_TIMEOUT","下载网络请求超时"):T("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?T("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):T("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function Jp(e){return pe(e)&&typeof e.code=="string"?e.code:void 0}function Bf(){return T("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Hf(){return T("DOWNLOAD_CANCELLED","下载已取消")}function e_(e){if(!e)return;const t=Object.keys(e).find(r=>Lp.has(r.trim().toLowerCase()));if(t)throw T("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Yu=8*1024*1024,t_=32*1024*1024;function qc(e){const t=new Map;let r=0;const n={signal:new AbortController().signal,lifecycle:"cleanup"},i=c=>c.remove(n).catch(()=>{}),s=async c=>{const u=t.get(c);u&&(t.delete(c),r-=u.size,await i(u.target))};e.signal.addEventListener("abort",()=>{for(const c of t.keys())s(c)},{once:!0});const a=c=>{if(e.signal.aborted||c.signal.aborted)throw T("DOWNLOAD_CANCELLED","存档下载已取消")};return{release:s,sizeOf:c=>t.get(c)?.size,async download(c,u,d){const l=c.file;if(!l||typeof l.file_id!="string"||typeof l.name!="string"||typeof l.size_bytes!="number"||!Number.isSafeInteger(l.size_bytes)||l.size_bytes<0||typeof c.download_url!="string"||typeof c.expires_at!="number"||!Number.isSafeInteger(c.expires_at))throw T("INVALID_RESPONSE","存档下载描述无效");if(l.size_bytes>Yu)throw T("FILE_TOO_LARGE","存档文件超过 8 MiB");const h={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:c.download_url},timeout:6e4};if(!If(h)||new URL(c.download_url).pathname!==`/cloud_archive/${l.file_id}.zip`||c.expires_at<=Date.now())throw T("INVALID_RESPONSE","存档下载地址无效");a(d);const f=Math.min(Yu,t_-r);if(f<=0)throw T("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达上限");const _=e.files.sandbox.file(`.hb-game-saves/${zc()}.zip`);if(!_.remove)throw T("REQUEST_UNSUPPORTED","宿主不支持私有存档清理");r+=f;let p=!1;try{await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},d),await _.create({recursive:!0,exclusive:!0},d);const y=e.registry.createTransferScope();try{const I=y.registerFile(_,"game-save","readwrite");await Uf({request:h,url:new URL(c.download_url),to:I.ref,targetKind:"file",maxBytes:f},{...d,trustedUserGesture:!1,postEvent:()=>{},postProgress:()=>{}},{transfer:e.transfer,fileRegistry:y,operationContext:d})}finally{y.dispose()}a(d);const w=(await _.stat(d)).size;if(!Number.isSafeInteger(w)||w<0||w>f)throw T("FILE_TOO_LARGE","存档实际大小超过限额");await u(d),a(d);const N=async()=>{throw T("FILE_ACCESS_DENIED","存档文件只读")},O={kind:"file",mode:"read",name:l.name,create:N,write:N,async read(I){a(I),await u(I);const H=await _.read(I);try{if(a(I),await u(I),H.byteLength!==w)throw T("INVALID_RESPONSE","私有存档副本长度不匹配");return H}catch(Q){throw H.fill(0),Q}},async stat(I){return a(I),await u(I),await _.stat(I),a(I),await u(I),{kind:"file",size:w,...typeof l.modified_at=="number"&&Number.isSafeInteger(l.modified_at)?{modifiedAt:l.modified_at}:{}}}};return r-=f-w,t.set(O,{target:_,size:w}),p=!0,O}finally{p||(r-=f,await i(_))}}}}const r_=/^(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 n_(e){if(!e?.minimumSdkVersion)throw ke("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=Cr(e.minimumSdkVersion),r=e.sdkVersion?Cr(e.sdkVersion):void 0;if(!t)throw ke("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw ke("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=Cr("0.6.0");if(!r){if(ns(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw ke("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0&&e.allowPublicPrerelease!==!0)throw ke("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(ns(r,t)<0)throw ke("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:ns(r,Cr("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function i_(e,t){if(typeof t!="string"||!Cr(t))throw ke("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw ke("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function La(e,t){const r=Cr(e),n=Cr(t);if(!(!r||!n))return ns(r,n)}function Cr(e){const t=r_.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(r=>/^\d+$/.test(r)?Number(r):r)??[]}}function ns(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],s=t.prerelease[n];if(i===void 0||s===void 0)return i===s?0:i===void 0?-1:1;if(i!==s)return typeof i=="number"&&typeof s=="string"?-1:typeof i=="string"&&typeof s=="number"?1:i<s?-1:1}return 0}function s_(e){return{[oi]:async(t,r)=>{const n=Ue(e.operationContext,r.signal);if(ve(n.signal),t!==void 0)throw T("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw T("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const s=e.presentation.showAppreciation;if(!s)throw T("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await Se(()=>s({name:i.name,author:i.author},n),n.signal)}}}function $r(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function qu(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function Ff(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,s=new Map,a=new Set,c=new Set;let u=!1;function d(y,w){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:y,type:w})).catch(()=>{})}catch{}}function l(y){const w=r.get(y);if(!w)throw new Error("Unknown runtime cache scope");return w}function h(y,w){return y.flatMap((N,O)=>{const I=JSON.stringify(y.slice(0,O+1));return[JSON.stringify([I]),JSON.stringify([I,w])]})}function f(y,w){return JSON.stringify(h(y,w).map(N=>n.get(N)??0))}async function _(y,w){const N=l(y),O=JSON.stringify([JSON.stringify(N),...w?[w]:[]]),I=(n.get(O)??0)+1;n.set(O,I),i.add(O);for(const H of c)H(N,w);if(!e.store){i.delete(O),d(w??"*","invalidation");return}try{await e.store.invalidate(N,w)}catch(H){throw d(w??"*","storage_error"),H}n.get(O)===I&&i.delete(O),d(w??"*","invalidation")}function p(y){if(u)throw new Error("Runtime cache manager disposed");const w=s.get(y.namespace);if(w){if(w.sourceCodec!==y.codec||w.definition.codec.version!==y.codec.version||JSON.stringify(w.definition.policy)!==JSON.stringify(y.policy))throw new Error("Conflicting runtime cache namespace");return w.cache}if(!y.namespace||!y.codec.version)throw new Error("Invalid runtime cache definition");const N=Object.freeze({...y.policy}),O=Object.freeze({version:y.codec.version,encode:y.codec.encode.bind(y.codec),decode:y.codec.decode.bind(y.codec),validate:y.codec.validate.bind(y.codec),clone:y.codec.clone.bind(y.codec)}),I=y.namespace;for(const U of[N.ttlMs,N.memoryMaxEntries,N.diskMaxEntries,N.diskMaxBytes,N.maxEntryBytes])if(!Number.isFinite(U)||U<0)throw new Error("Invalid runtime cache policy");const H=new Map,Q=new Map,M=new Map;let x=!1;function v(U,k,Y){if(u||x||U.aborted||f(k,I)!==Y)throw $r()}function W(U){return N.ttlMs>0&&N.persistence==="memory-and-disk"&&!!e.store&&!h(U,I).some(k=>i.has(k))}function q(U,k,Y){const R=t();return U.envelopeVersion===1&&JSON.stringify(U.address)===JSON.stringify(k)&&qu(U.revisions,Y)&&U.payload.byteLength<=N.maxEntryBytes&&Number.isFinite(U.cachedAt)&&Number.isFinite(U.expiresAt)&&U.cachedAt<=R&&U.cachedAt>=0&&U.expiresAt>U.cachedAt&&Math.min(U.expiresAt,U.cachedAt+N.ttlMs)>R}function te(U,k,Y,R,K){if(!(N.ttlMs<=0||N.memoryMaxEntries<1)){for(const[Z,ee]of H)Math.min(ee.entry.expiresAt,ee.entry.cachedAt+N.ttlMs)<=t()&&H.delete(Z);for(H.delete(U);H.size>=Math.floor(N.memoryMaxEntries);){const Z=H.keys().next();if(Z.done)break;H.delete(Z.value)}H.set(U,{entry:k,value:Y,epoch:R,persistent:K})}}async function F(U,k,Y,R){const K={namespace:I,codecVersion:O.version,scopeIds:k,key:U.key},Z=JSON.stringify(K);let ee=[],se=W(k);if(se)try{ee=await e.store.readRevisions(k,I)}catch{se=!1,d(I,"storage_error")}v(R.signal,k,Y);async function fe(){if(!se)return!0;try{return qu(ee,await e.store.readRevisions(k,I))}catch{return se=!1,d(I,"storage_error"),!1}}const we=H.get(Z);if(N.ttlMs>0&&we&&we.epoch===Y&&q(we.entry,K,ee)&&we.persistent===se&&await fe())return v(R.signal,k,Y),d(I,"memory_hit"),we.value;if(H.delete(Z),se){let m,S;try{m=await e.store.read(K,N.maxEntryBytes),m&&q(m,K,ee)?S=O.decode(m.payload):m=void 0}catch{m=void 0,d(I,"storage_error")}if(v(R.signal,k,Y),m&&await fe())return v(R.signal,k,Y),te(Z,m,S,Y,!0),d(I,"disk_hit"),S}d(I,"miss");const Pe=O.validate(await U.load(R.signal));v(R.signal,k,Y);const E=O.clone(Pe);if(!await fe()&&se)throw $r();if(v(R.signal,k,Y),N.ttlMs>0){const m=t();let S;try{S=O.encode(E)}catch{return E}const D={envelopeVersion:1,address:K,revisions:se?ee:[],cachedAt:m,expiresAt:m+N.ttlMs,payload:S};if(se&&S.byteLength<=N.maxEntryBytes){let P=!0,X=!1;try{P=await e.store.publish(D,N),X=P}catch{d(I,"storage_error")}if(v(R.signal,k,Y),!P)throw $r();X&&d(I,"published")}v(R.signal,k,Y),te(Z,D,E,Y,se)}return E}async function G(U){if(u||x||U.signal?.aborted)return Promise.reject($r());const k=l(U.scope),Y=f(k,I);let R;if(W(k)){const se=new AbortController;M.set(se,k);const fe=()=>se.abort();U.signal?.addEventListener("abort",fe,{once:!0});let we=()=>{};try{R=await Promise.race([e.store.readRevisions(k,I),new Promise((Pe,E)=>{const m=()=>E($r());se.signal.addEventListener("abort",m,{once:!0}),we=()=>se.signal.removeEventListener("abort",m)})])}catch{se.signal.aborted||d(I,"storage_error")}finally{we(),M.delete(se),U.signal?.removeEventListener("abort",fe)}}v(U.signal??new AbortController().signal,k,Y);const K=JSON.stringify([k,U.key,Y,R]);let Z=Q.get(K);if(Z?.controller.signal.aborted&&(Z=void 0),!Z){const se=new AbortController;Z={ids:k,controller:se,waiters:0,promise:Promise.resolve(void 0)};const fe=Z;fe.promise=F(U,k,Y,se).finally(()=>{Q.get(K)===fe&&Q.delete(K)}),Q.set(K,fe)}const ee=Z;return ee.waiters+=1,new Promise((se,fe)=>{let we=!1;function Pe(m){we||(we=!0,U.signal?.removeEventListener("abort",E),ee.controller.signal.removeEventListener("abort",E),ee.waiters-=1,ee.waiters===0&&ee.controller.abort(),m())}function E(){Pe(()=>fe($r()))}U.signal?.addEventListener("abort",E,{once:!0}),ee.controller.signal.addEventListener("abort",E,{once:!0}),ee.promise.then(m=>Pe(()=>{try{v(U.signal??new AbortController().signal,k,Y),se(O.clone(m))}catch(S){fe(S)}}),m=>Pe(()=>fe(m)))})}function j(U,k){if(k&&k!==I)return;const Y=R=>U.every((K,Z)=>R[Z]===K);for(const[R,K]of H)Y(K.entry.address.scopeIds)&&H.delete(R);for(const[R,K]of Q)Y(K.ids)&&(K.controller.abort(),Q.delete(R));for(const[R,K]of M)Y(K)&&R.abort()}function z(){if(!x){x=!0,H.clear();for(const U of M.keys())U.abort();M.clear();for(const U of Q.values())U.controller.abort();Q.clear(),a.delete(z),c.delete(j),s.get(I)?.cache===V&&s.delete(I)}}const V={read:G,invalidateScope:U=>_(U,I),dispose:z};return a.add(z),c.add(j),s.set(I,{definition:{namespace:I,codec:O,policy:N},sourceCodec:y.codec,cache:V}),V}return{createScope(y,w){if(u||!y)throw new Error("Invalid runtime cache scope");const N=Object.freeze({});return r.set(N,[...w?l(w):[],y]),N},register:p,invalidateScope:y=>_(y),dispose(){if(!u){u=!0;for(const y of[...a])y();s.clear(),n.clear(),i.clear()}}}}function a_(e){const t=new TextEncoder,r=new TextDecoder("utf-8",{fatal:!0});return{version:e.version,validate:e.validate,encode:n=>t.encode(JSON.stringify(n)),decode:n=>e.validate(JSON.parse(r.decode(n))),clone:n=>e.validate(JSON.parse(JSON.stringify(n)))}}const o_=".hb-runtime-cache-v1",c_=1e3,Xa=64*1024,Kr=1e3,u_=2048,Ln=32*1024*1024,d_=1024,is=new TextEncoder,Qu=new TextDecoder("utf-8",{fatal:!0});function Pn(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Fi(e){const t=await globalThis.crypto.subtle.digest("SHA-256",is.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Ft(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Wu(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function l_(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function $u(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function f_(e,t){const r=e.sandbox.directory(o_),n=r.directory("revisions"),i=r.directory("entries");for(const F of[r,n,i,i.directory("capability-check")])$u(F,["directory","file","create","stat","list","remove"]),$u(F.file("capability-check"),["create","stat","read","write","remove"]);const s=new AbortController,a=()=>s.abort();t.signal.aborted?a():t.signal.addEventListener("abort",a,{once:!0});const c={...t,signal:s.signal};let u=Promise.resolve(),d;function l(F){d=F,s.abort(),t.signal.removeEventListener("abort",a)}function h(F){if(l_(F))throw l(F),F}function f(){if(d)throw d;if(c.signal.aborted)throw Pn()}function _(F,G=c.signal){const j=u.then(()=>{if(G.aborted)throw d??Pn();return f(),F()},()=>{if(G.aborted)throw d??Pn();return f(),F()}).catch(k=>{throw h(k),k});if(u=j.catch(()=>{}),G.aborted)return Promise.reject(d??Pn());let z=()=>{};const V=new Promise((k,Y)=>{const R=()=>Y(d??Pn());G.addEventListener("abort",R,{once:!0}),z=()=>G.removeEventListener("abort",R)}),U=setTimeout(()=>{l(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},c_);return Promise.race([j,V]).finally(()=>{clearTimeout(U),z()})}async function p(){f(),await n.create({recursive:!0,exclusive:!1},c),f(),await i.create({recursive:!0,exclusive:!1},c),f()}async function y(F,G){const j=n.file(`${await Fi([F,G??null])}.revision`);await N(j);let z=!1;try{await j.create({recursive:!1,exclusive:!0},c),z=!0}catch(k){h(k),f()}if(z){const k=Wu();return await j.write(is.encode(k),c),f(),k}const V=await j.stat(c);if(V.size<1||V.size>128)throw new Error("缓存 revision 文件损坏");const U=Qu.decode(await j.read(c));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(U))throw new Error("缓存 revision 文件损坏");return f(),U}async function w(F){const G=await F.list({limit:Kr},c);if(G.length>=Kr)throw new Error("缓存目录超过治理上限");return G}async function N(F){try{await F.stat(c);return}catch(j){if(!zi(j))throw j}if((await w(n)).length>=Kr-1)throw new Error("缓存 metadata 超过治理上限")}async function O(F,G){await p();const j=[];for(let z=0;z<F.length;z+=1){const V=F.slice(0,z+1);j.push(await y(V),await y(V,G))}return j}async function I(F){return r.directory(`entries/${await Fi([F.namespace,F.codecVersion,F.scopeIds])}`)}async function H(F){return(await I(F)).file(`${await Fi(F.key)}.cache`)}async function Q(F,G){const j=await F.stat(c);if(j.size<5||j.size>G+Xa+4)throw new Error("缓存条目超过大小限制");const z=await F.read(c);if(f(),z.length!==j.size)throw new Error("缓存条目读取不完整");const V=new DataView(z.buffer,z.byteOffset,z.byteLength).getUint32(0);if(V<1||V>Xa||V+4>z.length)throw new Error("缓存信封损坏");const U=JSON.parse(Qu.decode(z.subarray(4,V+4))),k=z.slice(V+4);if(U.envelopeVersion!==1||!U.address||!Array.isArray(U.address.scopeIds)||!U.address.scopeIds.every(Y=>typeof Y=="string")||typeof U.address.namespace!="string"||typeof U.address.codecVersion!="string"||typeof U.address.key!="string"||!Array.isArray(U.revisions)||U.revisions.length!==U.address.scopeIds.length*2||!U.revisions.every(Y=>typeof Y=="string"&&Y.length>0)||!Number.isSafeInteger(U.cachedAt)||!Number.isSafeInteger(U.expiresAt)||U.cachedAt<0||U.expiresAt<=U.cachedAt||U.payloadBytes!==k.length||k.length>G)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:U.address,revisions:U.revisions,cachedAt:U.cachedAt,expiresAt:U.expiresAt,payload:k}}async function M(F){if(!F.remove)throw new Error("Host 不支持缓存文件删除");await F.remove(c)}async function x(F){try{if((await F.file.stat(c)).size!==F.size)return!1;const G=await Q(F.file,Ln);return!Ft(G.address,F.entry.address)||!Ft(G.revisions,F.entry.revisions)||G.cachedAt!==F.entry.cachedAt||G.expiresAt!==F.entry.expiresAt||!Ft(await v(G.payload),await v(F.entry.payload))?!1:(await M(F.file),!0)}catch(G){if(zi(G))return!0;throw G}}async function v(F){const G=await globalThis.crypto.subtle.digest("SHA-256",F);return Array.from(new Uint8Array(G),j=>j.toString(16).padStart(2,"0")).join("")}async function W(){const F=await w(n);let G=0;for(const U of F)if(U.kind==="file"&&(G+=(await U.stat(c)).size,G>Ln))throw new Error("缓存扫描超过字节上限");const j=[];let z=0,V=G;for(const U of await w(i)){if(U.kind!=="directory")throw new Error("缓存目录结构损坏");for(const k of await w(U)){if(k.kind!=="file"||++z>u_)throw new Error("缓存文件超过治理上限");const Y=(await k.stat(c)).size;if(V+=Y,V>Ln)throw new Error("缓存扫描超过字节上限");try{const R=await Q(k,Ln);j.push({file:k,entry:R,size:(await k.stat(c)).size,bucketName:U.name})}catch(R){h(R),f(),zi(R)||await M(k)}}}return{entries:j,metadataBytes:G}}async function q(){for(const F of await w(i))if(F.kind==="directory"&&F.remove&&(await w(F)).length===0)try{await F.remove({recursive:!1},c)}catch(G){h(G),f()}}function te(F){const{payload:G,...j}=F,z=is.encode(JSON.stringify({...j,payloadBytes:G.length}));if(z.length>Xa)throw new Error("缓存信封过大");const V=new Uint8Array(4+z.length+G.length);return new DataView(V.buffer).setUint32(0,z.length),V.set(z,4),V.set(G,z.length+4),V}return{readRevisions:(F,G)=>_(()=>O(F,G)),read:(F,G)=>_(async()=>{f();const j=await H(F);let z;try{z=await Q(j,G)}catch(V){if(f(),zi(V))return;throw V}if(!(!Ft(z.address,F)||z.expiresAt<=Date.now())&&Ft(z.revisions,await O(F.scopeIds,F.namespace)))return z}),publish:(F,G)=>_(async()=>{f();const{address:j}=F;if(!Ft(F.revisions,await O(j.scopeIds,j.namespace)))return!1;const z=te(F);if(F.payload.length>G.maxEntryBytes||z.length>G.diskMaxBytes||G.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await p();const V=await I(j),U=await H(j),k=await W(),Y=[],R=new Map;for(const ee of k.entries){if(ee.bucketName===V.name&&ee.file.name===U.name)continue;const se=JSON.stringify([ee.entry.address.scopeIds,ee.entry.address.namespace]);let fe=R.get(se);if(fe||(fe=await O(ee.entry.address.scopeIds,ee.entry.address.namespace),R.set(se,fe)),ee.entry.expiresAt<=Date.now()||!Ft(ee.entry.revisions,fe)){if(!await x(ee))throw new Error("缓存治理期间条目已变化")}else Y.push(ee)}Y.sort((ee,se)=>ee.entry.cachedAt-se.entry.cachedAt);function K(){const ee=Y.filter(se=>se.bucketName===V.name);return Y.length+1>d_||z.length+k.metadataBytes+Y.reduce((se,fe)=>se+fe.size,0)>Ln||ee.length+1>Math.min(G.diskMaxEntries,Kr-1)||z.length+ee.reduce((se,fe)=>se+fe.size,0)>G.diskMaxBytes}for(;K();){const ee=Y.filter(we=>we.bucketName===V.name),fe=ee.length+1>Math.min(G.diskMaxEntries,Kr-1)||z.length+ee.reduce((we,Pe)=>we+Pe.size,0)>G.diskMaxBytes?ee[0]:Y[0];if(!fe||!await x(fe))throw new Error("缓存容量不足或条目已变化");Y.splice(Y.indexOf(fe),1)}await q();const Z=await w(i);if(!Z.some(ee=>ee.name===V.name)&&Z.length>=Kr-1)throw new Error("缓存目录超过治理上限");if(await V.create({recursive:!0,exclusive:!1},c),!Ft(F.revisions,await O(j.scopeIds,j.namespace)))return!1;try{await U.create({recursive:!1,exclusive:!0},c)}catch(ee){h(ee),await U.stat(c)}return await U.write(z,c),f(),Ft(F.revisions,await O(j.scopeIds,j.namespace))}),invalidate:(F,G)=>_(async()=>{await p();const j=n.file(`${await Fi([F,G??null])}.revision`);await N(j);try{await j.create({recursive:!1,exclusive:!0},c)}catch(z){h(z),await j.stat(c)}await j.write(is.encode(Wu()),c),f();try{const{entries:z}=await W();for(const V of z){if(G!==void 0&&V.entry.address.namespace!==G||!F.every((k,Y)=>V.entry.address.scopeIds[Y]===k))continue;const U=await O(V.entry.address.scopeIds,V.entry.address.namespace);Ft(V.entry.revisions,U)||await x(V)}await q()}catch(z){h(z),f()}})}}function zi(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const h_="RATE_LIMITED_BY_RUNTIME",m_="RATE_LIMITED",zf=20,jf=40,Vf=150,Gf=20,Yf=1e4,qf=45e3,Qf=1,E_=300*1e3,g_=64;function Zr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function p_(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function __(e={}){const t=e.now??Date.now,r=p_(e.coalesceWindowMs,Vf),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,Zr(e.budget?.ratePerSecond,zf)),burst:Math.max(1,Math.floor(Zr(e.budget?.burst,jf)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(Zr(e.loopDetection?.maxCalls,Gf))),windowMs:Math.max(1,Math.floor(Zr(e.loopDetection?.windowMs,Yf)))},s=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(Zr(e.circuitBreaker?.failureThreshold,Qf))),openMs:Math.max(1,Math.floor(Zr(e.circuitBreaker?.openMs,qf)))},a=new Map,c=new Map,u=new Set,d=new Map,l=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},h={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let f=!1;function _(x){try{e.onReport?.(x)}catch{}}function p(x,v){if(!i)return{exceeded:!1,count:0};const W=c.get(x)??[],q=v-i.windowMs;let te=0;for(;te<W.length&&W[te]<=q;)te+=1;te>0&&W.splice(0,te);const F=W.length>=i.maxCalls;return F||(W.push(v),W.length>i.maxCalls+1&&W.splice(0,W.length-(i.maxCalls+1))),c.set(x,W),{exceeded:F,count:W.length}}function y(x){if(!n)return!0;const v=Math.max(0,x-l.updatedAt)/1e3;return l.tokens=Math.min(n.burst,l.tokens+v*n.ratePerSecond),l.updatedAt=x,l.tokens<1?!1:(l.tokens-=1,!0)}function w(x){if(!n)return 0;const v=Math.max(0,x-l.updatedAt)/1e3,W=Math.min(n.burst,l.tokens+v*n.ratePerSecond);return Math.max(0,Math.ceil((1-W)/n.ratePerSecond*1e3))}function N(x,v,W,q,te){if(!s)return;const F=d.get(v),G=(F?.open?0:F?.failures??0)+1;if(G<s.failureThreshold){d.set(v,{open:!1,openedAt:0,openMs:0,failures:G});return}const j=Math.min(Math.max(s.openMs,q),E_);d.set(v,{open:!0,openedAt:te,openMs:j,failures:G}),h.circuitOpened+=1,_({type:"circuit_opened",capability:x,endpointId:v,status:W,openMs:j,timestamp:te})}function O(x){const v=d.get(x);v&&!v.open&&d.delete(x)}function I(x){for(const[v,W]of a)!W.pending&&W.expiresAt<=x&&a.delete(v);for(;a.size>=g_;){const v=[...a].find(([,W])=>!W.pending);if(!v)break;a.delete(v[0])}}function H(x,v){if(x===void 0)return;const W=a.get(x);W?.promise===v&&(W.pending=!1)}function Q(x,v){if(x===void 0)return;a.get(x)?.promise===v&&a.delete(x)}async function M(x){if(f)return x.load();const v=t();if(s){const F=d.get(x.endpointId);if(F?.open){const G=F.openedAt+F.openMs-v;if(G>0)throw h.circuitRejected+=1,_({type:"circuit_rejected",capability:x.capability,endpointId:x.endpointId,retryAfterMs:G,timestamp:v}),I_("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:x.endpointId,retryAfterMs:G});d.delete(x.endpointId)}}const W=p(x.endpointId,v);W.exceeded&&i?u.has(x.endpointId)||(u.add(x.endpointId),_({type:"loop_detected",capability:x.capability,endpointId:x.endpointId,count:W.count,windowMs:i.windowMs,timestamp:v})):u.delete(x.endpointId);const q=r>0?x.coalesceKey:void 0;if(q!==void 0){const F=a.get(q);if(F&&(F.pending||F.expiresAt>v))return h.coalesced+=1,_({type:"coalesced",capability:x.capability,endpointId:x.endpointId,timestamp:v}),F.promise;F&&a.delete(q)}if(W.exceeded&&i)throw h.loopRejected+=1,Ku("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:x.capability,endpointId:x.endpointId,count:W.count,windowMs:i.windowMs});if(!y(v)){h.budgetRejected+=1;const F=w(v);throw _({type:"budget_exhausted",capability:x.capability,endpointId:x.endpointId,retryAfterMs:F,timestamp:v}),Ku("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:x.capability,endpointId:x.endpointId,retryAfterMs:F})}q!==void 0&&I(v);const te=x.load().then(F=>(H(q,te),O(x.endpointId),F),F=>{Q(q,te);const G=T_(F);throw G!==void 0&&N(x.capability,x.endpointId,G,A_(F),v),F});return q!==void 0&&a.set(q,{endpointId:x.endpointId,promise:te,expiresAt:v+r,pending:!0}),te}return{execute:M,invalidateCoalescing(x){if(x===void 0){a.clear();return}for(const[v,W]of a)x.includes(W.endpointId)&&a.delete(v)},snapshot(){return{...h,openCircuits:[...d.entries()].filter(([,x])=>x.open).map(([x])=>x)}},dispose(){f||(f=!0,a.clear(),c.clear(),u.clear(),d.clear())}}}function T_(e){if(typeof e!="object"||e===null)return;const t=e.status;if(!(typeof t!="number"||!Number.isInteger(t)))return t===403||t===429?t:void 0}function A_(e){if(typeof e!="object"||e===null)return 0;const t=e.retryAfterMs;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function Ku(e,t){return{code:h_,message:e,data:t}}function I_(e,t){return{code:m_,message:e,data:t}}const Wf=3e4,$f=6e4,Ho=1440*60*1e3;function b_(e){const t=e!==!1&&(e?.enabled??!0),r=e===!1?void 0:e;return{enabled:t,debugReport:t&&r?.debugReport===!0,identityTtlMs:t?Math.max(0,Math.floor(r?.identityTtlMs??Wf)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??$f)):0,steamGameListTtlMs:t?y_(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:zf,burst:jf},coalesceWindowMs:r?.coalesceWindowMs??Vf,loopDetection:r?.loopDetection??{maxCalls:Gf,windowMs:Yf},circuitBreaker:r?.circuitBreaker??{failureThreshold:Qf,openMs:qf}}}}function y_(e){return e===void 0||!Number.isFinite(e)?Ho:Math.max(0,Math.floor(e))}function Kf(e){return typeof e=="object"&&e!==null}function Zf(e,t){const r=e.data;if(!Kf(r))throw new Error(t);if(r.status!=="ok")throw new Error(typeof r.msg=="string"&&r.msg?r.msg:t);return r.result}function Ve(e,t){const r=e.data;if(!Kf(r)||typeof r.status!="string")throw new Error(t);return r}const Xf={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},N_={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}:{},...e.include_first_publish_post_reminder?{include_first_publish_post_reminder:"true"}:{}}},parse(e,t){return Ve(e,"工坊小程序详情加载失败")}};function Si(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function w_(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function D_(e){const t=Ve(e,"小程序登录授权接口响应异常"),r=t.result,n={};if(r.login_code&&typeof r.login_code=="object"){const i=r.login_code;n.loginCode={code:i.code,expiresIn:i.expires_in,scopes:i.scopes||[]}}return r.consent_challenge&&typeof r.consent_challenge=="object"&&(n.consentChallenge=w_(r.consent_challenge)),{...t,result:n}}const S_={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=>({...Si(e.runtimeContext),challenge:e.challenge}),parse:e=>Ve(e,"小程序授权取消接口响应异常")},O_={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=>Si(e.runtimeContext),parse:e=>Ve(e,"小程序授权撤销接口响应异常")},M_={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=>Si(e.runtimeContext),parse(e){const t=Ve(e,"小程序隔离身份接口响应异常"),r=typeof t.result.steam_id=="string"&&t.result.steam_id.trim()?t.result.steam_id.trim():void 0;return{...t,result:{appUserId:t.result.app_user_id,...r?{steamId:r}:{}}}}},R_={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=>({...Si(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>D_(e)},C_={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=>({...Si(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=Ve(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},L_=64;function Jf(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??L_)),n=e.now??Date.now,i=new Map,s=new Map;let a=0,c=!1;function u(h){for(const[f,_]of i)_.expiresAt<=h&&i.delete(f)}function d(h,f,_){if(c||t<=0||_!==a)return;const p=n();for(u(p),i.delete(h);i.size>=r;){const y=i.keys().next();if(y.done)break;i.delete(y.value)}i.set(h,{expiresAt:p+t,value:f})}function l(h,f){if(c)return f();if(t>0){const w=i.get(h);if(w&&w.expiresAt>n())return Promise.resolve(w.value);w&&i.delete(h)}const _=s.get(h);if(_)return _;const p=a,y=f().then(w=>(d(h,w,p),w)).finally(()=>{s.get(h)===y&&s.delete(h)});return s.set(h,y),y}return{read:l,invalidate(){a+=1,i.clear(),s.clear()},dispose(){c||(c=!0,a+=1,i.clear(),s.clear())},get size(){return i.size}}}function P_(e,t){return t?e?"server":"local":"legacy"}function v_(e,t){if(e==="local")throw T("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const k_=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],x_=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),U_=/authorization|cookie|pkey|password|secret|token/i,eh=/authorization|cookie|pkey|token|password|secret/i;function zt(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function B_(e){for(const t of Object.keys(e))if(!x_.has(t))throw new Je(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of k_)if(Object.prototype.hasOwnProperty.call(e,t)&&zt(e,t)!==void 0)throw new Je(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(zt(e,"bodyEncoding")!==void 0&&zt(e,"bodyEncoding")!=="json"&&zt(e,"bodyEncoding")!=="form")throw new Je("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(zt(e,"failurePresentation")!==void 0&&zt(e,"failurePresentation")!=="none")throw new Je("endpoint failurePresentation 必须为 none");if(zt(e,"auth")!==void 0&&zt(e,"auth")!=="none"&&zt(e,"auth")!=="optional"&&zt(e,"auth")!=="required")throw new Je("endpoint auth 必须为 none、optional 或 required")}function ea(e){if(Array.isArray(e))return e.map(ea);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))U_.test(n)||(r[n]=ea(i));return r}function Zu(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))eh.test(r)||(t[r]=n);return t}function H_(e){if(!e)return;const t=Object.keys(e).find(r=>eh.test(r));if(t)throw new Je(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Oi extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;retryAfterMs;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,Object.defineProperty(this,"responseData",{value:t.responseData,enumerable:!1}),t.retryAfterMs!==void 0&&(this.retryAfterMs=t.retryAfterMs),Object.setPrototypeOf(this,new.target.prototype)}}const Xu=1440*60*1e3,F_=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function z_(e,t=Date.now){if(!e)return;const r=Object.entries(e).find(([a])=>a.trim().toLowerCase()==="retry-after")?.[1];if(typeof r!="string"||!r.trim())return;const n=r.trim();if(/^\d+$/.test(n)){const a=Number(n)*1e3;return a>0?Math.min(a,Xu):void 0}if(!F_.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const s=i-t();return s>0?Math.min(s,Xu):void 0}function j_(e,t,r,n){if(e.method!=="GET")return;let i;try{i=JSON.stringify([t??null,r??null])??"undefined"}catch{return}return`${e.id}\0${n}\0${i}`}function th(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class pn extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,th(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Mi extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,th(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function V_(e,t,r,n,i,s,a,c){return{config:{auth:e.auth,body:ea(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:a.credentials,headers:Zu(s),method:e.method,metadata:{endpointId:e.id},query:ea(n),timeout:e.timeout,url:r},data:c.data,headers:Zu(c.headers)||{},status:c.status,statusText:c.statusText}}async function Pa(e,t,r,n){if(!n||!n.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(n.credentials!=="heybox-session"&&n.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(B_(t),typeof t.id!="string"||!t.id)throw new Je("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new Je("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new Je("endpoint path 必须为非空字符串");const s=t.query?await t.query(r):void 0,a=t.body?await t.body(r):void 0,c=t.headers?await t.headers(r):void 0;H_(c);const u=async()=>{let h;try{h=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...s===void 0?{}:{params:s},...a===void 0?{}:{data:a},...c===void 0?{}:{headers:c},credentials:n.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:n.signal,...n.miniProgramDetail===void 0?{}:{miniProgramDetail:n.miniProgramDetail}})}catch(_){throw _ instanceof Je?_:new pn({endpointId:t.id,cause:_})}if(h.status<200||h.status>=300)throw new Oi({endpointId:t.id,status:h.status,responseData:h.data,retryAfterMs:z_(h.headers)});const f=V_(t,r,i,s,a,c,n,h);if(t.parse)try{return await t.parse(f,r)}catch(_){throw new Mi({endpointId:t.id,cause:_})}return f.data},d=n.gate;if(!d)return u();const l=j_(t,s,a,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...l===void 0?{}:{coalesceKey:l},load:u})}const G_=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),Y_=new Set(En),Qc="steam_account",rh=new Set(En.filter(e=>e!==Qc)),q_=1e3;function Q_(e){const t=new Set,r=Jf({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??Wf))}),n=new Set;let i=0,s=!1,a=Promise.resolve(),c;const u=e.steamAccount===!0,d=e.userDataMode??P_(e.networkEnabled===!0,u),l=e.requestPolicyEnabled!==!1,h=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function f(){if(!u&&!e.authorizationContext)return{};if(!e.authorizationContext)throw T("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let k;try{k=await e.authorizationContext.get(e.operationContext)}catch(R){throw zo(R)?Ja(R.code,R.message,R):Ja("REQUEST_FAILED","读取 Runtime auth context 失败",R)}if(k.steamAccount!==u||k.userDataMode!==d)throw T("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const Y=k.token.trim();if(!Y)throw T("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:Y}}const _=e.account.onChange(k=>{if(p(),y("heybox_app_login_change",k?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),k&&e.account.getAccountKey){const Y=i;Q().then(R=>{!s&&i===Y&&y("heybox_app_login_change",R)}).catch(()=>{})}});function p(){i+=1,c?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function y(k,Y){k==="user_info_authorization_change"&&J_(Y)&&r.invalidate();for(const R of t)try{R(k,Y)}catch{}}function w(){const k=e.identity.get()?.miniProgramId?.trim();if(!k)throw T("INVALID_STATE","当前能力缺少 canonical 小程序身份");return k}function N(){if(s||e.operationContext.signal.aborted)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function O(){N();let k;try{k=await e.account.getCurrentUserId(e.operationContext)}catch(Y){throw rd(Y,e.operationContext.signal,"读取小黑盒账号失败")}return typeof k=="string"&&k.trim()?k.trim():void 0}async function I(k,Y){const R=await O();if(i!==Y||R!==k)throw T("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function H(k,Y,R=w()){if(!e.account.getAccountKey)throw T("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let K;try{K=await e.account.getAccountKey(R,k,e.operationContext)}catch{throw N(),T("REQUEST_FAILED","读取本地账号标识失败")}if(await I(k,Y),w()!==R)throw T("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof K!="string"||!K.trim())throw T("INVALID_RESPONSE","Host 返回了无效的账号标识");return K}async function Q(){const k=w(),Y=i,R=await O();if(N(),i!==Y)throw T("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return R?{isHeyboxAppLoggedIn:!0,accountKey:await H(R,Y,k)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function M(k){N();try{await e.account.ensureAuthenticated({trustedUserGesture:k,reason:"runtime_auth",signal:e.operationContext.signal})}catch(R){throw rd(R,e.operationContext.signal,"小黑盒登录失败")}const Y=await O();if(!Y)throw T("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return Y}async function x(k,Y,R=e.operationContext.signal){try{if(R.aborted)throw Fo();return await X_(Pa(e.network,k,Y,{...e.operationContext,credentials:"heybox-session",signal:R,...h?{gate:h}:{}}),R)}catch(K){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):K instanceof Je?T("REQUEST_UNSUPPORTED",K.message):K instanceof Mi?T("INVALID_RESPONSE","授权接口响应不合法"):K instanceof pn?T("REQUEST_FAILED","授权请求失败"):K instanceof Oi?l&&(K.status===403||K.status===429)?T("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:K.status,...K.retryAfterMs===void 0?{}:{retryAfterMs:K.retryAfterMs}}):T("REQUEST_FAILED",K.message):zo(K)?K:T("REQUEST_FAILED","授权请求失败")}}async function v(k,Y){await x(S_,{runtimeContext:{miniProgramId:k,...await f()},challenge:Y}).catch(()=>{})}function W(k){const Y=async()=>{const K=ed(e.operationContext.signal);c=K;try{return await k(K.signal)}finally{c===K&&(c=void 0),K.abort()}},R=a.then(Y,Y);return a=R.then(()=>{},()=>{}),R}async function q(k,Y,R,K,Z){if(!R)throw await v(k,Y.challenge),T("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await v(k,Y.challenge),T("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return W(async ee=>{await I(K,Z);const se=await te(k,Y.displayedScopes,ee);await I(K,Z);let fe;try{fe=await e.authPresentation.confirmAuthorization({miniProgramId:k,scopes:Y.displayedScopes,...se,signal:ee})}catch(Pe){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await I(K,Z),await v(k,Y.challenge),Ja("REQUEST_FAILED","授权确认界面执行失败",Pe))}if(await I(K,Z),fe.status!=="granted")throw await v(k,Y.challenge),T("AUTHORIZATION_CANCELLED","用户取消授权");const we=K_(fe.grantedScopes,Y.displayedScopes,u);if(!we.includes("identity"))throw await v(k,Y.challenge),T("AUTHORIZATION_CANCELLED","用户拒绝授权");return we})}async function te(k,Y,R){const K=ed(R),Z=setTimeout(()=>K.abort(),q_);try{const ee=Z_(e.miniProgramPresentation),[se,fe]=await Promise.all([ee?Promise.resolve(ee):F(k,K.signal),Y.includes("profile")?G(K.signal):Promise.resolve(void 0)]);return{...se?{miniProgram:se}:{},...fe?{userProfile:fe}:{}}}finally{clearTimeout(Z),K.abort()}}async function F(k,Y){try{const R=e.identity.get()?.version?.trim(),K=await x(N_,{mini_program_id:k,...R?{miniprogram_version:R}:{}},Y),Z=Xr(K,"小程序公开资料"),ee=an(Z.name),se=an(Z.icon_url);return ee||se?{...ee?{name:ee}:{},...se?{avatarUrl:se}:{}}:void 0}catch{return}}async function G(k){try{const Y=await x(Xf,void 0,k),R=Xr(Y,"账号基础信息"),K=an(R.display_username),Z=an(R.display_avatar);return K||Z?{...K?{nickname:K}:{},...Z?{avatar:Z}:{}}:void 0}catch{return}}async function j(k,Y){if(v_(d,"auth.login"),!u&&k.includes(Qc))throw T("INVALID_PARAMS","auth.login 参数不合法");const R=w(),K=await M(Y),Z=i,ee=await x(R_,{runtimeContext:{miniProgramId:R,...await f()},scopes:k});await I(K,Z);const se=Xr(ee,"小程序登录"),fe=td(se,"loginCode"),we=td(se,"consentChallenge");if(fe===we)throw T("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let Pe;if(fe)Pe=Ju(se.loginCode,u);else{const m=W_(se.consentChallenge,u),S=await q(R,m,Y,K,Z);await I(K,Z);const D=await x(C_,{runtimeContext:{miniProgramId:R,...await f()},challenge:m.challenge,selectedScopes:S});if(await I(K,Z),Pe=Ju(Xr(D,"小程序登录确认"),u),Pe.scopes.some(P=>!S.includes(P)))throw T("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const m of Pe.scopes)n.add(m);r.invalidate();const E=e.account.getAccountKey?await H(K,Z,R):void 0;return y("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...E===void 0?{}:{accountKey:E}}),y("user_info_authorization_change",eo(n,u)),{...Pe,...E===void 0?{}:{accountKey:E}}}async function z(k,Y){const R=i,K=await x(M_,{runtimeContext:{miniProgramId:Y,...await f()}});await I(k,R);const Z=$_(Xr(K,"用户本地身份"),u);for(const ee of u?En:rh)n.add(ee);return y("user_info_authorization_change",eo(n,u)),Z}function V(k){N();const Y=w(),R=`${k}\0${Y}\0${i}\0${u}`;return r.read(R,()=>z(k,Y))}async function U(k){if(!k)throw T("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const Y=w(),R=i,K=await O();if(!K)throw T("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const Z=await x(O_,{runtimeContext:{miniProgramId:Y,...await f()}});await I(K,R),Xr(Z,"用户授权撤销"),p(),y("user_info_authorization_change",{identity:"denied",profile:"denied",...u?{steam_account:"denied"}:{}})}return{getAccountState:Q,login:j,async confirmGameSaves(k){if(!k)throw T("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw T("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const Y=w(),R=await M(k),K=i;await W(async Z=>{await I(R,K);const ee=await te(Y,["identity"],Z),se=await e.authPresentation.confirmAuthorization({miniProgramId:Y,scopes:["identity","game_saves"],...ee,signal:Z});if(await I(R,K),se.status!=="granted"||!se.grantedScopes.includes("game_saves")||!se.grantedScopes.includes("identity"))throw T("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:V,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>eo(n,u),revoke:U,onEvent(k){return t.add(k),()=>t.delete(k)},dispose(){s||(s=!0,p(),r.dispose(),_(),t.clear())}}}function Ja(e,t,r){const n=T(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function Xr(e,t){if(!pe(e))throw T("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":G_.has(r)?r:"REQUEST_FAILED";throw T(n,r)}if(!pe(e.result))throw T("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Ju(e,t){if(!pe(e))throw T("INVALID_RESPONSE","login code 必须是对象");const r=ta(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!r.includes("identity"))throw T("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function W_(e,t){if(!pe(e))throw T("INVALID_RESPONSE","授权 challenge 必须是对象");const r=ta(e.requestedScopes,"challenge requestedScopes",t),n=ta(e.displayedScopes,"challenge displayedScopes",t);if(typeof e.challenge!="string"||!e.challenge.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!Number.isInteger(e.consentUiVersion)||Number(e.consentUiVersion)<0||!r.length||!r.includes("identity")||!n.length||!n.includes("identity")||r.some(i=>!n.includes(i)))throw T("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function $_(e,t){if(!pe(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw T("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw T("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const n=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return n?{appUserId:r,steamId:n}:{appUserId:r}}function K_(e,t,r){const n=ta(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw T("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function an(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Z_(e){const t=an(e?.name),r=an(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function ed(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 X_(e,t){return t.aborted?Promise.reject(Fo()):new Promise((r,n)=>{let i=!1;const s=c=>{i||(i=!0,t.removeEventListener("abort",a),c())},a=()=>s(()=>n(Fo()));t.addEventListener("abort",a,{once:!0}),e.then(c=>s(()=>r(c)),c=>s(()=>n(c)))})}function Fo(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function ta(e,t,r){const n=r?Y_:rh;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw T("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function eo(e,t){const r=t?En:En.filter(n=>n!==Qc);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function td(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function J_(e){return pe(e)?Object.values(e).some(t=>t==="denied"):!1}function zo(e){return pe(e)&&typeof e.code=="string"&&typeof e.message=="string"}function rd(e,t,r){return t.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):zo(e)?e:T("REQUEST_FAILED",r)}const eT=new Set(En);function tT(e){return{[_s]:async t=>{if(t!==void 0)throw T("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[Ts]:async(t,r)=>e.authorization.login(rT(t),r.trustedUserGesture)}}function rT(e){if(e===void 0)return["identity"];if(!pe(e)||Object.keys(e).some(t=>t!=="scopes"))throw nd();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!eT.has(t))||new Set(e.scopes).size!==e.scopes.length)throw nd();return[...e.scopes]}function nd(){return T("INVALID_PARAMS","auth.login 参数不合法")}const Me=e=>({code:e,message:`房间操作失败:${e}`,data:{}});function ss(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw Me("INVALID_PARAMS");const r=e;if(Object.keys(r).some(n=>!t.includes(n)))throw Me("INVALID_PARAMS");return r}function Dr(e,t=/^[A-Za-z0-9_-]{1,80}$/){if(typeof e!="string"||!t.test(e))throw Me("INVALID_PARAMS");return e}function id(e){const t=ss(e,["name","hash"]);return{name:Dr(t.name,/^[A-Za-z][A-Za-z0-9_]{0,47}$/),hash:Dr(t.hash,/^[a-f0-9]{64}$/)}}const nT=80,iT=64,ir=e=>e?.code||"RESULT_UNKNOWN",sT=e=>["RESULT_UNKNOWN","ROOM_BUSY","RATE_LIMITED","SERVICE_UNAVAILABLE","INTERNAL_ERROR"].includes(e),ji=e=>sT(e)||e.startsWith("runtime.transport."),sd=new Set(["FORBIDDEN","INVALID_PARAMS","UNKNOWN_ACTION","MEMBER_EXPIRED"]),sr=e=>({room_id:e.room_id,session_id:e.session_id}),un=e=>Number.isSafeInteger(e)&&e>=0;function ad(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Jr(e,t){const r=e.grant;if(!r||![r.room_id,r.session_id,r.member_id,r.generation].every(n=>typeof n=="string"&&n.length>0)||!/^[a-f0-9]{12}$/.test(r.code)||r.preview_release!==""&&(typeof r.preview_release!="string"||!/^preview:.+$/.test(r.preview_release))||![r.command_seq,r.recv_seq].every(un)||![r.authorization_expires_at_ms,r.token_expires_at_ms].every(un))throw Me("INVALID_RESPONSE");if(t&&(r.room_id!==t.room_id||r.session_id!==t.session_id||r.member_id!==t.member_id||r.generation!==t.generation||t.preview_release!==r.preview_release))throw Me("UNAUTHORIZED");return r}function od(e){if(!e||!un(e.revision)||!Array.isArray(e.members)||e.members.length>8)throw Me("INVALID_RESPONSE");return{members:e.members.map(({member_id:r,phase:n,owner:i})=>{if(n!=="active"&&n!=="grace")throw Me("INVALID_RESPONSE");return{id:r,phase:n,owner:i}}),locked:e.locked,status:{connection:"connected",room:"open"}}}function aT(e){let t=new AbortController,r,n,i,s,a=0,c=!1;const u=new Set;let d=[],l=!1,h=0;const f=new Map,_=new Map;function p(E){if(E.aborted||e.operationContext.signal.aborted)throw Me("ABORTED")}function y(E){if(p(E),!e.roomSocket||!e.authorizationContext)throw Me("METHOD_NOT_SUPPORTED");n??=e.account.onChange(we)}function w(){c=!1;for(const E of u)E()}function N(){r=void 0,w()}function O(E,m){if(!(!c||E.aborted||m?.aborted))return new Promise(S=>{function D(){clearTimeout(P),E.removeEventListener("abort",D),m?.removeEventListener("abort",D),u.delete(D),S()}const P=setTimeout(D,2e3);u.add(D),E.addEventListener("abort",D),m?.addEventListener("abort",D)})}function I(){const E=t.signal;if(y(E),r)return r;const m=e.roomSocket,S={...e.operationContext,signal:E},D=e.account.getCurrentUserId(S).then(P=>{if(p(E),!P)throw Me("UNAUTHORIZED");return m.connect({onPush(X){E.aborted||r!==D||(i?z(i,X):s&&(d.length<256?d.push(X):l=!0))},onDisconnect(){E.aborted||r!==D||(c=!0,a++,i&&(clearTimeout(i.leaseTimer),i.leaseTimer=void 0,x(i)))},onReconnect(){E.aborted||r!==D||(w(),i&&Y(i))},onClose(){E.aborted||r!==D||(a++,N(),i&&Y(i))}},S)}).then(P=>{if(E.aborted)throw P.close(),Me("ABORTED");return P});return r=D,D.catch(()=>{r===D&&N()}),D}async function H(E,m,S=t.signal){p(S);const D=I(),P=await D;p(S);const X=await P.request(`heybox/cloud_room/${E}`,m).catch(ce=>{throw ir(ce)==="UNAUTHORIZED"&&r===D&&(E==="list"||E==="create"||E==="join")&&(N(),a++,P.close(),E==="list"&&i&&Y(i)),ce});return p(S),X}async function Q(E,m){await I(),p(m);const S=e.authorizationContext,D={...e.operationContext,signal:m},P=await(S.getForRoom?S.getForRoom(D,E):S.get(D));if(p(m),!P.token)throw Me("UNAUTHORIZED");return P.token}function M(E){clearTimeout(E.gapTimer),E.gapTimer=void 0}function x(E){i!==E||E.offline||(M(E),clearTimeout(E.leaseTimer),E.leaseTimer=void 0,E.offline=!0,e.onRoomEvent?.({type:"status",roomId:E.grant.room_id,code:"RESULT_UNKNOWN"}))}function v(E){i===E&&(i=void 0,M(E),E.pending.clear(),clearTimeout(E.leaseTimer))}function W(E,m){E===i&&(E.terminalCode=m,v(E),e.onRoomEvent?.({type:"status",roomId:E.grant.room_id,code:m}))}function q(E,m,S=!1){if(m.revision>E.version){const D=od(m),P=E.snapshot;if(E.version=m.revision,!S&&D.locked===P.locked&&D.members.length===P.members.length&&D.members.every((X,ce)=>{const _e=P.members[ce];return X.id===_e.id&&X.phase===_e.phase&&X.owner===_e.owner}))return;E.snapshot=D}else if(!S)return;E.offline||e.onRoomEvent?.({type:"members",roomId:E.grant.room_id,snapshot:E.snapshot,streamId:E.grant.generation,version:E.version})}function te(E,m){E.cursor=m.recv_seq,e.onRoomEvent?.({type:"action",roomId:E.grant.room_id,messageId:m.message_id,action:m.action,params:m.params,sequence:m.recv_seq,sender:m.sender_id})}function F(E){for(;i===E;){const m=E.pending.get(E.cursor+1);if(!m)break;E.pending.delete(E.cursor+1),te(E,m)}E.cursor>=Math.max(E.observed,E.grant.recv_seq)&&(M(E),E.pending.clear())}function G(E){E!==i||E.offline||E.recovery||E.catchingUp||E.gapTimer||(E.gapTimer=setTimeout(()=>{E.gapTimer=void 0,k(E)},nT))}function j(E,m,S=!1){if(!un(m.recv_seq)||!m.message_id||!m.params){W(E,"INVALID_RESPONSE");return}if(E.observed=Math.max(E.observed,m.recv_seq),!(m.recv_seq<=E.cursor)){if(m.recv_seq===E.cursor+1){te(E,m),F(E),E.pending.size>0&&!S&&G(E);return}if(!S){if(E.pending.size<iT){E.pending.set(m.recv_seq,m),G(E);return}M(E),k(E)}}}function z(E,m){E!==i||m.room_id!==E.grant.room_id||m.member_id!==E.grant.member_id||m.generation!==E.grant.generation||("status"in m&&m.status?.code==="ROOM_CLOSED"?W(E,m.status.code):"action"in m&&m.action?j(E,m.action):"members"in m&&m.members&&q(E,m.members))}function V(E){if(clearTimeout(E.leaseTimer),i!==E)return;const m=E.grant,S=m.token_expires_at_ms-Date.now();E.leaseTimer=setTimeout(async()=>{if(i!==E)return;if(E.offline){Y(E);return}const D=a;try{const P=t.signal,ce=E.grant.preview_release||E.grant.token_expires_at_ms<=Date.now()+2e4?await Q(!0,P):void 0;if(E!==i||E.offline||a!==D)return;const _e=await H("heartbeat",{...sr(E.grant),...ce?{room_token:ce}:{}},P);if(i!==E||E.offline||a!==D)return;E.grant=Jr(_e,E.grant),_e.members&&q(E,_e.members),E.grant.recv_seq>E.cursor&&G(E)}catch{i===E&&a===D&&Y(E);return}V(E)},!m.preview_release&&S<2e4?Math.max(3e3,S-1e4):1e4)}async function U(E,m,S){const D=await Q(!0,S);return H("rejoin",{...sr(E),room_token:D,after_seq:m===0?0:m()},S)}function k(E){if(E!==i||E.offline||E.recovery||E.catchingUp)return E.catchingUp;if(M(E),E.cursor>=Math.max(E.grant.recv_seq,E.observed))return;const m=t.signal,S=a,D=E.cursor;return E.catchingUp=(async()=>{const P=await H("rejoin",{...sr(E.grant),after_seq:D},m);if(!(i!==E||S!==a||E.offline)){E.grant=Jr(P,E.grant),E.commandSeq=Math.max(E.commandSeq,E.grant.command_seq);for(const X of P.replay)i===E&&j(E,X,!0);F(E),P.members&&q(E,P.members)}})().catch(P=>{if(E!==i)return;const X=ir(P);if(X==="ROOM_REPLAY_EXPIRED"){E.cursor===D&&Y(E);return}if(X==="ROOM_CLOSED"||X==="INVALID_RESPONSE"){W(E,X);return}Y(E)}).finally(()=>{E.catchingUp=void 0,i===E&&!E.offline&&E.cursor<Math.max(E.grant.recv_seq,E.observed)&&G(E)}),E.catchingUp}function Y(E,m=!1){if(E!==i||E.recovery)return E.recovery;if(x(E),E.finishing&&!m){E.queue.then(()=>{E===i&&E.offline&&!E.leaseTimer&&Y(E)});return}const S=t.signal,D=a;return E.recovery=(async()=>{const P=await U(E.grant,()=>{if(i!==E||D!==a)throw Me("RESULT_UNKNOWN");return E.cursor},S);if(i!==E||D!==a)throw Me("RESULT_UNKNOWN");E.grant=Jr(P,E.grant),E.commandSeq=E.grant.command_seq;for(const X of P.replay)i===E&&j(E,X,!0);if(F(E),E.cursor<E.grant.recv_seq)throw Me("RESULT_UNKNOWN");if(E===i){if(E.offline=!1,E.retryDelay=500,!P.members)throw Me("INVALID_RESPONSE");q(E,P.members,!0),V(E)}})().catch(P=>{if(E!==i)return;const X=ir(P);if(!ji(X)){if(E.finishing&&(X==="UNAUTHORIZED"||X==="ROOM_CLOSED"))return X;W(E,X);return}clearTimeout(E.leaseTimer),E.leaseTimer=setTimeout(()=>{Y(E)},E.retryDelay),E.retryDelay=Math.min(5e3,E.retryDelay*2)}).finally(()=>{E.recovery=void 0,E.cursor<E.observed&&G(E)}),E.recovery}async function R(E){if(s||i)throw Me("ROOM_ALREADY_JOINED");const m=Symbol();s=m;try{return await E()}finally{s===m&&(s=void 0,d=[],l=!1)}}async function K(E,m,S){const D=t.signal,P=s,X=()=>S?.aborted||P!==s;if(X())throw Me("ABORTED");const ce=ss(m,E==="create"?["definition","visibility"]:["definition","code"]),_e=id(ce.definition),ye=E==="join"?Dr(ce.code,/^[a-f0-9]{12}$/):void 0,Ee=E==="create"?ce.visibility??"invite":void 0;if(Ee!==void 0&&Ee!=="public"&&Ee!=="invite")throw Me("INVALID_PARAMS");const Ce=ye&&f.get(ye);if(Ce&&await Ce,X())throw Me("ABORTED");const De=await Q(!1,D),Fe={definition:_e,request_id:ad(),room_token:De},$e=()=>{if(X())throw Me("ABORTED");return E==="join"?H("join",{...Fe,code:ye},D):H("create",{...Fe,visibility:Ee},D)};let He=a,ze,ct=!1;try{ze=await $e()}catch(mt){if(p(D),!ji(ir(mt)))throw mt;He!==a&&await O(D,S),ct=!0,ze=await $e()}async function Yr(mt,Jm){if(Jm)try{mt=Jr(await U(mt,0,D),mt)}catch{}throw await H("leave",{...sr(mt),command_seq:mt.command_seq+1},D).catch(()=>{}),Me("ABORTED")}let Ke=Jr(ze);if(X())return Yr(Ke,ct||He!==a);const fu=e.operationContext.miniProgramDetail?.releaseChannel;if(fu==="public"&&Ke.preview_release||fu==="preview"&&!Ke.preview_release)throw Me("UNAUTHORIZED");if(ct||Ke.recv_seq>0||He!==a){He=a;try{ze=await U(Ke,0,D)}catch(mt){if(X())return Yr(Ke,He!==a);throw mt}if(Ke=Jr(ze,Ke),X())return Yr(Ke,He!==a)}p(D);const Xm=od(ze.members),Lt={grant:Ke,cursor:0,observed:0,commandSeq:Ke.command_seq,version:ze.members.revision,snapshot:Xm,queue:Promise.resolve(),pending:new Map,offline:!1,retryDelay:500};i=Lt;for(const mt of ze.replay)i===Lt&&j(Lt,mt,!0);for(const mt of d)z(Lt,mt);if(i!==Lt)throw Me("ROOM_CLOSED");return V(Lt),He!==a?Y(Lt):(l||Lt.cursor<Ke.recv_seq)&&k(Lt),{id:Ke.room_id,code:Ke.code,memberId:Ke.member_id,definition:_e,sequence:0,current:Lt.snapshot,streamId:Ke.generation,version:Lt.version}}async function Z(E,m){const S=t.signal,D=ss(E,["definition","cursor"]),P=id(D.definition),X=D.cursor===void 0?void 0:Dr(D.cursor,/^\d{1,19}$/);if(m?.aborted)throw Me("ABORTED");const ce=JSON.stringify([P.name,P.hash,X]);let _e=_.get(ce);if(!_e){const Ee=new Set,Ce=Q(!1,S).then(De=>{if([...Ee].every(Fe=>Fe?.aborted))throw Me("ABORTED");return H("list",{definition:P,room_token:De,cursor:X},S)}).finally(()=>{_.get(ce)?.page===Ce&&_.delete(ce)});_e={callers:Ee,page:Ce},_.set(ce,_e)}_e.callers.add(m);const ye=await _e.page;if(p(S),m?.aborted)throw Me("ABORTED");if(!Array.isArray(ye.rooms)||ye.rooms.length>32)throw Me("INVALID_RESPONSE");return{rooms:ye.rooms.map(Ee=>{if(!/^[a-f0-9]{12}$/.test(Ee.code)||!un(Ee.member_count)||!un(Ee.capacity)||Ee.capacity<2||Ee.capacity>8||Ee.member_count>=Ee.capacity)throw Me("INVALID_RESPONSE");return{code:Ee.code,members:Ee.member_count,capacity:Ee.capacity}}),...ye.next_cursor?{nextCursor:ye.next_cursor}:{}}}async function ee(E,m,S,D,P){const X=()=>H("recover",{...sr(E.grant),command_seq:m},D);let ce=!0;async function _e(){try{return await X()}catch(De){p(D);const Fe=ir(De);if(sd.has(Fe))throw De;ce=ji(Fe)||Fe==="UNAUTHORIZED"}}const ye=await _e();if(ye)return ye;if(c&&(await O(D,P),p(D),P?.aborted))throw Me("ABORTED");if(E.finishing&&S!==a){const De=await _e();if(De)return De}const Ee=await Y(E,!0)??E.terminalCode;if(p(D),!(E.finishing&&(Ee==="ROOM_CLOSED"||Ee==="UNAUTHORIZED"))&&(E!==i||E.offline||!ce))throw Me("RESULT_UNKNOWN");try{return await X()}catch(De){throw Ee?W(E,Ee):ir(De)==="UNAUTHORIZED"&&Y(E),De}}async function se(E,m,S){const D=ss(m,E==="send"?["roomId","action","params","to"]:E==="lifecycle"?["roomId","operation"]:["roomId"]),P=i;if(!P||P.grant.room_id!==Dr(D.roomId)){if(E==="dispose")return;throw Me("ROOM_CLOSED")}let X,ce={};if(E==="send"){if(X="dispatch",!D.params||typeof D.params!="object"||Array.isArray(D.params)||D.to!==void 0&&(!Array.isArray(D.to)||D.to.length===0||D.to.length>8))throw Me("INVALID_PARAMS");ce={action:Dr(D.action),params:D.params,...Array.isArray(D.to)?{to:D.to.map(Ee=>Dr(Ee,/^[a-f0-9]{32}$/))}:{}}}else if(E==="lifecycle"){if(D.operation!=="close"&&D.operation!=="lockJoin"&&D.operation!=="unlockJoin")throw Me("INVALID_PARAMS");X=D.operation==="close"?"close":D.operation==="lockJoin"?"lock_join":"unlock_join"}else X=E;const _e=t.signal,ye=P.queue.then(async()=>{if(p(_e),P!==i)throw Me("ROOM_CLOSED");if(S?.aborted)throw Me("ABORTED");if(X==="dispose"){v(P),P.offline||await H("dispose",{...sr(P.grant),command_seq:P.commandSeq+1},_e).catch(()=>{});return}if(P.offline)throw Me("RESULT_UNKNOWN");const Ee=P.commandSeq+1;if(!Number.isSafeInteger(Ee))throw Me("SESSION_EXPIRED");const Ce={...sr(P.grant),command_seq:Ee,...ce},De=()=>{P.uncertainSeq=void 0,P.commandSeq=Math.max(P.commandSeq,Ee)};function Fe(ze){if(sd.has(ze))throw De(),Me(ze)}const $e=a;P.finishing=X==="leave"||X==="close";let He;try{He=await H(X,Ce,_e)}catch(ze){p(_e);const ct=ir(ze);if(ct==="ROOM_BUSY"||ct==="RATE_LIMITED"||ct==="PAYLOAD_TOO_LARGE")throw ze;if(Fe(ct),!ji(ct)||P.uncertainSeq===Ee)throw P.finishing=!1,await Y(P),Me(ct);P.uncertainSeq=Ee;try{He=await ee(P,Ee,$e,_e,S)}catch(Yr){p(_e);const Ke=ir(Yr);throw Fe(Ke),Ke==="ABORTED"?Yr:Me(ct)}}finally{P.finishing=!1}if(De(),X==="leave"&&v(P),X==="close"&&W(P,"ROOM_CLOSED"),X==="dispatch"){if(typeof He.message_id!="string"||!He.message_id)throw Me("INVALID_RESPONSE");return{messageId:He.message_id}}if(E==="lifecycle")return{disposition:"committed",code:"OK",requestId:"action_"+ad()}});return P.queue=ye.catch(()=>{}),ye}function fe(){s=void 0,d=[],l=!1;const E=i;if(!E)return;const m=t.signal;v(E);const S=E.grant.code,D=E.queue.then(()=>H("leave",{...sr(E.grant),command_seq:E.commandSeq+1},m)).then(()=>{},()=>{}).finally(()=>{f.get(S)===D&&f.delete(S)});f.set(S,D)}function we(){if(i){const E=i;v(E),e.onRoomEvent?.({type:"status",roomId:E.grant.room_id,code:"UNAUTHORIZED"})}f.clear(),_.clear(),t.abort(),r?.then(E=>E.close(),()=>{}),t=new AbortController,N(),d=[],l=!1,s=void 0,a++}function Pe(){t.signal.aborted||(we(),t.abort(),n?.(),e.operationContext.signal.removeEventListener("abort",Pe))}return e.operationContext.signal.addEventListener("abort",Pe,{once:!0}),e.operationContext.signal.aborted&&Pe(),{handlers:{"cloud.rooms.list":(E,m)=>Z(E,m?.signal),"cloud.rooms.create":(E,m)=>R(()=>K("create",E,m?.signal)),"cloud.rooms.join":(E,m)=>R(()=>K("join",E,m?.signal)),"cloud.rooms.send":async(E,m)=>{if(h>=32)throw Me("ROOM_BUSY");h++;try{return await se("send",E,m?.signal)}finally{h--}},"cloud.rooms.leave":(E,m)=>se("leave",E,m?.signal),"cloud.rooms.dispose":(E,m)=>se("dispose",E,m?.signal),"cloud.rooms.lifecycle":(E,m)=>se("lifecycle",E,m?.signal)},releaseForReload:fe,dispose:Pe}}const oT={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 Ve(e,"排行榜记录删除接口响应异常")}},cT={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 Ve(e,"当前排行榜记录接口响应异常")}},uT={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 Ve(e,"排行榜信息接口响应异常")}},dT={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 Ve(e,"排行榜列表接口响应异常")}},lT={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 Ve(e,"排行榜提交接口响应异常")}},fT={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"};async function Ri(e,t,r){e.assertUsable();const n={request:async(i,s)=>(e.assertUsable(),e.network.request(i,s))};try{return await Se(()=>Pa(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(ia(i)||Vn(i,"REQUEST_UNSUPPORTED")||Vn(i,"RATE_LIMITED")||Vn(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof Je)throw oe("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof pn&&Vn(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Oi){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw oe("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw oe("UNAUTHORIZED","当前用户未登录");const s=hT(i.responseData);if(Le(s)&&typeof s.status=="string"&&s.status!=="ok"){const a=Le(s.result)?Jt(s.result.error_code):void 0;if(s.status==="login"||s.status==="relogin"||ra(s.result)||ra(s)||a&&/^[A-Z][A-Z0-9_]+$/.test(a))throw nh(s,e.subject)}throw oe("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof pn?na(e.subject):i instanceof Mi?Oe(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):Oe(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function at(e,t,r){if(!Le(e)||typeof e.status!="string")throw Oe(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw nh(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw Oe(`${t} 响应缺少 result`);return e.result}function Ci(e,t){try{return e.onChange(t)}catch(r){if(Vn(r,bf))return()=>{};throw r}}function nh(e,t){if(e.status==="login"||e.status==="relogin")throw oe("UNAUTHORIZED",Jt(e.msg)||"当前用户未登录");if(Le(e.result)){const i=Jt(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw oe(i,Jt(e.result.message)||Jt(e.msg)||`${t}请求失败`)}const r=ra(e.result)??ra(e),n=Jt(r?.user_message)||Jt(e.msg)||Jt(r?.developer_message)||`${t}请求失败`;throw r?oe(mT(r),n,{status:e.status,sbe:r}):oe("HEYBOX_API_ERROR",n,{status:e.status})}function hT(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function ra(e){return Le(e)&&Le(e.sbe)?e.sbe:void 0}function mT(e){const t=Jt(e.developer_message);if(t==="CLOUD_STORAGE_KEY_LIMIT_EXCEEDED")return"STORAGE_QUOTA_EXCEEDED";if(t&&/^[A-Z][A-Z0-9_]+$/.test(t))return t;const r=e.code;if(typeof r=="number"&&Number.isInteger(r))return fT[r]||t||"HEYBOX_API_ERROR";if(typeof r=="string"){const n=/^([A-Za-z][A-Za-z0-9_]*)(?:\(\d+\))?$/.exec(r.trim());if(n?.[1])return n[1]}return t||"HEYBOX_API_ERROR"}function Le(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Vn(e,t){return Le(e)&&e.code===t}function oe(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function Oe(e){return oe("INVALID_RESPONSE",e)}function na(e){return oe("REQUEST_FAILED",`${e}请求失败`)}function ia(e){return e instanceof Error&&e.name==="AbortError"}const ET="default",br="排行榜",gT=/^[A-Za-z0-9_-]{1,64}$/,pT=300*1e3,_T=250,TT=3;class AT{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Ci(t.account,()=>this.invalidateForAccountChange()),t.operationContext.signal.aborted?this.dispose():t.operationContext.signal.addEventListener("abort",this.handleTerminalAbort,{once:!0})}accountGeneration=0;buckets=new Map;inflight=new Map;unsubscribeAccountChange;requestGateContext;disposed=!1;handleTerminalAbort=()=>this.dispose();async submit(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(lT,{miniProgramId:n,...t});this.assertAccountGeneration(r);const s=at(i,tr,br);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),to(s,tr)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=vn("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const s=await this.request(dT,{miniProgramId:r,...t}),a=at(s,vt,br);if(!Le(a)||!Array.isArray(a.entries)||typeof a.has_more!="boolean")throw Oe(`${vt} 返回值不合法`);if(a.cursor!==void 0&&a.cursor!==null&&typeof a.cursor!="string")throw Oe(`${vt} 返回的 cursor 必须是字符串`);return{entries:a.entries.map(c=>to(c,vt)),...typeof a.cursor=="string"&&a.cursor?{cursor:a.cursor}:{},hasMore:a.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId(),i=await this.requireCurrentUser(r),s=this.createBucketKey(n,t.key),a=vn("current",i);return this.read(s,"current",a,async()=>{const c=await this.request(cT,{miniProgramId:n,...t}),u=at(c,gr,br);if(!Le(u))throw Oe(`${gr} 返回值必须是对象`);return u.entry===void 0||u.entry===null?void 0:to(u.entry,gr)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(oT,{miniProgramId:n,...t});this.assertAccountGeneration(r);const s=at(i,Hr,br);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Le(s)||typeof s.deleted!="boolean")throw Oe(`${Hr} 返回的 deleted 必须是布尔值`);return{deleted:s.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",vn("info"),async()=>{const i=await this.request(uT,{miniProgramId:r,...t}),s=at(i,qt,br);if(!Le(s)||typeof s.key!="string"||!gT.test(s.key))throw Oe(`${qt} 返回的 key 不合法`);if(t.key!==void 0&&s.key!==t.key)throw Oe(`${qt} 返回的 key 与请求不一致`);if(s.order!=="asc"&&s.order!=="desc")throw Oe(`${qt} 返回的 order 必须是 asc 或 desc`);if(typeof s.rank_limit!="number"||!Number.isInteger(s.rank_limit)||s.rank_limit<0)throw Oe(`${qt} 返回的 rankLimit 必须是非负整数`);return{key:s.key,order:s.order,rankLimit:s.rank_limit}})}read(t,r,n,i){this.assertUsable();const s=this.getOrCreateBucket(t),a=s?.caches[r],c=a?.get(n);if(c&&c.expiresAt>Date.now())return Promise.resolve(c.value);a?.delete(n);const u=vn(t,n),d=this.inflight.get(u);if(d)return d.promise;const l=this.accountGeneration,h=s?.generation,f=i().then(_=>(this.assertAccountGeneration(l),s&&a&&s.generation===h&&(r==="list"?a.size>=_T&&a.delete(a.keys().next().value):a.clear(),a.set(n,{expiresAt:Date.now()+pT,value:_})),_)).finally(()=>{this.inflight.get(u)?.promise===f&&this.inflight.delete(u),s&&this.removeEmptyBucket(t,s)});return this.inflight.set(u,{bucketKey:t,promise:f}),f}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=TT)return;const n={generation:0,caches:{list:new Map,current:new Map,info:new Map}};return this.buckets.set(t,n),n}invalidateMutableReads(t){this.invalidateInflight(t);const r=this.buckets.get(t);r&&(r.generation+=1,r.caches.list.clear(),r.caches.current.clear())}invalidateForAccountChange(){this.accountGeneration+=1,this.buckets.clear(),this.inflight.clear()}invalidateInflight(t){for(const[r,n]of this.inflight)n.bucketKey===t&&this.inflight.delete(r)}pruneExpiredBuckets(){const t=Date.now();for(const[r,n]of this.buckets)cd(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){cd(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await Se(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw ia(n)?n:na(br)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw oe("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw oe("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return vn(t,r??ET)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw oe("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return Ri({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:br,assertUsable:()=>this.assertUsable()},t,r)}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(ve(this.options.operationContext.signal),this.disposed)throw oe("INVALID_STATE","Cloud capability 已释放")}}function IT(e){return new AT(e)}function to(e,t){if(!Le(e))throw Oe(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw Oe(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw Oe(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw Oe(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw Oe(`${t} 返回的 score 必须是有限数字`);if(!Le(e.extra))throw Oe(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw Oe(`${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 cd(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function vn(...e){return JSON.stringify(e)}const bT={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.delete.post",method:"POST",path:"/user_miniprogram/cloud/storage/delete",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken,key:e.key}},parse(e,t){return Ve(e,"云端存储删除接口响应异常")}},ud={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.get.post",method:"POST",path:"/user_miniprogram/cloud/storage/get",body(e){return{key:e.key,runtime_auth_context_token:e.runtimeAuthContextToken}},parse(e,t){return Ve(e,"云端存储读取接口响应异常")}},dd={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.keys.post",method:"POST",path:"/user_miniprogram/cloud/storage/keys",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken}},parse(e,t){return Ve(e,"云端存储 key 列表接口响应异常")}},yT={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.set.post",method:"POST",path:"/user_miniprogram/cloud/storage/set",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken,key:e.key,value:e.value,expected_version:String(e.expectedVersion),expected_revision:e.expectedRevision}},parse(e,t){return Ve(e,"云端存储写入接口响应异常")}},yr="云端存储",NT=3e4,wT=128,DT=500;class ST{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Ci(t.account,r=>{this.observedUserId=r?.trim()||void 0,this.hasAccountObservation=!0,!(this.boundUserId===void 0||this.boundUserId===this.observedUserId)&&this.invalidateForAccountChange()}),t.operationContext.signal.aborted?this.dispose():t.operationContext.signal.addEventListener("abort",this.handleTerminalAbort,{once:!0})}accountGeneration=0;cache=new Map;inflight=new Map;keyGenerations=new Map;queues=new Map;activeKeys=new Set;timers=new Map;blockedKeys=new Map;unfinished=new Set;disposed=!1;boundScope;boundUserId;observedUserId;hasAccountObservation=!1;unsubscribeAccountChange;requestGateContext;handleTerminalAbort=()=>this.dispose();async getItem(t){const r=this.accountGeneration;await this.requireCurrentUser(r),this.assertAccountGeneration(r);const n=[...this.unfinished].filter(a=>a.key===t).at(-1);if(n)return n.kind==="set"?n.value:void 0;const i=this.keyGenerations.get(t)??0,s=await this.readStored(t,r,!1);return this.assertAccountGeneration(r),(this.keyGenerations.get(t)??0)!==i?this.getItem(t):(this.blockedKeys.delete(t),s.found?s.value:void 0)}setItem(t,r){return this.enqueue("set",t,r)}removeItem(t){return this.enqueue("remove",t,"")}async getKeys(){const t=this.accountGeneration;await this.requireCurrentUser(t),this.assertAccountGeneration(t);const r=at(await this.request(dd,{}),Fr,yr);if(this.assertAccountGeneration(t),!Le(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw Oe("cloud.storage.getKeys 返回的 keys 必须是字符串数组");const n=new Set(r.keys??[]);for(const i of this.unfinished)i.kind==="set"?n.add(i.key):n.delete(i.key);return[...n]}async enqueue(t,r,n){this.assertUsable(),this.readMiniProgramId();const i=this.accountGeneration;return await this.requireCurrentUser(i),this.assertAccountGeneration(i),t==="set"&&this.blockedKeys.has(r)?Promise.reject(this.blockedKeys.get(r)):new Promise((s,a)=>{const c=this.queues.get(r)??[],u=c.at(-1);if(t==="set"&&u?.kind==="set"&&u.generation===this.accountGeneration&&u.readyAt>Date.now())u.value=n,u.waiters.push({resolve:s,reject:a});else{const d={kind:t,key:r,value:n,generation:this.accountGeneration,readyAt:Date.now()+(t==="set"?DT:0),waiters:[{resolve:s,reject:a}]};c.push(d),this.unfinished.add(d)}this.queues.set(r,c),this.invalidateRead(r),this.drainKey(r)})}async drainKey(t){if(!this.activeKeys.has(t)){this.activeKeys.add(t);try{let r;for(;r=this.queues.get(t)?.[0];){const n=r.readyAt-Date.now();if(n>0){this.timers.has(t)||this.timers.set(t,setTimeout(()=>{this.timers.delete(t),this.drainKey(t)},n));break}this.queues.get(t).shift();try{if(await this.requireCurrentUser(r.generation),this.assertAccountGeneration(r.generation),r.kind==="remove"){const i=at(await this.request(bT,{key:t}),mn,yr);if(this.assertAccountGeneration(r.generation),!Le(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw Oe("删除结果不合法");this.writeCache(t,{value:"",found:!1,version:0,revision:""}),this.blockedKeys.delete(t)}else{const i=await this.readStored(t,r.generation,!0);if(this.assertAccountGeneration(r.generation),!Number.isSafeInteger(i.version+1))throw Oe("云存储版本超出安全整数范围");const s=at(await this.request(yT,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),hn,yr);if(this.assertAccountGeneration(r.generation),!Le(s)||s.success!==!0)throw Oe("云存储写入结果不合法");const a=ld({...s,found:!0,value:r.value});if(a.version!==i.version+1||i.found&&a.revision!==i.revision)throw Oe("写入版本凭证不匹配");this.writeCache(t,a)}this.finish(r)}catch(i){if(this.finish(r,i),r.generation===this.accountGeneration){this.cache.delete(t),this.blockedKeys.set(t,i);for(const s of this.queues.get(t)??[])this.finish(s,i);this.queues.delete(t)}}}}finally{this.activeKeys.delete(t),this.queues.get(t)?.length||this.queues.delete(t)}}}async readStored(t,r,n){this.assertAccountGeneration(r);const i=this.cache.get(t);if(i&&(n||i.expiresAt>Date.now()))return i.value;const s=this.inflight.get(t);if(s)return s;const a=this.keyGenerations.get(t)??0,c=this.request(ud,{key:t}).then(u=>{this.assertAccountGeneration(r);const d=ld(at(u,fn,yr));return(this.keyGenerations.get(t)??0)===a&&this.writeCache(t,d),d}).finally(()=>{this.inflight.get(t)===c&&this.inflight.delete(t)});return this.inflight.set(t,c),c}writeCache(t,r){this.cache.delete(t),this.cache.size>=wT&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+NT,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([ud.id,dd.id])}finish(t,r){if(this.unfinished.delete(t)){t.generation===this.accountGeneration&&this.invalidateRead(t.key);for(const n of t.waiters)r===void 0?n.resolve():n.reject(r)}}dispose(){this.disposed||(this.disposed=!0,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.purge(oe("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(oe("UNAUTHORIZED","登录状态已变化,请重试")),this.options.requestGate?.invalidateCoalescing()}purge(t){this.accountGeneration+=1;for(const r of this.timers.values())clearTimeout(r);this.timers.clear();for(const r of[...this.unfinished])this.finish(r,t);this.queues.clear(),this.blockedKeys.clear(),this.cache.clear(),this.inflight.clear(),this.keyGenerations.clear(),this.boundScope=void 0,this.boundUserId=void 0}async requireCurrentUser(t){this.assertAccountGeneration(t);const r=this.readMiniProgramId();let n;try{n=await Se(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw ia(s)?s:na(yr)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),oe("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),oe("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw oe("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw oe("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw oe("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw oe("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await Se(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(a){throw ia(a)?a:na(yr)}this.assertAccountGeneration(n);const s=i.token.trim();if(!s||i.expiresAt<=Date.now())throw oe("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return Ri({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:yr,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:s})}assertUsable(){if(ve(this.options.operationContext.signal),this.disposed)throw oe("INVALID_STATE","Cloud capability 已释放")}}function OT(e){return new ST(e)}function ld(e){if(!Le(e))throw Oe("云存储读取结果必须是对象");const t=e.found??!1,r=e.value??"",n=e.version??0,i=e.revision??"";if(typeof t!="boolean"||typeof r!="string"||typeof n!="number"||!Number.isSafeInteger(n)||n<0||typeof i!="string")throw Oe("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw Oe("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const MT=/^[A-Za-z0-9_-]{1,64}$/,fd=20,RT=100,hd=2048,CT=/^[A-Za-z0-9_-]{1,128}$/,md=16*1024;function LT(e){const t=IT(e),r=OT(e),n=aT(e);return{handlers:{...n.handlers,[tr]:async s=>t.submit(PT(s)),[vt]:async s=>t.getList(vT(s)),[gr]:async s=>t.getCurrentUserEntry(ro(s,gr)),[Hr]:async s=>t.deleteCurrentUserEntry(ro(s,Hr)),[qt]:async s=>t.getInfo(ro(s,qt)),[fn]:async s=>r.getItem(Ed(s,fn)),[hn]:async s=>{const{key:a,value:c}=kT(s);return r.setItem(a,c)},[mn]:async s=>r.removeItem(Ed(s,mn)),[Fr]:async s=>(UT(s),r.getKeys())},releaseRoomsForDocumentReload:n.releaseForReload,dispose:()=>{t.dispose(),r.dispose(),n.dispose()}}}function PT(e){const t=On(e,tr,!1);if(Mn(t,["key","score","extra"],tr),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw _t("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Wc(t.key,tr),score:t.score,...t.extra===void 0?{}:{extra:BT(t.extra)}}}function vT(e){if(e===void 0)return{limit:fd};const t=On(e,vt,!0);Mn(t,["key","limit","cursor"],vt);const r=t.limit===void 0?fd:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>RT)throw _t("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw _t("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Wc(t.key,vt),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function ro(e,t){if(e===void 0)return{};const r=On(e,t,!0);return Mn(r,["key"],t),Wc(r.key,t)}function Ed(e,t){const r=On(e,t,!1);return Mn(r,["key"],t),ih(r.key,t)}function kT(e){const t=hn,r=On(e,t,!1);Mn(r,["key","value"],t);const n=ih(r.key,t);if(typeof r.value!="string")throw _t("INVALID_PARAMS",`${t} value 必须是字符串`);if(xT(r.value))throw _t("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>md)throw _t("INVALID_PARAMS",`${t} value 不能超过 ${md} 字节`);return{key:n,value:r.value}}function xT(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=55296&&r<=56319){const n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return!0;t++}else if(r>=56320&&r<=57343)return!0}return!1}function UT(e){const t=On(e,Fr,!0);Mn(t,[],Fr)}function ih(e,t){if(typeof e!="string"||!CT.test(e))throw _t("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function On(e,t,r){if(e===void 0&&r)return{};if(!sh(e))throw _t("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Mn(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw _t("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Wc(e,t){if(e===void 0)return{};if(typeof e!="string"||!MT.test(e))throw _t("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function BT(e){if(!sh(e))throw _t("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw _t("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw _t("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>hd)throw _t("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${hd} 字节`);return e}function sh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _t(e,t){return{code:e,message:t}}const HT={auth:"optional",channel:"api",id:"heybox.user_miniprogram.runtime.game_saves.post",method:"POST",path:"/user_miniprogram/runtime/game_saves",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return Ve(e,"游戏存档接口响应异常")}},FT=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function jo(e,t=0){return t>64?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e)&&(!Number.isInteger(e)||Number.isSafeInteger(e)):Array.isArray(e)?e.every(r=>jo(r,t+1)):Le(e)&&Object.values(e).every(r=>jo(r,t+1))}function zT(e,t){const r=FT.get(t);if(!r||Le(e)&&e.status==="unsupported")return{status:"unsupported"};if(Le(e)&&e.game===r){if(e.status==="empty")return{status:"empty"};if(e.status==="failed"&&["UNAUTHORIZED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED"].includes(String(e.error_code)))throw oe(String(e.error_code),"账号或授权已变化");if(e.status==="ready"&&Le(e.data)&&jo(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function ah(e){const t=new Map,r=new Map,n=u=>u.resource?`hb_runtime_game_save_resource_sync_v1_${[u.miniProgramId,u.userId,u.resource].map(encodeURIComponent).join(":")}`:`hb_runtime_game_save_sync_v1_${[u.miniProgramId,u.userId,u.gameId].map(encodeURIComponent).join(":")}`;async function i(u,d,l){const h=n(u),f=r.get(h)??Promise.resolve();let _;const p=new Promise(w=>{_=w}),y=f.then(()=>p);r.set(h,y);try{return await Se(()=>f,d.signal),ve(d.signal),e?.withLock?await e.withLock(h,l):await l()}finally{_(),r.get(h)===y&&y.then(()=>{r.get(h)===y&&r.delete(h)})}}async function s(u,d,l=!1){const h=n(u);if(!l&&t.has(h)||!e)return t.get(h);try{const f=await Se(()=>e.getRaw(h,d),d.signal);if(!f)return;const _=JSON.parse(f);if(!_||typeof _!="object")return;const p=_;return p.version!==1||p.miniProgramId!==u.miniProgramId||p.userId!==u.userId||p.gameId!==u.gameId||(u.resource?p.resource!==u.resource:typeof p.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(p.accountId))||typeof p.taskId!="string"||(u.resource?p.taskId.length<1||p.taskId.length>128:!/^[1-9][0-9]{0,19}$/.test(p.taskId))?void 0:(l||t.set(h,p),p)}catch(f){if(ve(d.signal),l)throw f;return t.get(h)}}async function a(u,d,l){ve(l.signal);const h=n(u),f=d?{...u,version:1,taskId:d}:void 0;if(t.set(h,f),!!e)try{await Se(()=>e.setRaw(h,f?JSON.stringify(f):"",l),l.signal)}catch{ve(l.signal)}}async function c(u,d,l){await i(u,l,async()=>{const h=n(u),f=t.get(h),_=f?.taskId===d&&f.accountId===u.accountId;let p;try{p=await s(u,l,!0)}catch{ve(l.signal),_&&t.set(h,void 0);return}p?.taskId===d&&p.accountId===u.accountId?(await a(u,void 0,l),f&&!_&&t.set(h,f)):_&&t.set(h,p)})}return{run:i,async get(u,d){const l=await s(u,d);if(l&&l.accountId!==u.accountId){t.delete(n(u));return}return l?.taskId},set:a,remove:c,clear(u){for(const d of t.values())d&&c(d,d.taskId,u).catch(()=>{})}}}const jT=2e3,VT=5*6e4;function GT(e){const t=ah(e.storage);let r=0,n=!1,i;const s=e.fileDownloads??(e.files&&e.transfer?qc({files:e.files,transfer:e.transfer,registry:e.fileRegistry,signal:e.operationContext.signal}):void 0),a=new Set,c=new Map,u={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},d=v=>s?.release(v)??Promise.resolve(),l=new Set;let h=new AbortController,f;const _=()=>{h.abort(),h=new AbortController,f=void 0},p=(v=!0)=>{v&&t.clear(u),r++,_();for(const W of l)W.abort();for(const W of a)d(W).catch(()=>{});a.clear(),c.clear()},y=Ci(e.account,v=>{i&&v!==i&&(p(),i=void 0)}),w=e.authorization.onEvent(()=>p());function N(v,W,q,te){if(O(q),te.signal.aborted||!v.account_id||!e.presentation?.showSteamLoginRequired)return;const F=`${v.account_id}:${v.game_id}:${v.task_id??"sync"}`;if(f!==F){f=F;try{e.presentation.showSteamLoginRequired({userId:W,accountId:v.account_id},Ue(e.operationContext,h.signal))}catch{}}}function O(v){if(n||e.operationContext.signal.aborted)throw oe("RUNTIME_DESTROYED","小程序已关闭");if(v!==r)throw oe("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function I(v,W,q){if(O(W),await e.account.getCurrentUserId(q)!==v)throw p(),oe("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");O(W)}async function H(v,W,q,te){if(await I(W,q,te),!e.authorizationContext)throw oe("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const F=await e.authorizationContext.get(te);if(!F.token||F.expiresAt<=Date.now())throw oe("UNAUTHORIZED","小程序运行上下文已过期");const G=await Ri({network:e.network,operationContext:te,subject:"游戏存档",assertUsable:()=>O(q),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},HT,{...v,runtime_auth_context_token:F.token});if(await I(W,q,te),G.status==="failed"&&Le(G.result)&&G.result.error_code==="RECENT_SAVE_AVAILABLE")throw oe("RECENT_SAVE_AVAILABLE",typeof G.msg=="string"&&G.msg?G.msg:"已有近期存档,请直接查询使用");const j=at(G,v.action,"游戏存档");if(!Le(j))throw oe("INVALID_RESPONSE","存档响应不合法");return j}async function Q(v,W,q){const te=YT(v,W),F=r;if(O(F),v==="file"&&(!e.transfer||!e.files))throw oe("METHOD_FORBIDDEN","宿主不支持存档文件读取");const G=new AbortController;l.add(G);let j=!1;const z=v==="sync"?setTimeout(()=>{j=!0,G.abort()},VT):void 0,V=Ue(Ue(e.operationContext,q.signal),G.signal);try{const U=await e.account.getCurrentUserId(V);if(!U)throw oe("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==U)throw p(),oe("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=U,v==="sync"||v==="parsed"){if(v==="sync"&&_(),!te.account_id){const Z=await H({action:"check",game_id:te.game_id},U,F,V);te.account_id=Ti(Z.account_id)}if(v==="sync")return await M(te,U,F,V)}const k=await H({action:v,...te},U,F,V);if(v==="list")return qT(k);if(v==="parsed")return zT(k.parsed_data,te.game_id);if(oh(k.file).fileId!==te.file_id)throw oe("INVALID_RESPONSE","文件标识不匹配");if(!s)throw oe("REQUEST_UNSUPPORTED","宿主不支持存档下载");const R=await s.download(k,async Z=>{try{O(F),await H({action:"check",game_id:te.game_id,account_id:te.account_id},U,F,Z)}catch(ee){const se=Le(ee)?String(ee.code):"";throw["RUNTIME_DESTROYED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED","UNAUTHORIZED"].includes(se)?(p(),oe("FILE_ACCESS_REVOKED","游戏存档授权已失效")):ee}},V);let K=!1;try{if(await I(U,F,V),O(F),V.signal.aborted)throw oe("DOWNLOAD_CANCELLED","存档下载已取消");const Z=e.fileRegistry.registerFile(R,"game-save","read");return a.add(R),c.set(zc(),{file:R,sizeBytes:s.sizeOf(R)}),K=!0,Z}finally{K||await s.release(R)}}catch(U){throw j?oe("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):U}finally{z!==void 0&&clearTimeout(z),l.delete(G)}}async function M(v,W,q,te){const F=e.identity.get()?.miniProgramId;if(!F)throw oe("INVALID_STATE","小程序身份尚未确认");const G={miniProgramId:F,userId:W,gameId:v.game_id,accountId:v.account_id},j=V=>H({action:"status",...v,task_id:V},W,q,te);let z;try{const V=await t.run(G,te,async()=>{await I(W,q,te);const k=await t.get(G,te);if(k){z=k;try{return{taskId:k,status:await j(k)}}catch(R){if(!Le(R)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(R.code)))throw R;await t.set(G,void 0,te),z=void 0}}const Y=await H({action:"sync",...v},W,q,te);return z=Ti(Y.task_id),await t.set(G,z,te),await I(W,q,te),{taskId:z,status:void 0}});z=V.taskId;let U=V.status;for(;;){if(O(q),te.signal.aborted)throw oe("REQUEST_CANCELLED","已停止等待存档同步");if(U??=await j(z),U.state==="succeeded"||U.state==="failed"){if(await t.remove(G,z,te),await I(W,q,te),U.state==="succeeded")return{state:"succeeded"};throw oe(U.error_code?sa(U.error_code):"SYNC_FAILED",U.message?sa(U.message):"存档同步失败")}if(U.state!=="syncing"&&U.state!=="uploading")throw oe("INVALID_RESPONSE","同步状态不合法");U=void 0,await QT(jT,te.signal)}}catch(V){if(Le(V)){const U=String(V.code);U==="STEAM_LOGIN_REQUIRED"&&N({...v,task_id:z},W,q,te),z&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(U)&&await t.remove(G,z,u)}throw V}}return{handlers:{"gameSaves.list":(v,W)=>Q("list",v,W),"gameSaves.sync":(v,W)=>Q("sync",v,W),"gameSaves.readParsedData":(v,W)=>Q("parsed",v,W),"gameSaves.getFile":(v,W)=>Q("file",v,W)},diagnostics:{async getSnapshot(){const v=r;return i&&await I(i,v,e.operationContext),O(v),Array.from(c,([W,q])=>({id:W,name:q.file.name,sizeBytes:q.sizeBytes}))},async readFile(v,W){const q=r;O(q);const te=c.get(v);if(!te)throw oe("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const F=Ue(e.operationContext,W);F.signal.throwIfAborted();const G=await te.file.read(F);try{return F.signal.throwIfAborted(),O(q),{name:te.file.name,bytes:G}}catch(j){throw G.fill(0),j}}},allowsRead(v,W){return["file.readBytes","file.readText","file.stat","file.exists"].includes(v)&&Le(W)&&e.fileRegistry.isGameSaveRef(W.target)},dispose(){n||(n=!0,p(!1),y(),w())}}}function YT(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!Le(t)||Object.keys(t).some(i=>!r.includes(i)))throw oe("INVALID_PARAMS","存档参数不合法");const n=Gn(t.gameId);if(Number(n)>2147483647)throw oe("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:Gn(t.accountId)}:{},...e==="file"?{save_id:Gn(t.saveId),file_id:Gn(t.fileId)}:{}}}function Gn(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw oe("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function Ti(e){try{return Gn(e)}catch{throw oe("INVALID_RESPONSE","服务端存档标识无效")}}function sa(e){if(typeof e!="string")throw oe("INVALID_RESPONSE","服务端存档字段无效");return e}function Vo(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw oe("INVALID_RESPONSE","服务端存档数值无效");return e}function oh(e){if(!Le(e))throw oe("INVALID_RESPONSE","存档文件信息无效");return{fileId:Ti(e.file_id),name:sa(e.name),originalPath:sa(e.original_path),sizeBytes:Vo(e.size_bytes),modifiedAt:Vo(e.modified_at)}}function qT(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw oe("INVALID_RESPONSE","存档列表无效");return{accountId:Ti(e.account_id),saves:e.saves.map(t=>{if(!Le(t)||!Array.isArray(t.files)||t.files.length>200)throw oe("INVALID_RESPONSE","存档文件列表无效");return{saveId:Ti(t.save_id),createdAt:Vo(t.created_at),files:t.files.map(oh)}})}}function QT(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(s),t.removeEventListener("abort",i),n(oe("REQUEST_CANCELLED","已停止等待存档同步"))},s=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}function ch(e,t){return{auth:"optional",channel:"api",id:e,method:"GET",path:t,query(r){return{...r}},parse(r){return Zf(r,"赛事中心接口响应异常")}}}function uh(e,t){return{auth:"optional",bodyEncoding:"form",body(r){return{...r.body}},channel:"api",id:e,method:"POST",path:t,query(r){return r.query?{...r.query}:void 0},parse(r){return Zf(r,"赛事中心接口响应异常")}}}const WT=ch("heybox.bbs.app.link.tree.get","/bbs/app/link/tree"),$T=ch("heybox.bbs.app.comment.sub.comments.get","/bbs/app/comment/sub/comments"),KT=uh("heybox.bbs.app.comment.support.post","/bbs/app/comment/support"),ZT=uh("heybox.bbs.app.comment.delete.post","/bbs/app/comment/delete");function va(e){return Ve(e,"社区评论响应异常")}const gd={...WT,parse:va},XT={...$T,parse:va},JT={...KT,bodyEncoding:"form",body:e=>Object.fromEntries(Object.entries(e.body).map(([t,r])=>[t,String(r)])),parse:va},eA={...ZT,bodyEncoding:"form",body:e=>Object.fromEntries(Object.entries(e.body).map(([t,r])=>[t,String(r)])),parse:va},tA={auth:"optional",channel:"api",id:"heybox.user_miniprogram.post.favorite",method:"POST",path:"/bbs/app/link/favour",bodyEncoding:"form",failurePresentation:"none",body:e=>({link_id:e.targetId,favour_type:e.enabled?1:0}),parse:e=>Ve(e,"社区操作响应异常")},rA={auth:"optional",channel:"api",id:"heybox.user_miniprogram.post.like",method:"POST",path:"/bbs/app/profile/award/link",bodyEncoding:"form",failurePresentation:"none",body:e=>({link_id:e.targetId,award_type:e.enabled?"1":"0"}),parse:e=>Ve(e,"社区操作响应异常")},nA={auth:"optional",channel:"api",id:"heybox.user_miniprogram.runtime.post.read",method:"POST",path:"/user_miniprogram/runtime/post",bodyEncoding:"form",failurePresentation:"none",body:e=>({...e}),parse:e=>Ve(e,"关联帖子响应异常")},iA=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),Ye="�";var g;(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z"})(g||(g={}));const Et={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function dh(e){return e>=55296&&e<=57343}function sA(e){return e>=56320&&e<=57343}function aA(e,t){return(e-55296)*1024+9216+t}function lh(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function fh(e){return e>=64976&&e<=65007||iA.has(e)}var $;(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text"})($||($={}));const oA=65536;class cA{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=oA,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,r){const{line:n,col:i,offset:s}=this,a=i+r,c=s+r;return{code:t,startLine:n,endLine:n,startCol:a,endCol:a,startOffset:c,endOffset:c}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(t){if(this.pos!==this.html.length-1){const r=this.html.charCodeAt(this.pos+1);if(sA(r))return this.pos++,this._addGap(),aA(t,r)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,g.EOF;return this._err($.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(t,r){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=!1,this.lastChunkWritten=r}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(t,r){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(r)return this.html.startsWith(t,this.pos);for(let n=0;n<t.length;n++)if((this.html.charCodeAt(this.pos+n)|32)!==t.charCodeAt(n))return!1;return!0}peek(t){const r=this.pos+t;if(r>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,g.EOF;const n=this.html.charCodeAt(r);return n===g.CARRIAGE_RETURN?g.LINE_FEED:n}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,g.EOF;let t=this.html.charCodeAt(this.pos);return t===g.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,g.LINE_FEED):t===g.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,dh(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===g.LINE_FEED||t===g.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){lh(t)?this._err($.controlCharacterInInputStream):fh(t)&&this._err($.noncharacterInInputStream)}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}}var xe;(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION"})(xe||(xe={}));function hh(e,t){for(let r=e.attrs.length-1;r>=0;r--)if(e.attrs[r].name===t)return e.attrs[r].value;return null}const uA=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),dA=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function lA(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=dA.get(e))!==null&&t!==void 0?t:e}var et;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"})(et||(et={}));const fA=32;var hr;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(hr||(hr={}));function Go(e){return e>=et.ZERO&&e<=et.NINE}function hA(e){return e>=et.UPPER_A&&e<=et.UPPER_F||e>=et.LOWER_A&&e<=et.LOWER_F}function mA(e){return e>=et.UPPER_A&&e<=et.UPPER_Z||e>=et.LOWER_A&&e<=et.LOWER_Z||Go(e)}function EA(e){return e===et.EQUALS||mA(e)}var Xe;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(Xe||(Xe={}));var er;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(er||(er={}));class gA{constructor(t,r,n){this.decodeTree=t,this.emitCodePoint=r,this.errors=n,this.state=Xe.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=er.Strict}startEntity(t){this.decodeMode=t,this.state=Xe.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(t,r){switch(this.state){case Xe.EntityStart:return t.charCodeAt(r)===et.NUM?(this.state=Xe.NumericStart,this.consumed+=1,this.stateNumericStart(t,r+1)):(this.state=Xe.NamedEntity,this.stateNamedEntity(t,r));case Xe.NumericStart:return this.stateNumericStart(t,r);case Xe.NumericDecimal:return this.stateNumericDecimal(t,r);case Xe.NumericHex:return this.stateNumericHex(t,r);case Xe.NamedEntity:return this.stateNamedEntity(t,r)}}stateNumericStart(t,r){return r>=t.length?-1:(t.charCodeAt(r)|fA)===et.LOWER_X?(this.state=Xe.NumericHex,this.consumed+=1,this.stateNumericHex(t,r+1)):(this.state=Xe.NumericDecimal,this.stateNumericDecimal(t,r))}addToNumericResult(t,r,n,i){if(r!==n){const s=n-r;this.result=this.result*Math.pow(i,s)+Number.parseInt(t.substr(r,s),i),this.consumed+=s}}stateNumericHex(t,r){const n=r;for(;r<t.length;){const i=t.charCodeAt(r);if(Go(i)||hA(i))r+=1;else return this.addToNumericResult(t,n,r,16),this.emitNumericEntity(i,3)}return this.addToNumericResult(t,n,r,16),-1}stateNumericDecimal(t,r){const n=r;for(;r<t.length;){const i=t.charCodeAt(r);if(Go(i))r+=1;else return this.addToNumericResult(t,n,r,10),this.emitNumericEntity(i,2)}return this.addToNumericResult(t,n,r,10),-1}emitNumericEntity(t,r){var n;if(this.consumed<=r)return(n=this.errors)===null||n===void 0||n.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===et.SEMI)this.consumed+=1;else if(this.decodeMode===er.Strict)return 0;return this.emitCodePoint(lA(this.result),this.consumed),this.errors&&(t!==et.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,r){const{decodeTree:n}=this;let i=n[this.treeIndex],s=(i&hr.VALUE_LENGTH)>>14;for(;r<t.length;r++,this.excess++){const a=t.charCodeAt(r);if(this.treeIndex=pA(n,i,this.treeIndex+Math.max(1,s),a),this.treeIndex<0)return this.result===0||this.decodeMode===er.Attribute&&(s===0||EA(a))?0:this.emitNotTerminatedNamedEntity();if(i=n[this.treeIndex],s=(i&hr.VALUE_LENGTH)>>14,s!==0){if(a===et.SEMI)return this.emitNamedEntityData(this.treeIndex,s,this.consumed+this.excess);this.decodeMode!==er.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var t;const{result:r,decodeTree:n}=this,i=(n[r]&hr.VALUE_LENGTH)>>14;return this.emitNamedEntityData(r,i,this.consumed),(t=this.errors)===null||t===void 0||t.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,r,n){const{decodeTree:i}=this;return this.emitCodePoint(r===1?i[t]&~hr.VALUE_LENGTH:i[t+1],n),r===3&&this.emitCodePoint(i[t+2],n),n}end(){var t;switch(this.state){case Xe.NamedEntity:return this.result!==0&&(this.decodeMode!==er.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Xe.NumericDecimal:return this.emitNumericEntity(0,2);case Xe.NumericHex:return this.emitNumericEntity(0,3);case Xe.NumericStart:return(t=this.errors)===null||t===void 0||t.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Xe.EntityStart:return 0}}}function pA(e,t,r,n){const i=(t&hr.BRANCH_LENGTH)>>7,s=t&hr.JUMP_TABLE;if(i===0)return s!==0&&n===s?r:-1;if(s){const u=n-s;return u<0||u>=i?-1:e[r+u]-1}let a=r,c=a+i-1;for(;a<=c;){const u=a+c>>>1,d=e[u];if(d<n)a=u+1;else if(d>n)c=u-1;else return e[u+i]}return-1}var ne;(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/"})(ne||(ne={}));var xr;(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size"})(xr||(xr={}));var wt;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"})(wt||(wt={}));var B;(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp"})(B||(B={}));var o;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP"})(o||(o={}));const _A=new Map([[B.A,o.A],[B.ADDRESS,o.ADDRESS],[B.ANNOTATION_XML,o.ANNOTATION_XML],[B.APPLET,o.APPLET],[B.AREA,o.AREA],[B.ARTICLE,o.ARTICLE],[B.ASIDE,o.ASIDE],[B.B,o.B],[B.BASE,o.BASE],[B.BASEFONT,o.BASEFONT],[B.BGSOUND,o.BGSOUND],[B.BIG,o.BIG],[B.BLOCKQUOTE,o.BLOCKQUOTE],[B.BODY,o.BODY],[B.BR,o.BR],[B.BUTTON,o.BUTTON],[B.CAPTION,o.CAPTION],[B.CENTER,o.CENTER],[B.CODE,o.CODE],[B.COL,o.COL],[B.COLGROUP,o.COLGROUP],[B.DD,o.DD],[B.DESC,o.DESC],[B.DETAILS,o.DETAILS],[B.DIALOG,o.DIALOG],[B.DIR,o.DIR],[B.DIV,o.DIV],[B.DL,o.DL],[B.DT,o.DT],[B.EM,o.EM],[B.EMBED,o.EMBED],[B.FIELDSET,o.FIELDSET],[B.FIGCAPTION,o.FIGCAPTION],[B.FIGURE,o.FIGURE],[B.FONT,o.FONT],[B.FOOTER,o.FOOTER],[B.FOREIGN_OBJECT,o.FOREIGN_OBJECT],[B.FORM,o.FORM],[B.FRAME,o.FRAME],[B.FRAMESET,o.FRAMESET],[B.H1,o.H1],[B.H2,o.H2],[B.H3,o.H3],[B.H4,o.H4],[B.H5,o.H5],[B.H6,o.H6],[B.HEAD,o.HEAD],[B.HEADER,o.HEADER],[B.HGROUP,o.HGROUP],[B.HR,o.HR],[B.HTML,o.HTML],[B.I,o.I],[B.IMG,o.IMG],[B.IMAGE,o.IMAGE],[B.INPUT,o.INPUT],[B.IFRAME,o.IFRAME],[B.KEYGEN,o.KEYGEN],[B.LABEL,o.LABEL],[B.LI,o.LI],[B.LINK,o.LINK],[B.LISTING,o.LISTING],[B.MAIN,o.MAIN],[B.MALIGNMARK,o.MALIGNMARK],[B.MARQUEE,o.MARQUEE],[B.MATH,o.MATH],[B.MENU,o.MENU],[B.META,o.META],[B.MGLYPH,o.MGLYPH],[B.MI,o.MI],[B.MO,o.MO],[B.MN,o.MN],[B.MS,o.MS],[B.MTEXT,o.MTEXT],[B.NAV,o.NAV],[B.NOBR,o.NOBR],[B.NOFRAMES,o.NOFRAMES],[B.NOEMBED,o.NOEMBED],[B.NOSCRIPT,o.NOSCRIPT],[B.OBJECT,o.OBJECT],[B.OL,o.OL],[B.OPTGROUP,o.OPTGROUP],[B.OPTION,o.OPTION],[B.P,o.P],[B.PARAM,o.PARAM],[B.PLAINTEXT,o.PLAINTEXT],[B.PRE,o.PRE],[B.RB,o.RB],[B.RP,o.RP],[B.RT,o.RT],[B.RTC,o.RTC],[B.RUBY,o.RUBY],[B.S,o.S],[B.SCRIPT,o.SCRIPT],[B.SEARCH,o.SEARCH],[B.SECTION,o.SECTION],[B.SELECT,o.SELECT],[B.SOURCE,o.SOURCE],[B.SMALL,o.SMALL],[B.SPAN,o.SPAN],[B.STRIKE,o.STRIKE],[B.STRONG,o.STRONG],[B.STYLE,o.STYLE],[B.SUB,o.SUB],[B.SUMMARY,o.SUMMARY],[B.SUP,o.SUP],[B.TABLE,o.TABLE],[B.TBODY,o.TBODY],[B.TEMPLATE,o.TEMPLATE],[B.TEXTAREA,o.TEXTAREA],[B.TFOOT,o.TFOOT],[B.TD,o.TD],[B.TH,o.TH],[B.THEAD,o.THEAD],[B.TITLE,o.TITLE],[B.TR,o.TR],[B.TRACK,o.TRACK],[B.TT,o.TT],[B.U,o.U],[B.UL,o.UL],[B.SVG,o.SVG],[B.VAR,o.VAR],[B.WBR,o.WBR],[B.XMP,o.XMP]]);function ka(e){var t;return(t=_A.get(e))!==null&&t!==void 0?t:o.UNKNOWN}const ae=o,TA={[ne.HTML]:new Set([ae.ADDRESS,ae.APPLET,ae.AREA,ae.ARTICLE,ae.ASIDE,ae.BASE,ae.BASEFONT,ae.BGSOUND,ae.BLOCKQUOTE,ae.BODY,ae.BR,ae.BUTTON,ae.CAPTION,ae.CENTER,ae.COL,ae.COLGROUP,ae.DD,ae.DETAILS,ae.DIR,ae.DIV,ae.DL,ae.DT,ae.EMBED,ae.FIELDSET,ae.FIGCAPTION,ae.FIGURE,ae.FOOTER,ae.FORM,ae.FRAME,ae.FRAMESET,ae.H1,ae.H2,ae.H3,ae.H4,ae.H5,ae.H6,ae.HEAD,ae.HEADER,ae.HGROUP,ae.HR,ae.HTML,ae.IFRAME,ae.IMG,ae.INPUT,ae.LI,ae.LINK,ae.LISTING,ae.MAIN,ae.MARQUEE,ae.MENU,ae.META,ae.NAV,ae.NOEMBED,ae.NOFRAMES,ae.NOSCRIPT,ae.OBJECT,ae.OL,ae.P,ae.PARAM,ae.PLAINTEXT,ae.PRE,ae.SCRIPT,ae.SECTION,ae.SELECT,ae.SOURCE,ae.STYLE,ae.SUMMARY,ae.TABLE,ae.TBODY,ae.TD,ae.TEMPLATE,ae.TEXTAREA,ae.TFOOT,ae.TH,ae.THEAD,ae.TITLE,ae.TR,ae.TRACK,ae.UL,ae.WBR,ae.XMP]),[ne.MATHML]:new Set([ae.MI,ae.MO,ae.MN,ae.MS,ae.MTEXT,ae.ANNOTATION_XML]),[ne.SVG]:new Set([ae.TITLE,ae.FOREIGN_OBJECT,ae.DESC]),[ne.XLINK]:new Set,[ne.XML]:new Set,[ne.XMLNS]:new Set},Yo=new Set([ae.H1,ae.H2,ae.H3,ae.H4,ae.H5,ae.H6]);B.STYLE,B.SCRIPT,B.XMP,B.IFRAME,B.NOEMBED,B.NOFRAMES,B.PLAINTEXT;var A;(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND"})(A||(A={}));const pt={DATA:A.DATA,RCDATA:A.RCDATA,RAWTEXT:A.RAWTEXT,SCRIPT_DATA:A.SCRIPT_DATA,PLAINTEXT:A.PLAINTEXT,CDATA_SECTION:A.CDATA_SECTION};function AA(e){return e>=g.DIGIT_0&&e<=g.DIGIT_9}function Yn(e){return e>=g.LATIN_CAPITAL_A&&e<=g.LATIN_CAPITAL_Z}function IA(e){return e>=g.LATIN_SMALL_A&&e<=g.LATIN_SMALL_Z}function or(e){return IA(e)||Yn(e)}function pd(e){return or(e)||AA(e)}function Vi(e){return e+32}function mh(e){return e===g.SPACE||e===g.LINE_FEED||e===g.TABULATION||e===g.FORM_FEED}function _d(e){return mh(e)||e===g.SOLIDUS||e===g.GREATER_THAN_SIGN}function bA(e){return e===g.NULL?$.nullCharacterReference:e>1114111?$.characterReferenceOutsideUnicodeRange:dh(e)?$.surrogateCharacterReference:fh(e)?$.noncharacterCharacterReference:lh(e)||e===g.CARRIAGE_RETURN?$.controlCharacterReference:null}class yA{constructor(t,r){this.options=t,this.handler=r,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,this.state=A.DATA,this.returnState=A.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new cA(r),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new gA(uA,(n,i)=>{this.preprocessor.pos=this.entityStartPos+i-1,this._flushCodePointConsumedAsCharacterReference(n)},r.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err($.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:n=>{this._err($.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+n)},validateNumericCharacterReference:n=>{const i=bA(n);i&&this._err(i,1)}}:void 0)}_err(t,r=0){var n,i;(i=(n=this.handler).onParseError)===null||i===void 0||i.call(n,this.preprocessor.getError(t,r))}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;const t=this._consume();this._ensureHibernation()||this._callState(t)}this.inLoop=!1}}pause(){this.paused=!0}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,!this.inLoop&&(this._runParsingLoop(),this.paused||t?.())}write(t,r,n){this.active=!0,this.preprocessor.write(t,r),this._runParsingLoop(),this.paused||n?.()}insertHtmlAtCurrentPos(t){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop()}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0):!1}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let r=0;r<t;r++)this.preprocessor.advance()}_consumeSequenceIfMatch(t,r){return this.preprocessor.startsWith(t,r)?(this._advanceBy(t.length-1),!0):!1}_createStartTagToken(){this.currentToken={type:xe.START_TAG,tagName:"",tagID:o.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:xe.END_TAG,tagName:"",tagID:o.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(t){this.currentToken={type:xe.COMMENT,data:"",location:this.getCurrentLocation(t)}}_createDoctypeToken(t){this.currentToken={type:xe.DOCTYPE,name:t,forceQuirks:!1,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(t,r){this.currentCharacterToken={type:t,chars:r,location:this.currentLocation}}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var t,r;const n=this.currentToken;if(hh(n,this.currentAttr.name)===null){if(n.attrs.push(this.currentAttr),n.location&&this.currentLocation){const i=(t=(r=n.location).attrs)!==null&&t!==void 0?t:r.attrs=Object.create(null);i[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err($.duplicateAttribute)}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset)}prepareToken(t){this._emitCurrentCharacterToken(t.location),this.currentToken=null,t.location&&(t.location.endLine=this.preprocessor.line,t.location.endCol=this.preprocessor.col+1,t.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){const t=this.currentToken;this.prepareToken(t),t.tagID=ka(t.tagName),t.type===xe.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err($.endTagWithAttributes),t.selfClosing&&this._err($.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk()}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case xe.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case xe.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case xe.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null}}_emitEOFToken(){const t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:xe.EOF,location:t}),this.active=!1}_appendCharToCurrentCharacterToken(t,r){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=r;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,r)}_emitCodePoint(t){const r=mh(t)?xe.WHITESPACE_CHARACTER:t===g.NULL?xe.NULL_CHARACTER:xe.CHARACTER;this._appendCharToCurrentCharacterToken(r,String.fromCodePoint(t))}_emitChars(t){this._appendCharToCurrentCharacterToken(xe.CHARACTER,t)}_startCharacterReference(){this.returnState=this.state,this.state=A.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?er.Attribute:er.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===A.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===A.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===A.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t)}_callState(t){switch(this.state){case A.DATA:{this._stateData(t);break}case A.RCDATA:{this._stateRcdata(t);break}case A.RAWTEXT:{this._stateRawtext(t);break}case A.SCRIPT_DATA:{this._stateScriptData(t);break}case A.PLAINTEXT:{this._statePlaintext(t);break}case A.TAG_OPEN:{this._stateTagOpen(t);break}case A.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case A.TAG_NAME:{this._stateTagName(t);break}case A.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case A.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case A.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case A.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case A.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case A.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case A.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case A.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case A.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case A.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case A.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case A.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case A.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case A.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case A.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case A.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case A.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case A.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case A.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case A.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case A.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case A.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case A.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case A.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case A.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case A.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case A.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case A.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case A.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case A.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case A.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case A.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case A.BOGUS_COMMENT:{this._stateBogusComment(t);break}case A.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case A.COMMENT_START:{this._stateCommentStart(t);break}case A.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case A.COMMENT:{this._stateComment(t);break}case A.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case A.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case A.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case A.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case A.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case A.COMMENT_END:{this._stateCommentEnd(t);break}case A.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case A.DOCTYPE:{this._stateDoctype(t);break}case A.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case A.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case A.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case A.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case A.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case A.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case A.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case A.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case A.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case A.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case A.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case A.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case A.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case A.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case A.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case A.CDATA_SECTION:{this._stateCdataSection(t);break}case A.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case A.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case A.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case A.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case g.LESS_THAN_SIGN:{this.state=A.TAG_OPEN;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err($.unexpectedNullCharacter),this._emitCodePoint(t);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRcdata(t){switch(t){case g.AMPERSAND:{this._startCharacterReference();break}case g.LESS_THAN_SIGN:{this.state=A.RCDATA_LESS_THAN_SIGN;break}case g.NULL:{this._err($.unexpectedNullCharacter),this._emitChars(Ye);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRawtext(t){switch(t){case g.LESS_THAN_SIGN:{this.state=A.RAWTEXT_LESS_THAN_SIGN;break}case g.NULL:{this._err($.unexpectedNullCharacter),this._emitChars(Ye);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptData(t){switch(t){case g.LESS_THAN_SIGN:{this.state=A.SCRIPT_DATA_LESS_THAN_SIGN;break}case g.NULL:{this._err($.unexpectedNullCharacter),this._emitChars(Ye);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case g.NULL:{this._err($.unexpectedNullCharacter),this._emitChars(Ye);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateTagOpen(t){if(or(t))this._createStartTagToken(),this.state=A.TAG_NAME,this._stateTagName(t);else switch(t){case g.EXCLAMATION_MARK:{this.state=A.MARKUP_DECLARATION_OPEN;break}case g.SOLIDUS:{this.state=A.END_TAG_OPEN;break}case g.QUESTION_MARK:{this._err($.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=A.BOGUS_COMMENT,this._stateBogusComment(t);break}case g.EOF:{this._err($.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err($.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=A.DATA,this._stateData(t)}}_stateEndTagOpen(t){if(or(t))this._createEndTagToken(),this.state=A.TAG_NAME,this._stateTagName(t);else switch(t){case g.GREATER_THAN_SIGN:{this._err($.missingEndTagName),this.state=A.DATA;break}case g.EOF:{this._err($.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err($.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=A.BOGUS_COMMENT,this._stateBogusComment(t)}}_stateTagName(t){const r=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=A.BEFORE_ATTRIBUTE_NAME;break}case g.SOLIDUS:{this.state=A.SELF_CLOSING_START_TAG;break}case g.GREATER_THAN_SIGN:{this.state=A.DATA,this.emitCurrentTagToken();break}case g.NULL:{this._err($.unexpectedNullCharacter),r.tagName+=Ye;break}case g.EOF:{this._err($.eofInTag),this._emitEOFToken();break}default:r.tagName+=String.fromCodePoint(Yn(t)?Vi(t):t)}}_stateRcdataLessThanSign(t){t===g.SOLIDUS?this.state=A.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=A.RCDATA,this._stateRcdata(t))}_stateRcdataEndTagOpen(t){or(t)?(this.state=A.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=A.RCDATA,this._stateRcdata(t))}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();const r=this.currentToken;switch(r.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=A.BEFORE_ATTRIBUTE_NAME,!1;case g.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=A.SELF_CLOSING_START_TAG,!1;case g.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=A.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=A.RCDATA,this._stateRcdata(t))}_stateRawtextLessThanSign(t){t===g.SOLIDUS?this.state=A.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=A.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagOpen(t){or(t)?(this.state=A.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=A.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=A.RAWTEXT,this._stateRawtext(t))}_stateScriptDataLessThanSign(t){switch(t){case g.SOLIDUS:{this.state=A.SCRIPT_DATA_END_TAG_OPEN;break}case g.EXCLAMATION_MARK:{this.state=A.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=A.SCRIPT_DATA,this._stateScriptData(t)}}_stateScriptDataEndTagOpen(t){or(t)?(this.state=A.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=A.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=A.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStart(t){t===g.HYPHEN_MINUS?(this.state=A.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=A.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStartDash(t){t===g.HYPHEN_MINUS?(this.state=A.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=A.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscaped(t){switch(t){case g.HYPHEN_MINUS:{this.state=A.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=A.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.NULL:{this._err($.unexpectedNullCharacter),this._emitChars(Ye);break}case g.EOF:{this._err($.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataEscapedDash(t){switch(t){case g.HYPHEN_MINUS:{this.state=A.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=A.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.NULL:{this._err($.unexpectedNullCharacter),this.state=A.SCRIPT_DATA_ESCAPED,this._emitChars(Ye);break}case g.EOF:{this._err($.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=A.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedDashDash(t){switch(t){case g.HYPHEN_MINUS:{this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=A.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.GREATER_THAN_SIGN:{this.state=A.SCRIPT_DATA,this._emitChars(">");break}case g.NULL:{this._err($.unexpectedNullCharacter),this.state=A.SCRIPT_DATA_ESCAPED,this._emitChars(Ye);break}case g.EOF:{this._err($.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=A.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedLessThanSign(t){t===g.SOLIDUS?this.state=A.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:or(t)?(this._emitChars("<"),this.state=A.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=A.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagOpen(t){or(t)?(this.state=A.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=A.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=A.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(Et.SCRIPT,!1)&&_d(this.preprocessor.peek(Et.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r<Et.SCRIPT.length;r++)this._emitCodePoint(this._consume());this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=A.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscaped(t){switch(t){case g.HYPHEN_MINUS:{this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.NULL:{this._err($.unexpectedNullCharacter),this._emitChars(Ye);break}case g.EOF:{this._err($.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDash(t){switch(t){case g.HYPHEN_MINUS:{this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.NULL:{this._err($.unexpectedNullCharacter),this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Ye);break}case g.EOF:{this._err($.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case g.HYPHEN_MINUS:{this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.GREATER_THAN_SIGN:{this.state=A.SCRIPT_DATA,this._emitChars(">");break}case g.NULL:{this._err($.unexpectedNullCharacter),this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Ye);break}case g.EOF:{this._err($.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedLessThanSign(t){t===g.SOLIDUS?(this.state=A.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(Et.SCRIPT,!1)&&_d(this.preprocessor.peek(Et.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r<Et.SCRIPT.length;r++)this._emitCodePoint(this._consume());this.state=A.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateBeforeAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.SOLIDUS:case g.GREATER_THAN_SIGN:case g.EOF:{this.state=A.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case g.EQUALS_SIGN:{this._err($.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=A.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=A.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:case g.SOLIDUS:case g.GREATER_THAN_SIGN:case g.EOF:{this._leaveAttrName(),this.state=A.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case g.EQUALS_SIGN:{this._leaveAttrName(),this.state=A.BEFORE_ATTRIBUTE_VALUE;break}case g.QUOTATION_MARK:case g.APOSTROPHE:case g.LESS_THAN_SIGN:{this._err($.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case g.NULL:{this._err($.unexpectedNullCharacter),this.currentAttr.name+=Ye;break}default:this.currentAttr.name+=String.fromCodePoint(Yn(t)?Vi(t):t)}}_stateAfterAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.SOLIDUS:{this.state=A.SELF_CLOSING_START_TAG;break}case g.EQUALS_SIGN:{this.state=A.BEFORE_ATTRIBUTE_VALUE;break}case g.GREATER_THAN_SIGN:{this.state=A.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err($.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=A.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateBeforeAttributeValue(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{this.state=A.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this.state=A.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err($.missingAttributeValue),this.state=A.DATA,this.emitCurrentTagToken();break}default:this.state=A.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t)}}_stateAttributeValueDoubleQuoted(t){switch(t){case g.QUOTATION_MARK:{this.state=A.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err($.unexpectedNullCharacter),this.currentAttr.value+=Ye;break}case g.EOF:{this._err($.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueSingleQuoted(t){switch(t){case g.APOSTROPHE:{this.state=A.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err($.unexpectedNullCharacter),this.currentAttr.value+=Ye;break}case g.EOF:{this._err($.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueUnquoted(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this._leaveAttrValue(),this.state=A.BEFORE_ATTRIBUTE_NAME;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=A.DATA,this.emitCurrentTagToken();break}case g.NULL:{this._err($.unexpectedNullCharacter),this.currentAttr.value+=Ye;break}case g.QUOTATION_MARK:case g.APOSTROPHE:case g.LESS_THAN_SIGN:case g.EQUALS_SIGN:case g.GRAVE_ACCENT:{this._err($.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case g.EOF:{this._err($.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAfterAttributeValueQuoted(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this._leaveAttrValue(),this.state=A.BEFORE_ATTRIBUTE_NAME;break}case g.SOLIDUS:{this._leaveAttrValue(),this.state=A.SELF_CLOSING_START_TAG;break}case g.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=A.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err($.eofInTag),this._emitEOFToken();break}default:this._err($.missingWhitespaceBetweenAttributes),this.state=A.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateSelfClosingStartTag(t){switch(t){case g.GREATER_THAN_SIGN:{const r=this.currentToken;r.selfClosing=!0,this.state=A.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err($.eofInTag),this._emitEOFToken();break}default:this._err($.unexpectedSolidusInTag),this.state=A.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateBogusComment(t){const r=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.state=A.DATA,this.emitCurrentComment(r);break}case g.EOF:{this.emitCurrentComment(r),this._emitEOFToken();break}case g.NULL:{this._err($.unexpectedNullCharacter),r.data+=Ye;break}default:r.data+=String.fromCodePoint(t)}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(Et.DASH_DASH,!0)?(this._createCommentToken(Et.DASH_DASH.length+1),this.state=A.COMMENT_START):this._consumeSequenceIfMatch(Et.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(Et.DOCTYPE.length+1),this.state=A.DOCTYPE):this._consumeSequenceIfMatch(Et.CDATA_START,!0)?this.inForeignNode?this.state=A.CDATA_SECTION:(this._err($.cdataInHtmlContent),this._createCommentToken(Et.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=A.BOGUS_COMMENT):this._ensureHibernation()||(this._err($.incorrectlyOpenedComment),this._createCommentToken(2),this.state=A.BOGUS_COMMENT,this._stateBogusComment(t))}_stateCommentStart(t){switch(t){case g.HYPHEN_MINUS:{this.state=A.COMMENT_START_DASH;break}case g.GREATER_THAN_SIGN:{this._err($.abruptClosingOfEmptyComment),this.state=A.DATA;const r=this.currentToken;this.emitCurrentComment(r);break}default:this.state=A.COMMENT,this._stateComment(t)}}_stateCommentStartDash(t){const r=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=A.COMMENT_END;break}case g.GREATER_THAN_SIGN:{this._err($.abruptClosingOfEmptyComment),this.state=A.DATA,this.emitCurrentComment(r);break}case g.EOF:{this._err($.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="-",this.state=A.COMMENT,this._stateComment(t)}}_stateComment(t){const r=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=A.COMMENT_END_DASH;break}case g.LESS_THAN_SIGN:{r.data+="<",this.state=A.COMMENT_LESS_THAN_SIGN;break}case g.NULL:{this._err($.unexpectedNullCharacter),r.data+=Ye;break}case g.EOF:{this._err($.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+=String.fromCodePoint(t)}}_stateCommentLessThanSign(t){const r=this.currentToken;switch(t){case g.EXCLAMATION_MARK:{r.data+="!",this.state=A.COMMENT_LESS_THAN_SIGN_BANG;break}case g.LESS_THAN_SIGN:{r.data+="<";break}default:this.state=A.COMMENT,this._stateComment(t)}}_stateCommentLessThanSignBang(t){t===g.HYPHEN_MINUS?this.state=A.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=A.COMMENT,this._stateComment(t))}_stateCommentLessThanSignBangDash(t){t===g.HYPHEN_MINUS?this.state=A.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=A.COMMENT_END_DASH,this._stateCommentEndDash(t))}_stateCommentLessThanSignBangDashDash(t){t!==g.GREATER_THAN_SIGN&&t!==g.EOF&&this._err($.nestedComment),this.state=A.COMMENT_END,this._stateCommentEnd(t)}_stateCommentEndDash(t){const r=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=A.COMMENT_END;break}case g.EOF:{this._err($.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="-",this.state=A.COMMENT,this._stateComment(t)}}_stateCommentEnd(t){const r=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.state=A.DATA,this.emitCurrentComment(r);break}case g.EXCLAMATION_MARK:{this.state=A.COMMENT_END_BANG;break}case g.HYPHEN_MINUS:{r.data+="-";break}case g.EOF:{this._err($.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="--",this.state=A.COMMENT,this._stateComment(t)}}_stateCommentEndBang(t){const r=this.currentToken;switch(t){case g.HYPHEN_MINUS:{r.data+="--!",this.state=A.COMMENT_END_DASH;break}case g.GREATER_THAN_SIGN:{this._err($.incorrectlyClosedComment),this.state=A.DATA,this.emitCurrentComment(r);break}case g.EOF:{this._err($.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="--!",this.state=A.COMMENT,this._stateComment(t)}}_stateDoctype(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=A.BEFORE_DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this.state=A.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case g.EOF:{this._err($.eofInDoctype),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err($.missingWhitespaceBeforeDoctypeName),this.state=A.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t)}}_stateBeforeDoctypeName(t){if(Yn(t))this._createDoctypeToken(String.fromCharCode(Vi(t))),this.state=A.DOCTYPE_NAME;else switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.NULL:{this._err($.unexpectedNullCharacter),this._createDoctypeToken(Ye),this.state=A.DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this._err($.missingDoctypeName),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err($.eofInDoctype),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=A.DOCTYPE_NAME}}_stateDoctypeName(t){const r=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=A.AFTER_DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.NULL:{this._err($.unexpectedNullCharacter),r.name+=Ye;break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.name+=String.fromCodePoint(Yn(t)?Vi(t):t)}}_stateAfterDoctypeName(t){const r=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(Et.PUBLIC,!1)?this.state=A.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(Et.SYSTEM,!1)?this.state=A.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err($.invalidCharacterSequenceAfterDoctypeName),r.forceQuirks=!0,this.state=A.BOGUS_DOCTYPE,this._stateBogusDoctype(t))}}_stateAfterDoctypePublicKeyword(t){const r=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=A.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.QUOTATION_MARK:{this._err($.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=A.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err($.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=A.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err($.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err($.missingQuoteBeforeDoctypePublicIdentifier),r.forceQuirks=!0,this.state=A.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypePublicIdentifier(t){const r=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{r.publicId="",this.state=A.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{r.publicId="",this.state=A.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err($.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err($.missingQuoteBeforeDoctypePublicIdentifier),r.forceQuirks=!0,this.state=A.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypePublicIdentifierDoubleQuoted(t){const r=this.currentToken;switch(t){case g.QUOTATION_MARK:{this.state=A.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.NULL:{this._err($.unexpectedNullCharacter),r.publicId+=Ye;break}case g.GREATER_THAN_SIGN:{this._err($.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.publicId+=String.fromCodePoint(t)}}_stateDoctypePublicIdentifierSingleQuoted(t){const r=this.currentToken;switch(t){case g.APOSTROPHE:{this.state=A.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.NULL:{this._err($.unexpectedNullCharacter),r.publicId+=Ye;break}case g.GREATER_THAN_SIGN:{this._err($.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.publicId+=String.fromCodePoint(t)}}_stateAfterDoctypePublicIdentifier(t){const r=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=A.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case g.GREATER_THAN_SIGN:{this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.QUOTATION_MARK:{this._err($.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err($.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err($.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=A.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){const r=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.QUOTATION_MARK:{r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err($.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=A.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateAfterDoctypeSystemKeyword(t){const r=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=A.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.QUOTATION_MARK:{this._err($.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err($.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err($.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err($.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=A.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypeSystemIdentifier(t){const r=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err($.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err($.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=A.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypeSystemIdentifierDoubleQuoted(t){const r=this.currentToken;switch(t){case g.QUOTATION_MARK:{this.state=A.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.NULL:{this._err($.unexpectedNullCharacter),r.systemId+=Ye;break}case g.GREATER_THAN_SIGN:{this._err($.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.systemId+=String.fromCodePoint(t)}}_stateDoctypeSystemIdentifierSingleQuoted(t){const r=this.currentToken;switch(t){case g.APOSTROPHE:{this.state=A.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.NULL:{this._err($.unexpectedNullCharacter),r.systemId+=Ye;break}case g.GREATER_THAN_SIGN:{this._err($.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.systemId+=String.fromCodePoint(t)}}_stateAfterDoctypeSystemIdentifier(t){const r=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err($.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err($.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=A.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBogusDoctype(t){const r=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.NULL:{this._err($.unexpectedNullCharacter);break}case g.EOF:{this.emitCurrentDoctype(r),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case g.RIGHT_SQUARE_BRACKET:{this.state=A.CDATA_SECTION_BRACKET;break}case g.EOF:{this._err($.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateCdataSectionBracket(t){t===g.RIGHT_SQUARE_BRACKET?this.state=A.CDATA_SECTION_END:(this._emitChars("]"),this.state=A.CDATA_SECTION,this._stateCdataSection(t))}_stateCdataSectionEnd(t){switch(t){case g.GREATER_THAN_SIGN:{this.state=A.DATA;break}case g.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=A.CDATA_SECTION,this._stateCdataSection(t)}}_stateCharacterReference(){let t=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(t<0)if(this.preprocessor.lastChunkWritten)t=this.entityDecoder.end();else{this.active=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=!0;return}t===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(g.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&pd(this.preprocessor.peek(1))?A.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(t){pd(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===g.SEMICOLON&&this._err($.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t))}}const Eh=new Set([o.DD,o.DT,o.LI,o.OPTGROUP,o.OPTION,o.P,o.RB,o.RP,o.RT,o.RTC]),Td=new Set([...Eh,o.CAPTION,o.COLGROUP,o.TBODY,o.TD,o.TFOOT,o.TH,o.THEAD,o.TR]),aa=new Set([o.APPLET,o.CAPTION,o.HTML,o.MARQUEE,o.OBJECT,o.TABLE,o.TD,o.TEMPLATE,o.TH]),NA=new Set([...aa,o.OL,o.UL]),wA=new Set([...aa,o.BUTTON]),Ad=new Set([o.ANNOTATION_XML,o.MI,o.MN,o.MO,o.MS,o.MTEXT]),Id=new Set([o.DESC,o.FOREIGN_OBJECT,o.TITLE]),DA=new Set([o.TR,o.TEMPLATE,o.HTML]),SA=new Set([o.TBODY,o.TFOOT,o.THEAD,o.TEMPLATE,o.HTML]),OA=new Set([o.TABLE,o.TEMPLATE,o.HTML]),MA=new Set([o.TD,o.TH]);class RA{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,r,n){this.treeAdapter=r,this.handler=n,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=o.UNKNOWN,this.current=t}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===o.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===ne.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(t,r){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=r,this.currentTagId=r,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,r,!0)}pop(){const t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!0)}replace(t,r){const n=this._indexOf(t);this.items[n]=r,n===this.stackTop&&(this.current=r)}insertAfter(t,r,n){const i=this._indexOf(t)+1;this.items.splice(i,0,r),this.tagIDs.splice(i,0,n),this.stackTop++,i===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,i===this.stackTop)}popUntilTagNamePopped(t){let r=this.stackTop+1;do r=this.tagIDs.lastIndexOf(t,r-1);while(r>0&&this.treeAdapter.getNamespaceURI(this.items[r])!==ne.HTML);this.shortenToLength(Math.max(r,0))}shortenToLength(t){for(;this.stackTop>=t;){const r=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(r,this.stackTop<t)}}popUntilElementPopped(t){const r=this._indexOf(t);this.shortenToLength(Math.max(r,0))}popUntilPopped(t,r){const n=this._indexOfTagNames(t,r);this.shortenToLength(Math.max(n,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(Yo,ne.HTML)}popUntilTableCellPopped(){this.popUntilPopped(MA,ne.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(t,r){for(let n=this.stackTop;n>=0;n--)if(t.has(this.tagIDs[n])&&this.treeAdapter.getNamespaceURI(this.items[n])===r)return n;return-1}clearBackTo(t,r){const n=this._indexOfTagNames(t,r);this.shortenToLength(n+1)}clearBackToTableContext(){this.clearBackTo(OA,ne.HTML)}clearBackToTableBodyContext(){this.clearBackTo(SA,ne.HTML)}clearBackToTableRowContext(){this.clearBackTo(DA,ne.HTML)}remove(t){const r=this._indexOf(t);r>=0&&(r===this.stackTop?this.pop():(this.items.splice(r,1),this.tagIDs.splice(r,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===o.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){const r=this._indexOf(t)-1;return r>=0?this.items[r]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===o.HTML}hasInDynamicScope(t,r){for(let n=this.stackTop;n>=0;n--){const i=this.tagIDs[n];switch(this.treeAdapter.getNamespaceURI(this.items[n])){case ne.HTML:{if(i===t)return!0;if(r.has(i))return!1;break}case ne.SVG:{if(Id.has(i))return!1;break}case ne.MATHML:{if(Ad.has(i))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,aa)}hasInListItemScope(t){return this.hasInDynamicScope(t,NA)}hasInButtonScope(t){return this.hasInDynamicScope(t,wA)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){const r=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case ne.HTML:{if(Yo.has(r))return!0;if(aa.has(r))return!1;break}case ne.SVG:{if(Id.has(r))return!1;break}case ne.MATHML:{if(Ad.has(r))return!1;break}}}return!0}hasInTableScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===ne.HTML)switch(this.tagIDs[r]){case t:return!0;case o.TABLE:case o.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===ne.HTML)switch(this.tagIDs[t]){case o.TBODY:case o.THEAD:case o.TFOOT:return!0;case o.TABLE:case o.HTML:return!1}return!0}hasInSelectScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===ne.HTML)switch(this.tagIDs[r]){case t:return!0;case o.OPTION:case o.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&Eh.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&Td.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&Td.has(this.currentTagId);)this.pop()}}const no=3;var Yt;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"})(Yt||(Yt={}));const bd={type:Yt.Marker};class CA{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(t,r){const n=[],i=r.length,s=this.treeAdapter.getTagName(t),a=this.treeAdapter.getNamespaceURI(t);for(let c=0;c<this.entries.length;c++){const u=this.entries[c];if(u.type===Yt.Marker)break;const{element:d}=u;if(this.treeAdapter.getTagName(d)===s&&this.treeAdapter.getNamespaceURI(d)===a){const l=this.treeAdapter.getAttrList(d);l.length===i&&n.push({idx:c,attrs:l})}}return n}_ensureNoahArkCondition(t){if(this.entries.length<no)return;const r=this.treeAdapter.getAttrList(t),n=this._getNoahArkConditionCandidates(t,r);if(n.length<no)return;const i=new Map(r.map(a=>[a.name,a.value]));let s=0;for(let a=0;a<n.length;a++){const c=n[a];c.attrs.every(u=>i.get(u.name)===u.value)&&(s+=1,s>=no&&this.entries.splice(c.idx,1))}}insertMarker(){this.entries.unshift(bd)}pushElement(t,r){this._ensureNoahArkCondition(t),this.entries.unshift({type:Yt.Element,element:t,token:r})}insertElementAfterBookmark(t,r){const n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:Yt.Element,element:t,token:r})}removeEntry(t){const r=this.entries.indexOf(t);r!==-1&&this.entries.splice(r,1)}clearToLastMarker(){const t=this.entries.indexOf(bd);t===-1?this.entries.length=0:this.entries.splice(0,t+1)}getElementEntryInScopeWithTagName(t){const r=this.entries.find(n=>n.type===Yt.Marker||this.treeAdapter.getTagName(n.element)===t);return r&&r.type===Yt.Element?r:null}getElementEntry(t){return this.entries.find(r=>r.type===Yt.Element&&r.element===t)}}const cr={createDocument(){return{nodeName:"#document",mode:wt.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return{nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,r){return{nodeName:e,tagName:e,attrs:r,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return{nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return{nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,r){const n=e.childNodes.indexOf(r);e.childNodes.splice(n,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent(e){return e.content},setDocumentType(e,t,r,n){const i=e.childNodes.find(s=>s.nodeName==="#documentType");if(i)i.name=t,i.publicId=r,i.systemId=n;else{const s={nodeName:"#documentType",name:t,publicId:r,systemId:n,parentNode:null};cr.appendChild(e,s)}},setDocumentMode(e,t){e.mode=t},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){const t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){const r=e.childNodes[e.childNodes.length-1];if(cr.isTextNode(r)){r.value+=t;return}}cr.appendChild(e,cr.createTextNode(t))},insertTextBefore(e,t,r){const n=e.childNodes[e.childNodes.indexOf(r)-1];n&&cr.isTextNode(n)?n.value+=t:cr.insertBefore(e,cr.createTextNode(t),r)},adoptAttributes(e,t){const r=new Set(e.attrs.map(n=>n.name));for(let n=0;n<t.length;n++)r.has(t[n].name)||e.attrs.push(t[n])},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName==="#text"},isCommentNode(e){return e.nodeName==="#comment"},isDocumentTypeNode(e){return e.nodeName==="#documentType"},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,"tagName")},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t}}},gh="html",LA="about:legacy-compat",PA="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",ph=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],vA=[...ph,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],kA=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),_h=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],xA=[..._h,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function yd(e,t){return t.some(r=>e.startsWith(r))}function UA(e){return e.name===gh&&e.publicId===null&&(e.systemId===null||e.systemId===LA)}function BA(e){if(e.name!==gh)return wt.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===PA)return wt.QUIRKS;let{publicId:r}=e;if(r!==null){if(r=r.toLowerCase(),kA.has(r))return wt.QUIRKS;let n=t===null?vA:ph;if(yd(r,n))return wt.QUIRKS;if(n=t===null?_h:xA,yd(r,n))return wt.LIMITED_QUIRKS}return wt.NO_QUIRKS}const Nd={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},HA="definitionurl",FA="definitionURL",zA=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),jA=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:ne.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:ne.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:ne.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:ne.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:ne.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:ne.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:ne.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:ne.XML}],["xml:space",{prefix:"xml",name:"space",namespace:ne.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:ne.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:ne.XMLNS}]]),VA=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),GA=new Set([o.B,o.BIG,o.BLOCKQUOTE,o.BODY,o.BR,o.CENTER,o.CODE,o.DD,o.DIV,o.DL,o.DT,o.EM,o.EMBED,o.H1,o.H2,o.H3,o.H4,o.H5,o.H6,o.HEAD,o.HR,o.I,o.IMG,o.LI,o.LISTING,o.MENU,o.META,o.NOBR,o.OL,o.P,o.PRE,o.RUBY,o.S,o.SMALL,o.SPAN,o.STRONG,o.STRIKE,o.SUB,o.SUP,o.TABLE,o.TT,o.U,o.UL,o.VAR]);function YA(e){const t=e.tagID;return t===o.FONT&&e.attrs.some(({name:n})=>n===xr.COLOR||n===xr.SIZE||n===xr.FACE)||GA.has(t)}function Th(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===HA){e.attrs[t].name=FA;break}}function Ah(e){for(let t=0;t<e.attrs.length;t++){const r=zA.get(e.attrs[t].name);r!=null&&(e.attrs[t].name=r)}}function $c(e){for(let t=0;t<e.attrs.length;t++){const r=jA.get(e.attrs[t].name);r&&(e.attrs[t].prefix=r.prefix,e.attrs[t].name=r.name,e.attrs[t].namespace=r.namespace)}}function qA(e){const t=VA.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=ka(e.tagName))}function QA(e,t){return t===ne.MATHML&&(e===o.MI||e===o.MO||e===o.MN||e===o.MS||e===o.MTEXT)}function WA(e,t,r){if(t===ne.MATHML&&e===o.ANNOTATION_XML){for(let n=0;n<r.length;n++)if(r[n].name===xr.ENCODING){const i=r[n].value.toLowerCase();return i===Nd.TEXT_HTML||i===Nd.APPLICATION_XML}}return t===ne.SVG&&(e===o.FOREIGN_OBJECT||e===o.DESC||e===o.TITLE)}function $A(e,t,r,n){return(!n||n===ne.HTML)&&WA(e,t,r)||(!n||n===ne.MATHML)&&QA(e,t)}const KA="hidden",ZA=8,XA=3;var b;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"})(b||(b={}));const JA={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Ih=new Set([o.TABLE,o.TBODY,o.TFOOT,o.THEAD,o.TR]),wd={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:cr,onParseError:null};class eI{constructor(t,r,n=null,i=null){this.fragmentContext=n,this.scriptHandler=i,this.currentToken=null,this.stopped=!1,this.insertionMode=b.INITIAL,this.originalInsertionMode=b.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...wd,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=r??this.treeAdapter.createDocument(),this.tokenizer=new yA(this.options,this),this.activeFormattingElements=new CA(this.treeAdapter),this.fragmentContextID=n?ka(this.treeAdapter.getTagName(n)):o.UNKNOWN,this._setContextModes(n??this.document,this.fragmentContextID),this.openElements=new RA(this.document,this.treeAdapter,this)}static parse(t,r){const n=new this(r);return n.tokenizer.write(t,!0),n.document}static getFragmentParser(t,r){const n={...wd,...r};t??(t=n.treeAdapter.createElement(B.TEMPLATE,ne.HTML,[]));const i=n.treeAdapter.createElement("documentmock",ne.HTML,[]),s=new this(n,i,t);return s.fragmentContextID===o.TEMPLATE&&s.tmplInsertionModeStack.unshift(b.IN_TEMPLATE),s._initTokenizerForFragmentParsing(),s._insertFakeRootElement(),s._resetInsertionMode(),s._findFormInFragmentContext(),s}getFragment(){const t=this.treeAdapter.getFirstChild(this.document),r=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,r),r}_err(t,r,n){var i;if(!this.onParseError)return;const s=(i=t.location)!==null&&i!==void 0?i:JA,a={code:r,startLine:s.startLine,startCol:s.startCol,startOffset:s.startOffset,endLine:n?s.startLine:s.endLine,endCol:n?s.startCol:s.endCol,endOffset:n?s.startOffset:s.endOffset};this.onParseError(a)}onItemPush(t,r,n){var i,s;(s=(i=this.treeAdapter).onItemPush)===null||s===void 0||s.call(i,t),n&&this.openElements.stackTop>0&&this._setContextModes(t,r)}onItemPop(t,r){var n,i;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(i=(n=this.treeAdapter).onItemPop)===null||i===void 0||i.call(n,t,this.openElements.current),r){let s,a;this.openElements.stackTop===0&&this.fragmentContext?(s=this.fragmentContext,a=this.fragmentContextID):{current:s,currentTagId:a}=this.openElements,this._setContextModes(s,a)}}_setContextModes(t,r){const n=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===ne.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&t!==void 0&&r!==void 0&&!this._isIntegrationPoint(r,t)}_switchToTextParsing(t,r){this._insertElement(t,ne.HTML),this.tokenizer.state=r,this.originalInsertionMode=this.insertionMode,this.insertionMode=b.TEXT}switchToPlaintextParsing(){this.insertionMode=b.TEXT,this.originalInsertionMode=b.IN_BODY,this.tokenizer.state=pt.PLAINTEXT}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===B.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==ne.HTML))switch(this.fragmentContextID){case o.TITLE:case o.TEXTAREA:{this.tokenizer.state=pt.RCDATA;break}case o.STYLE:case o.XMP:case o.IFRAME:case o.NOEMBED:case o.NOFRAMES:case o.NOSCRIPT:{this.tokenizer.state=pt.RAWTEXT;break}case o.SCRIPT:{this.tokenizer.state=pt.SCRIPT_DATA;break}case o.PLAINTEXT:{this.tokenizer.state=pt.PLAINTEXT;break}}}_setDocumentType(t){const r=t.name||"",n=t.publicId||"",i=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,r,n,i),t.location){const a=this.treeAdapter.getChildNodes(this.document).find(c=>this.treeAdapter.isDocumentTypeNode(c));a&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location)}}_attachElementToTree(t,r){if(this.options.sourceCodeLocationInfo){const n=r&&{...r,startTag:r};this.treeAdapter.setNodeSourceCodeLocation(t,n)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else{const n=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(n??this.document,t)}}_appendElement(t,r){const n=this.treeAdapter.createElement(t.tagName,r,t.attrs);this._attachElementToTree(n,t.location)}_insertElement(t,r){const n=this.treeAdapter.createElement(t.tagName,r,t.attrs);this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID)}_insertFakeElement(t,r){const n=this.treeAdapter.createElement(t,ne.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,r)}_insertTemplate(t){const r=this.treeAdapter.createElement(t.tagName,ne.HTML,t.attrs),n=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(r,n),this._attachElementToTree(r,t.location),this.openElements.push(r,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,null)}_insertFakeRootElement(){const t=this.treeAdapter.createElement(B.HTML,ne.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,o.HTML)}_appendCommentNode(t,r){const n=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(r,n),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,t.location)}_insertCharacters(t){let r,n;if(this._shouldFosterParentOnInsertion()?({parent:r,beforeElement:n}=this._findFosterParentingLocation(),n?this.treeAdapter.insertTextBefore(r,t.chars,n):this.treeAdapter.insertText(r,t.chars)):(r=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(r,t.chars)),!t.location)return;const i=this.treeAdapter.getChildNodes(r),s=n?i.lastIndexOf(n):i.length,a=i[s-1];if(this.treeAdapter.getNodeSourceCodeLocation(a)){const{endLine:u,endCol:d,endOffset:l}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(a,{endLine:u,endCol:d,endOffset:l})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location)}_adoptNodes(t,r){for(let n=this.treeAdapter.getFirstChild(t);n;n=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(n),this.treeAdapter.appendChild(r,n)}_setEndLocation(t,r){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&r.location){const n=r.location,i=this.treeAdapter.getTagName(t),s=r.type===xe.END_TAG&&i===r.tagName?{endTag:{...n},endLine:n.endLine,endCol:n.endCol,endOffset:n.endOffset}:{endLine:n.startLine,endCol:n.startCol,endOffset:n.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,s)}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return!1;let r,n;return this.openElements.stackTop===0&&this.fragmentContext?(r=this.fragmentContext,n=this.fragmentContextID):{current:r,currentTagId:n}=this.openElements,t.tagID===o.SVG&&this.treeAdapter.getTagName(r)===B.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(r)===ne.MATHML?!1:this.tokenizer.inForeignNode||(t.tagID===o.MGLYPH||t.tagID===o.MALIGNMARK)&&n!==void 0&&!this._isIntegrationPoint(n,r,ne.HTML)}_processToken(t){switch(t.type){case xe.CHARACTER:{this.onCharacter(t);break}case xe.NULL_CHARACTER:{this.onNullCharacter(t);break}case xe.COMMENT:{this.onComment(t);break}case xe.DOCTYPE:{this.onDoctype(t);break}case xe.START_TAG:{this._processStartTag(t);break}case xe.END_TAG:{this.onEndTag(t);break}case xe.EOF:{this.onEof(t);break}case xe.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,r,n){const i=this.treeAdapter.getNamespaceURI(r),s=this.treeAdapter.getAttrList(r);return $A(t,i,s,n)}_reconstructActiveFormattingElements(){const t=this.activeFormattingElements.entries.length;if(t){const r=this.activeFormattingElements.entries.findIndex(i=>i.type===Yt.Marker||this.openElements.contains(i.element)),n=r===-1?t-1:r-1;for(let i=n;i>=0;i--){const s=this.activeFormattingElements.entries[i];this._insertElement(s.token,this.treeAdapter.getNamespaceURI(s.element)),s.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=b.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(o.P),this.openElements.popUntilTagNamePopped(o.P)}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case o.TR:{this.insertionMode=b.IN_ROW;return}case o.TBODY:case o.THEAD:case o.TFOOT:{this.insertionMode=b.IN_TABLE_BODY;return}case o.CAPTION:{this.insertionMode=b.IN_CAPTION;return}case o.COLGROUP:{this.insertionMode=b.IN_COLUMN_GROUP;return}case o.TABLE:{this.insertionMode=b.IN_TABLE;return}case o.BODY:{this.insertionMode=b.IN_BODY;return}case o.FRAMESET:{this.insertionMode=b.IN_FRAMESET;return}case o.SELECT:{this._resetInsertionModeForSelect(t);return}case o.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case o.HTML:{this.insertionMode=this.headElement?b.AFTER_HEAD:b.BEFORE_HEAD;return}case o.TD:case o.TH:{if(t>0){this.insertionMode=b.IN_CELL;return}break}case o.HEAD:{if(t>0){this.insertionMode=b.IN_HEAD;return}break}}this.insertionMode=b.IN_BODY}_resetInsertionModeForSelect(t){if(t>0)for(let r=t-1;r>0;r--){const n=this.openElements.tagIDs[r];if(n===o.TEMPLATE)break;if(n===o.TABLE){this.insertionMode=b.IN_SELECT_IN_TABLE;return}}this.insertionMode=b.IN_SELECT}_isElementCausesFosterParenting(t){return Ih.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){const r=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case o.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(r)===ne.HTML)return{parent:this.treeAdapter.getTemplateContent(r),beforeElement:null};break}case o.TABLE:{const n=this.treeAdapter.getParentNode(r);return n?{parent:n,beforeElement:r}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){const r=this._findFosterParentingLocation();r.beforeElement?this.treeAdapter.insertBefore(r.parent,t,r.beforeElement):this.treeAdapter.appendChild(r.parent,t)}_isSpecialElement(t,r){const n=this.treeAdapter.getNamespaceURI(t);return TA[n].has(r)}onCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){Rb(this,t);return}switch(this.insertionMode){case b.INITIAL:{kn(this,t);break}case b.BEFORE_HTML:{$n(this,t);break}case b.BEFORE_HEAD:{Kn(this,t);break}case b.IN_HEAD:{Zn(this,t);break}case b.IN_HEAD_NO_SCRIPT:{Xn(this,t);break}case b.AFTER_HEAD:{Jn(this,t);break}case b.IN_BODY:case b.IN_CAPTION:case b.IN_CELL:case b.IN_TEMPLATE:{yh(this,t);break}case b.TEXT:case b.IN_SELECT:case b.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case b.IN_TABLE:case b.IN_TABLE_BODY:case b.IN_ROW:{io(this,t);break}case b.IN_TABLE_TEXT:{Mh(this,t);break}case b.IN_COLUMN_GROUP:{oa(this,t);break}case b.AFTER_BODY:{ca(this,t);break}case b.AFTER_AFTER_BODY:{as(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){Mb(this,t);return}switch(this.insertionMode){case b.INITIAL:{kn(this,t);break}case b.BEFORE_HTML:{$n(this,t);break}case b.BEFORE_HEAD:{Kn(this,t);break}case b.IN_HEAD:{Zn(this,t);break}case b.IN_HEAD_NO_SCRIPT:{Xn(this,t);break}case b.AFTER_HEAD:{Jn(this,t);break}case b.TEXT:{this._insertCharacters(t);break}case b.IN_TABLE:case b.IN_TABLE_BODY:case b.IN_ROW:{io(this,t);break}case b.IN_COLUMN_GROUP:{oa(this,t);break}case b.AFTER_BODY:{ca(this,t);break}case b.AFTER_AFTER_BODY:{as(this,t);break}}}onComment(t){if(this.skipNextNewLine=!1,this.currentNotInHTML){qo(this,t);return}switch(this.insertionMode){case b.INITIAL:case b.BEFORE_HTML:case b.BEFORE_HEAD:case b.IN_HEAD:case b.IN_HEAD_NO_SCRIPT:case b.AFTER_HEAD:case b.IN_BODY:case b.IN_TABLE:case b.IN_CAPTION:case b.IN_COLUMN_GROUP:case b.IN_TABLE_BODY:case b.IN_ROW:case b.IN_CELL:case b.IN_SELECT:case b.IN_SELECT_IN_TABLE:case b.IN_TEMPLATE:case b.IN_FRAMESET:case b.AFTER_FRAMESET:{qo(this,t);break}case b.IN_TABLE_TEXT:{xn(this,t);break}case b.AFTER_BODY:{oI(this,t);break}case b.AFTER_AFTER_BODY:case b.AFTER_AFTER_FRAMESET:{cI(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case b.INITIAL:{uI(this,t);break}case b.BEFORE_HEAD:case b.IN_HEAD:case b.IN_HEAD_NO_SCRIPT:case b.AFTER_HEAD:{this._err(t,$.misplacedDoctype);break}case b.IN_TABLE_TEXT:{xn(this,t);break}}}onStartTag(t){this.skipNextNewLine=!1,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,$.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?Cb(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case b.INITIAL:{kn(this,t);break}case b.BEFORE_HTML:{dI(this,t);break}case b.BEFORE_HEAD:{fI(this,t);break}case b.IN_HEAD:{Bt(this,t);break}case b.IN_HEAD_NO_SCRIPT:{EI(this,t);break}case b.AFTER_HEAD:{pI(this,t);break}case b.IN_BODY:{ot(this,t);break}case b.IN_TABLE:{_n(this,t);break}case b.IN_TABLE_TEXT:{xn(this,t);break}case b.IN_CAPTION:{hb(this,t);break}case b.IN_COLUMN_GROUP:{Xc(this,t);break}case b.IN_TABLE_BODY:{Ba(this,t);break}case b.IN_ROW:{Ha(this,t);break}case b.IN_CELL:{gb(this,t);break}case b.IN_SELECT:{Lh(this,t);break}case b.IN_SELECT_IN_TABLE:{_b(this,t);break}case b.IN_TEMPLATE:{Ab(this,t);break}case b.AFTER_BODY:{bb(this,t);break}case b.IN_FRAMESET:{yb(this,t);break}case b.AFTER_FRAMESET:{wb(this,t);break}case b.AFTER_AFTER_BODY:{Sb(this,t);break}case b.AFTER_AFTER_FRAMESET:{Ob(this,t);break}}}onEndTag(t){this.skipNextNewLine=!1,this.currentToken=t,this.currentNotInHTML?Lb(this,t):this._endTagOutsideForeignContent(t)}_endTagOutsideForeignContent(t){switch(this.insertionMode){case b.INITIAL:{kn(this,t);break}case b.BEFORE_HTML:{lI(this,t);break}case b.BEFORE_HEAD:{hI(this,t);break}case b.IN_HEAD:{mI(this,t);break}case b.IN_HEAD_NO_SCRIPT:{gI(this,t);break}case b.AFTER_HEAD:{_I(this,t);break}case b.IN_BODY:{Ua(this,t);break}case b.TEXT:{nb(this,t);break}case b.IN_TABLE:{Ai(this,t);break}case b.IN_TABLE_TEXT:{xn(this,t);break}case b.IN_CAPTION:{mb(this,t);break}case b.IN_COLUMN_GROUP:{Eb(this,t);break}case b.IN_TABLE_BODY:{Qo(this,t);break}case b.IN_ROW:{Ch(this,t);break}case b.IN_CELL:{pb(this,t);break}case b.IN_SELECT:{Ph(this,t);break}case b.IN_SELECT_IN_TABLE:{Tb(this,t);break}case b.IN_TEMPLATE:{Ib(this,t);break}case b.AFTER_BODY:{kh(this,t);break}case b.IN_FRAMESET:{Nb(this,t);break}case b.AFTER_FRAMESET:{Db(this,t);break}case b.AFTER_AFTER_BODY:{as(this,t);break}}}onEof(t){switch(this.insertionMode){case b.INITIAL:{kn(this,t);break}case b.BEFORE_HTML:{$n(this,t);break}case b.BEFORE_HEAD:{Kn(this,t);break}case b.IN_HEAD:{Zn(this,t);break}case b.IN_HEAD_NO_SCRIPT:{Xn(this,t);break}case b.AFTER_HEAD:{Jn(this,t);break}case b.IN_BODY:case b.IN_TABLE:case b.IN_CAPTION:case b.IN_COLUMN_GROUP:case b.IN_TABLE_BODY:case b.IN_ROW:case b.IN_CELL:case b.IN_SELECT:case b.IN_SELECT_IN_TABLE:{Sh(this,t);break}case b.TEXT:{ib(this,t);break}case b.IN_TABLE_TEXT:{xn(this,t);break}case b.IN_TEMPLATE:{vh(this,t);break}case b.AFTER_BODY:case b.IN_FRAMESET:case b.AFTER_FRAMESET:case b.AFTER_AFTER_BODY:case b.AFTER_AFTER_FRAMESET:{Zc(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,t.chars.charCodeAt(0)===g.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1)}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case b.IN_HEAD:case b.IN_HEAD_NO_SCRIPT:case b.AFTER_HEAD:case b.TEXT:case b.IN_COLUMN_GROUP:case b.IN_SELECT:case b.IN_SELECT_IN_TABLE:case b.IN_FRAMESET:case b.AFTER_FRAMESET:{this._insertCharacters(t);break}case b.IN_BODY:case b.IN_CAPTION:case b.IN_CELL:case b.IN_TEMPLATE:case b.AFTER_BODY:case b.AFTER_AFTER_BODY:case b.AFTER_AFTER_FRAMESET:{bh(this,t);break}case b.IN_TABLE:case b.IN_TABLE_BODY:case b.IN_ROW:{io(this,t);break}case b.IN_TABLE_TEXT:{Oh(this,t);break}}}}function tI(e,t){let r=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return r?e.openElements.contains(r.element)?e.openElements.hasInScope(t.tagID)||(r=null):(e.activeFormattingElements.removeEntry(r),r=null):Dh(e,t),r}function rI(e,t){let r=null,n=e.openElements.stackTop;for(;n>=0;n--){const i=e.openElements.items[n];if(i===t.element)break;e._isSpecialElement(i,e.openElements.tagIDs[n])&&(r=i)}return r||(e.openElements.shortenToLength(Math.max(n,0)),e.activeFormattingElements.removeEntry(t)),r}function nI(e,t,r){let n=t,i=e.openElements.getCommonAncestor(t);for(let s=0,a=i;a!==r;s++,a=i){i=e.openElements.getCommonAncestor(a);const c=e.activeFormattingElements.getElementEntry(a),u=c&&s>=XA;!c||u?(u&&e.activeFormattingElements.removeEntry(c),e.openElements.remove(a)):(a=iI(e,c),n===t&&(e.activeFormattingElements.bookmark=c),e.treeAdapter.detachNode(n),e.treeAdapter.appendChild(a,n),n=a)}return n}function iI(e,t){const r=e.treeAdapter.getNamespaceURI(t.element),n=e.treeAdapter.createElement(t.token.tagName,r,t.token.attrs);return e.openElements.replace(t.element,n),t.element=n,n}function sI(e,t,r){const n=e.treeAdapter.getTagName(t),i=ka(n);if(e._isElementCausesFosterParenting(i))e._fosterParentElement(r);else{const s=e.treeAdapter.getNamespaceURI(t);i===o.TEMPLATE&&s===ne.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,r)}}function aI(e,t,r){const n=e.treeAdapter.getNamespaceURI(r.element),{token:i}=r,s=e.treeAdapter.createElement(i.tagName,n,i.attrs);e._adoptNodes(t,s),e.treeAdapter.appendChild(t,s),e.activeFormattingElements.insertElementAfterBookmark(s,i),e.activeFormattingElements.removeEntry(r),e.openElements.remove(r.element),e.openElements.insertAfter(t,s,i.tagID)}function Kc(e,t){for(let r=0;r<ZA;r++){const n=tI(e,t);if(!n)break;const i=rI(e,n);if(!i)break;e.activeFormattingElements.bookmark=n;const s=nI(e,i,n.element),a=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(s),a&&sI(e,a,s),aI(e,i,n)}}function qo(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function oI(e,t){e._appendCommentNode(t,e.openElements.items[0])}function cI(e,t){e._appendCommentNode(t,e.document)}function Zc(e,t){if(e.stopped=!0,t.location){const r=e.fragmentContext?0:2;for(let n=e.openElements.stackTop;n>=r;n--)e._setEndLocation(e.openElements.items[n],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const n=e.openElements.items[0],i=e.treeAdapter.getNodeSourceCodeLocation(n);if(i&&!i.endTag&&(e._setEndLocation(n,t),e.openElements.stackTop>=1)){const s=e.openElements.items[1],a=e.treeAdapter.getNodeSourceCodeLocation(s);a&&!a.endTag&&e._setEndLocation(s,t)}}}}function uI(e,t){e._setDocumentType(t);const r=t.forceQuirks?wt.QUIRKS:BA(t);UA(t)||e._err(t,$.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,r),e.insertionMode=b.BEFORE_HTML}function kn(e,t){e._err(t,$.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,wt.QUIRKS),e.insertionMode=b.BEFORE_HTML,e._processToken(t)}function dI(e,t){t.tagID===o.HTML?(e._insertElement(t,ne.HTML),e.insertionMode=b.BEFORE_HEAD):$n(e,t)}function lI(e,t){const r=t.tagID;(r===o.HTML||r===o.HEAD||r===o.BODY||r===o.BR)&&$n(e,t)}function $n(e,t){e._insertFakeRootElement(),e.insertionMode=b.BEFORE_HEAD,e._processToken(t)}function fI(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.HEAD:{e._insertElement(t,ne.HTML),e.headElement=e.openElements.current,e.insertionMode=b.IN_HEAD;break}default:Kn(e,t)}}function hI(e,t){const r=t.tagID;r===o.HEAD||r===o.BODY||r===o.HTML||r===o.BR?Kn(e,t):e._err(t,$.endTagWithoutMatchingOpenElement)}function Kn(e,t){e._insertFakeElement(B.HEAD,o.HEAD),e.headElement=e.openElements.current,e.insertionMode=b.IN_HEAD,e._processToken(t)}function Bt(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.BASE:case o.BASEFONT:case o.BGSOUND:case o.LINK:case o.META:{e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case o.TITLE:{e._switchToTextParsing(t,pt.RCDATA);break}case o.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,pt.RAWTEXT):(e._insertElement(t,ne.HTML),e.insertionMode=b.IN_HEAD_NO_SCRIPT);break}case o.NOFRAMES:case o.STYLE:{e._switchToTextParsing(t,pt.RAWTEXT);break}case o.SCRIPT:{e._switchToTextParsing(t,pt.SCRIPT_DATA);break}case o.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=b.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(b.IN_TEMPLATE);break}case o.HEAD:{e._err(t,$.misplacedStartTagForHeadElement);break}default:Zn(e,t)}}function mI(e,t){switch(t.tagID){case o.HEAD:{e.openElements.pop(),e.insertionMode=b.AFTER_HEAD;break}case o.BODY:case o.BR:case o.HTML:{Zn(e,t);break}case o.TEMPLATE:{Vr(e,t);break}default:e._err(t,$.endTagWithoutMatchingOpenElement)}}function Vr(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==o.TEMPLATE&&e._err(t,$.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(o.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,$.endTagWithoutMatchingOpenElement)}function Zn(e,t){e.openElements.pop(),e.insertionMode=b.AFTER_HEAD,e._processToken(t)}function EI(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.BASEFONT:case o.BGSOUND:case o.HEAD:case o.LINK:case o.META:case o.NOFRAMES:case o.STYLE:{Bt(e,t);break}case o.NOSCRIPT:{e._err(t,$.nestedNoscriptInHead);break}default:Xn(e,t)}}function gI(e,t){switch(t.tagID){case o.NOSCRIPT:{e.openElements.pop(),e.insertionMode=b.IN_HEAD;break}case o.BR:{Xn(e,t);break}default:e._err(t,$.endTagWithoutMatchingOpenElement)}}function Xn(e,t){const r=t.type===xe.EOF?$.openElementsLeftAfterEof:$.disallowedContentInNoscriptInHead;e._err(t,r),e.openElements.pop(),e.insertionMode=b.IN_HEAD,e._processToken(t)}function pI(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.BODY:{e._insertElement(t,ne.HTML),e.framesetOk=!1,e.insertionMode=b.IN_BODY;break}case o.FRAMESET:{e._insertElement(t,ne.HTML),e.insertionMode=b.IN_FRAMESET;break}case o.BASE:case o.BASEFONT:case o.BGSOUND:case o.LINK:case o.META:case o.NOFRAMES:case o.SCRIPT:case o.STYLE:case o.TEMPLATE:case o.TITLE:{e._err(t,$.abandonedHeadElementChild),e.openElements.push(e.headElement,o.HEAD),Bt(e,t),e.openElements.remove(e.headElement);break}case o.HEAD:{e._err(t,$.misplacedStartTagForHeadElement);break}default:Jn(e,t)}}function _I(e,t){switch(t.tagID){case o.BODY:case o.HTML:case o.BR:{Jn(e,t);break}case o.TEMPLATE:{Vr(e,t);break}default:e._err(t,$.endTagWithoutMatchingOpenElement)}}function Jn(e,t){e._insertFakeElement(B.BODY,o.BODY),e.insertionMode=b.IN_BODY,xa(e,t)}function xa(e,t){switch(t.type){case xe.CHARACTER:{yh(e,t);break}case xe.WHITESPACE_CHARACTER:{bh(e,t);break}case xe.COMMENT:{qo(e,t);break}case xe.START_TAG:{ot(e,t);break}case xe.END_TAG:{Ua(e,t);break}case xe.EOF:{Sh(e,t);break}}}function bh(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function yh(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function TI(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function AI(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(r,t.attrs))}function II(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&r&&(e.treeAdapter.detachNode(r),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,ne.HTML),e.insertionMode=b.IN_FRAMESET)}function bI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,ne.HTML)}function yI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&Yo.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,ne.HTML)}function NI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function wI(e,t){const r=e.openElements.tmplCount>0;(!e.formElement||r)&&(e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,ne.HTML),r||(e.formElement=e.openElements.current))}function DI(e,t){e.framesetOk=!1;const r=t.tagID;for(let n=e.openElements.stackTop;n>=0;n--){const i=e.openElements.tagIDs[n];if(r===o.LI&&i===o.LI||(r===o.DD||r===o.DT)&&(i===o.DD||i===o.DT)){e.openElements.generateImpliedEndTagsWithExclusion(i),e.openElements.popUntilTagNamePopped(i);break}if(i!==o.ADDRESS&&i!==o.DIV&&i!==o.P&&e._isSpecialElement(e.openElements.items[n],i))break}e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,ne.HTML)}function SI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.tokenizer.state=pt.PLAINTEXT}function OI(e,t){e.openElements.hasInScope(o.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.framesetOk=!1}function MI(e,t){const r=e.activeFormattingElements.getElementEntryInScopeWithTagName(B.A);r&&(Kc(e,t),e.openElements.remove(r.element),e.activeFormattingElements.removeEntry(r)),e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function RI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function CI(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(o.NOBR)&&(Kc(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function LI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function PI(e,t){e.treeAdapter.getDocumentMode(e.document)!==wt.QUIRKS&&e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.framesetOk=!1,e.insertionMode=b.IN_TABLE}function Nh(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ne.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function wh(e){const t=hh(e,xr.TYPE);return t!=null&&t.toLowerCase()===KA}function vI(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ne.HTML),wh(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function kI(e,t){e._appendElement(t,ne.HTML),t.ackSelfClosing=!0}function xI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._appendElement(t,ne.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function UI(e,t){t.tagName=B.IMG,t.tagID=o.IMG,Nh(e,t)}function BI(e,t){e._insertElement(t,ne.HTML),e.skipNextNewLine=!0,e.tokenizer.state=pt.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=b.TEXT}function HI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,pt.RAWTEXT)}function FI(e,t){e.framesetOk=!1,e._switchToTextParsing(t,pt.RAWTEXT)}function Dd(e,t){e._switchToTextParsing(t,pt.RAWTEXT)}function zI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===b.IN_TABLE||e.insertionMode===b.IN_CAPTION||e.insertionMode===b.IN_TABLE_BODY||e.insertionMode===b.IN_ROW||e.insertionMode===b.IN_CELL?b.IN_SELECT_IN_TABLE:b.IN_SELECT}function jI(e,t){e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML)}function VI(e,t){e.openElements.hasInScope(o.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,ne.HTML)}function GI(e,t){e.openElements.hasInScope(o.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(o.RTC),e._insertElement(t,ne.HTML)}function YI(e,t){e._reconstructActiveFormattingElements(),Th(t),$c(t),t.selfClosing?e._appendElement(t,ne.MATHML):e._insertElement(t,ne.MATHML),t.ackSelfClosing=!0}function qI(e,t){e._reconstructActiveFormattingElements(),Ah(t),$c(t),t.selfClosing?e._appendElement(t,ne.SVG):e._insertElement(t,ne.SVG),t.ackSelfClosing=!0}function Sd(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML)}function ot(e,t){switch(t.tagID){case o.I:case o.S:case o.B:case o.U:case o.EM:case o.TT:case o.BIG:case o.CODE:case o.FONT:case o.SMALL:case o.STRIKE:case o.STRONG:{RI(e,t);break}case o.A:{MI(e,t);break}case o.H1:case o.H2:case o.H3:case o.H4:case o.H5:case o.H6:{yI(e,t);break}case o.P:case o.DL:case o.OL:case o.UL:case o.DIV:case o.DIR:case o.NAV:case o.MAIN:case o.MENU:case o.ASIDE:case o.CENTER:case o.FIGURE:case o.FOOTER:case o.HEADER:case o.HGROUP:case o.DIALOG:case o.DETAILS:case o.ADDRESS:case o.ARTICLE:case o.SEARCH:case o.SECTION:case o.SUMMARY:case o.FIELDSET:case o.BLOCKQUOTE:case o.FIGCAPTION:{bI(e,t);break}case o.LI:case o.DD:case o.DT:{DI(e,t);break}case o.BR:case o.IMG:case o.WBR:case o.AREA:case o.EMBED:case o.KEYGEN:{Nh(e,t);break}case o.HR:{xI(e,t);break}case o.RB:case o.RTC:{VI(e,t);break}case o.RT:case o.RP:{GI(e,t);break}case o.PRE:case o.LISTING:{NI(e,t);break}case o.XMP:{HI(e,t);break}case o.SVG:{qI(e,t);break}case o.HTML:{TI(e,t);break}case o.BASE:case o.LINK:case o.META:case o.STYLE:case o.TITLE:case o.SCRIPT:case o.BGSOUND:case o.BASEFONT:case o.TEMPLATE:{Bt(e,t);break}case o.BODY:{AI(e,t);break}case o.FORM:{wI(e,t);break}case o.NOBR:{CI(e,t);break}case o.MATH:{YI(e,t);break}case o.TABLE:{PI(e,t);break}case o.INPUT:{vI(e,t);break}case o.PARAM:case o.TRACK:case o.SOURCE:{kI(e,t);break}case o.IMAGE:{UI(e,t);break}case o.BUTTON:{OI(e,t);break}case o.APPLET:case o.OBJECT:case o.MARQUEE:{LI(e,t);break}case o.IFRAME:{FI(e,t);break}case o.SELECT:{zI(e,t);break}case o.OPTION:case o.OPTGROUP:{jI(e,t);break}case o.NOEMBED:case o.NOFRAMES:{Dd(e,t);break}case o.FRAMESET:{II(e,t);break}case o.TEXTAREA:{BI(e,t);break}case o.NOSCRIPT:{e.options.scriptingEnabled?Dd(e,t):Sd(e,t);break}case o.PLAINTEXT:{SI(e,t);break}case o.COL:case o.TH:case o.TD:case o.TR:case o.HEAD:case o.FRAME:case o.TBODY:case o.TFOOT:case o.THEAD:case o.CAPTION:case o.COLGROUP:break;default:Sd(e,t)}}function QI(e,t){if(e.openElements.hasInScope(o.BODY)&&(e.insertionMode=b.AFTER_BODY,e.options.sourceCodeLocationInfo)){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e._setEndLocation(r,t)}}function WI(e,t){e.openElements.hasInScope(o.BODY)&&(e.insertionMode=b.AFTER_BODY,kh(e,t))}function $I(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r))}function KI(e){const t=e.openElements.tmplCount>0,{formElement:r}=e;t||(e.formElement=null),(r||t)&&e.openElements.hasInScope(o.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(o.FORM):r&&e.openElements.remove(r))}function ZI(e){e.openElements.hasInButtonScope(o.P)||e._insertFakeElement(B.P,o.P),e._closePElement()}function XI(e){e.openElements.hasInListItemScope(o.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(o.LI),e.openElements.popUntilTagNamePopped(o.LI))}function JI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r))}function eb(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function tb(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker())}function rb(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(B.BR,o.BR),e.openElements.pop(),e.framesetOk=!1}function Dh(e,t){const r=t.tagName,n=t.tagID;for(let i=e.openElements.stackTop;i>0;i--){const s=e.openElements.items[i],a=e.openElements.tagIDs[i];if(n===a&&(n!==o.UNKNOWN||e.treeAdapter.getTagName(s)===r)){e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.stackTop>=i&&e.openElements.shortenToLength(i);break}if(e._isSpecialElement(s,a))break}}function Ua(e,t){switch(t.tagID){case o.A:case o.B:case o.I:case o.S:case o.U:case o.EM:case o.TT:case o.BIG:case o.CODE:case o.FONT:case o.NOBR:case o.SMALL:case o.STRIKE:case o.STRONG:{Kc(e,t);break}case o.P:{ZI(e);break}case o.DL:case o.UL:case o.OL:case o.DIR:case o.DIV:case o.NAV:case o.PRE:case o.MAIN:case o.MENU:case o.ASIDE:case o.BUTTON:case o.CENTER:case o.FIGURE:case o.FOOTER:case o.HEADER:case o.HGROUP:case o.DIALOG:case o.ADDRESS:case o.ARTICLE:case o.DETAILS:case o.SEARCH:case o.SECTION:case o.SUMMARY:case o.LISTING:case o.FIELDSET:case o.BLOCKQUOTE:case o.FIGCAPTION:{$I(e,t);break}case o.LI:{XI(e);break}case o.DD:case o.DT:{JI(e,t);break}case o.H1:case o.H2:case o.H3:case o.H4:case o.H5:case o.H6:{eb(e);break}case o.BR:{rb(e);break}case o.BODY:{QI(e,t);break}case o.HTML:{WI(e,t);break}case o.FORM:{KI(e);break}case o.APPLET:case o.OBJECT:case o.MARQUEE:{tb(e,t);break}case o.TEMPLATE:{Vr(e,t);break}default:Dh(e,t)}}function Sh(e,t){e.tmplInsertionModeStack.length>0?vh(e,t):Zc(e,t)}function nb(e,t){var r;t.tagID===o.SCRIPT&&((r=e.scriptHandler)===null||r===void 0||r.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function ib(e,t){e._err(t,$.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function io(e,t){if(e.openElements.currentTagId!==void 0&&Ih.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=b.IN_TABLE_TEXT,t.type){case xe.CHARACTER:{Mh(e,t);break}case xe.WHITESPACE_CHARACTER:{Oh(e,t);break}}else Li(e,t)}function sb(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,ne.HTML),e.insertionMode=b.IN_CAPTION}function ab(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ne.HTML),e.insertionMode=b.IN_COLUMN_GROUP}function ob(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(B.COLGROUP,o.COLGROUP),e.insertionMode=b.IN_COLUMN_GROUP,Xc(e,t)}function cb(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ne.HTML),e.insertionMode=b.IN_TABLE_BODY}function ub(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(B.TBODY,o.TBODY),e.insertionMode=b.IN_TABLE_BODY,Ba(e,t)}function db(e,t){e.openElements.hasInTableScope(o.TABLE)&&(e.openElements.popUntilTagNamePopped(o.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function lb(e,t){wh(t)?e._appendElement(t,ne.HTML):Li(e,t),t.ackSelfClosing=!0}function fb(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,ne.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function _n(e,t){switch(t.tagID){case o.TD:case o.TH:case o.TR:{ub(e,t);break}case o.STYLE:case o.SCRIPT:case o.TEMPLATE:{Bt(e,t);break}case o.COL:{ob(e,t);break}case o.FORM:{fb(e,t);break}case o.TABLE:{db(e,t);break}case o.TBODY:case o.TFOOT:case o.THEAD:{cb(e,t);break}case o.INPUT:{lb(e,t);break}case o.CAPTION:{sb(e,t);break}case o.COLGROUP:{ab(e,t);break}default:Li(e,t)}}function Ai(e,t){switch(t.tagID){case o.TABLE:{e.openElements.hasInTableScope(o.TABLE)&&(e.openElements.popUntilTagNamePopped(o.TABLE),e._resetInsertionMode());break}case o.TEMPLATE:{Vr(e,t);break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:case o.TBODY:case o.TD:case o.TFOOT:case o.TH:case o.THEAD:case o.TR:break;default:Li(e,t)}}function Li(e,t){const r=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,xa(e,t),e.fosterParentingEnabled=r}function Oh(e,t){e.pendingCharacterTokens.push(t)}function Mh(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function xn(e,t){let r=0;if(e.hasNonWhitespacePendingCharacterToken)for(;r<e.pendingCharacterTokens.length;r++)Li(e,e.pendingCharacterTokens[r]);else for(;r<e.pendingCharacterTokens.length;r++)e._insertCharacters(e.pendingCharacterTokens[r]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}const Rh=new Set([o.CAPTION,o.COL,o.COLGROUP,o.TBODY,o.TD,o.TFOOT,o.TH,o.THEAD,o.TR]);function hb(e,t){const r=t.tagID;Rh.has(r)?e.openElements.hasInTableScope(o.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=b.IN_TABLE,_n(e,t)):ot(e,t)}function mb(e,t){const r=t.tagID;switch(r){case o.CAPTION:case o.TABLE:{e.openElements.hasInTableScope(o.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=b.IN_TABLE,r===o.TABLE&&Ai(e,t));break}case o.BODY:case o.COL:case o.COLGROUP:case o.HTML:case o.TBODY:case o.TD:case o.TFOOT:case o.TH:case o.THEAD:case o.TR:break;default:Ua(e,t)}}function Xc(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.COL:{e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case o.TEMPLATE:{Bt(e,t);break}default:oa(e,t)}}function Eb(e,t){switch(t.tagID){case o.COLGROUP:{e.openElements.currentTagId===o.COLGROUP&&(e.openElements.pop(),e.insertionMode=b.IN_TABLE);break}case o.TEMPLATE:{Vr(e,t);break}case o.COL:break;default:oa(e,t)}}function oa(e,t){e.openElements.currentTagId===o.COLGROUP&&(e.openElements.pop(),e.insertionMode=b.IN_TABLE,e._processToken(t))}function Ba(e,t){switch(t.tagID){case o.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,ne.HTML),e.insertionMode=b.IN_ROW;break}case o.TH:case o.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(B.TR,o.TR),e.insertionMode=b.IN_ROW,Ha(e,t);break}case o.CAPTION:case o.COL:case o.COLGROUP:case o.TBODY:case o.TFOOT:case o.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=b.IN_TABLE,_n(e,t));break}default:_n(e,t)}}function Qo(e,t){const r=t.tagID;switch(t.tagID){case o.TBODY:case o.TFOOT:case o.THEAD:{e.openElements.hasInTableScope(r)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=b.IN_TABLE);break}case o.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=b.IN_TABLE,Ai(e,t));break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:case o.TD:case o.TH:case o.TR:break;default:Ai(e,t)}}function Ha(e,t){switch(t.tagID){case o.TH:case o.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,ne.HTML),e.insertionMode=b.IN_CELL,e.activeFormattingElements.insertMarker();break}case o.CAPTION:case o.COL:case o.COLGROUP:case o.TBODY:case o.TFOOT:case o.THEAD:case o.TR:{e.openElements.hasInTableScope(o.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=b.IN_TABLE_BODY,Ba(e,t));break}default:_n(e,t)}}function Ch(e,t){switch(t.tagID){case o.TR:{e.openElements.hasInTableScope(o.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=b.IN_TABLE_BODY);break}case o.TABLE:{e.openElements.hasInTableScope(o.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=b.IN_TABLE_BODY,Qo(e,t));break}case o.TBODY:case o.TFOOT:case o.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(o.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=b.IN_TABLE_BODY,Qo(e,t));break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:case o.TD:case o.TH:break;default:Ai(e,t)}}function gb(e,t){const r=t.tagID;Rh.has(r)?(e.openElements.hasInTableScope(o.TD)||e.openElements.hasInTableScope(o.TH))&&(e._closeTableCell(),Ha(e,t)):ot(e,t)}function pb(e,t){const r=t.tagID;switch(r){case o.TD:case o.TH:{e.openElements.hasInTableScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=b.IN_ROW);break}case o.TABLE:case o.TBODY:case o.TFOOT:case o.THEAD:case o.TR:{e.openElements.hasInTableScope(r)&&(e._closeTableCell(),Ch(e,t));break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:break;default:Ua(e,t)}}function Lh(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.OPTION:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e._insertElement(t,ne.HTML);break}case o.OPTGROUP:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e.openElements.currentTagId===o.OPTGROUP&&e.openElements.pop(),e._insertElement(t,ne.HTML);break}case o.HR:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e.openElements.currentTagId===o.OPTGROUP&&e.openElements.pop(),e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case o.INPUT:case o.KEYGEN:case o.TEXTAREA:case o.SELECT:{e.openElements.hasInSelectScope(o.SELECT)&&(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode(),t.tagID!==o.SELECT&&e._processStartTag(t));break}case o.SCRIPT:case o.TEMPLATE:{Bt(e,t);break}}}function Ph(e,t){switch(t.tagID){case o.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===o.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===o.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===o.OPTGROUP&&e.openElements.pop();break}case o.OPTION:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop();break}case o.SELECT:{e.openElements.hasInSelectScope(o.SELECT)&&(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode());break}case o.TEMPLATE:{Vr(e,t);break}}}function _b(e,t){const r=t.tagID;r===o.CAPTION||r===o.TABLE||r===o.TBODY||r===o.TFOOT||r===o.THEAD||r===o.TR||r===o.TD||r===o.TH?(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode(),e._processStartTag(t)):Lh(e,t)}function Tb(e,t){const r=t.tagID;r===o.CAPTION||r===o.TABLE||r===o.TBODY||r===o.TFOOT||r===o.THEAD||r===o.TR||r===o.TD||r===o.TH?e.openElements.hasInTableScope(r)&&(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode(),e.onEndTag(t)):Ph(e,t)}function Ab(e,t){switch(t.tagID){case o.BASE:case o.BASEFONT:case o.BGSOUND:case o.LINK:case o.META:case o.NOFRAMES:case o.SCRIPT:case o.STYLE:case o.TEMPLATE:case o.TITLE:{Bt(e,t);break}case o.CAPTION:case o.COLGROUP:case o.TBODY:case o.TFOOT:case o.THEAD:{e.tmplInsertionModeStack[0]=b.IN_TABLE,e.insertionMode=b.IN_TABLE,_n(e,t);break}case o.COL:{e.tmplInsertionModeStack[0]=b.IN_COLUMN_GROUP,e.insertionMode=b.IN_COLUMN_GROUP,Xc(e,t);break}case o.TR:{e.tmplInsertionModeStack[0]=b.IN_TABLE_BODY,e.insertionMode=b.IN_TABLE_BODY,Ba(e,t);break}case o.TD:case o.TH:{e.tmplInsertionModeStack[0]=b.IN_ROW,e.insertionMode=b.IN_ROW,Ha(e,t);break}default:e.tmplInsertionModeStack[0]=b.IN_BODY,e.insertionMode=b.IN_BODY,ot(e,t)}}function Ib(e,t){t.tagID===o.TEMPLATE&&Vr(e,t)}function vh(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(o.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):Zc(e,t)}function bb(e,t){t.tagID===o.HTML?ot(e,t):ca(e,t)}function kh(e,t){var r;if(t.tagID===o.HTML){if(e.fragmentContext||(e.insertionMode=b.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===o.HTML){e._setEndLocation(e.openElements.items[0],t);const n=e.openElements.items[1];n&&!(!((r=e.treeAdapter.getNodeSourceCodeLocation(n))===null||r===void 0)&&r.endTag)&&e._setEndLocation(n,t)}}else ca(e,t)}function ca(e,t){e.insertionMode=b.IN_BODY,xa(e,t)}function yb(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.FRAMESET:{e._insertElement(t,ne.HTML);break}case o.FRAME:{e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case o.NOFRAMES:{Bt(e,t);break}}}function Nb(e,t){t.tagID===o.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==o.FRAMESET&&(e.insertionMode=b.AFTER_FRAMESET))}function wb(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.NOFRAMES:{Bt(e,t);break}}}function Db(e,t){t.tagID===o.HTML&&(e.insertionMode=b.AFTER_AFTER_FRAMESET)}function Sb(e,t){t.tagID===o.HTML?ot(e,t):as(e,t)}function as(e,t){e.insertionMode=b.IN_BODY,xa(e,t)}function Ob(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.NOFRAMES:{Bt(e,t);break}}}function Mb(e,t){t.chars=Ye,e._insertCharacters(t)}function Rb(e,t){e._insertCharacters(t),e.framesetOk=!1}function xh(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==ne.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function Cb(e,t){if(YA(t))xh(e),e._startTagOutsideForeignContent(t);else{const r=e._getAdjustedCurrentElement(),n=e.treeAdapter.getNamespaceURI(r);n===ne.MATHML?Th(t):n===ne.SVG&&(qA(t),Ah(t)),$c(t),t.selfClosing?e._appendElement(t,n):e._insertElement(t,n),t.ackSelfClosing=!0}}function Lb(e,t){if(t.tagID===o.P||t.tagID===o.BR){xh(e),e._endTagOutsideForeignContent(t);return}for(let r=e.openElements.stackTop;r>0;r--){const n=e.openElements.items[r];if(e.treeAdapter.getNamespaceURI(n)===ne.HTML){e._endTagOutsideForeignContent(t);break}const i=e.treeAdapter.getTagName(n);if(i.toLowerCase()===t.tagName){t.tagName=i,e.openElements.shortenToLength(r);break}}}B.AREA,B.BASE,B.BASEFONT,B.BGSOUND,B.BR,B.COL,B.EMBED,B.FRAME,B.HR,B.IMG,B.INPUT,B.KEYGEN,B.LINK,B.META,B.PARAM,B.SOURCE,B.TRACK,B.WBR;function Pb(e,t,r){typeof e=="string"&&(r=t,t=e,e=null);const n=eI.getFragmentParser(e,r);return n.tokenizer.write(t,!0),n.getFragment()}const lr=e=>{if(!Le(e))throw Oe("帖子响应必须是对象");return e};function At(e){if(typeof e!="string")throw Oe("帖子响应字符串字段无效");return e}function Sr(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw Oe("帖子响应数值字段无效");return e}function os(e){if(typeof e!="boolean")throw Oe("帖子响应状态无效");return e}function vb(e,t){if(!Array.isArray(e))throw Oe("帖子响应列表无效");return e.map(t)}function kb(e){const t=lr(e),r=At(t.revision);if(!/^(0|[1-9]\d*)$/.test(r))throw Oe("绑定版本无效");return{postId:At(t.postId),revision:r}}function xb(e){const t=lr(e);return{id:At(t.id),name:At(t.name),avatar:At(t.avatar),isMe:os(t.isMe)}}function Ub(e){const t=lr(e);return{url:At(t.url),width:Sr(t.width),height:Sr(t.height)}}function Bb(e){const t=lr(e),r=lr(t.stats),n=lr(t.viewer);return{id:At(lr(t.binding).postId),title:At(t.title),text:At(t.text),author:xb(t.author),content:vb(t.content,i=>{const s=lr(i);if(s.type==="text")return{type:"text",text:At(s.text)};if(s.type==="image")return{type:"image",image:Ub(s.image)};if(s.type==="link")return{type:"link",url:At(s.url)};throw Oe("帖子内容类型无效")}),createdAt:Sr(t.createdAt),updatedAt:Sr(t.updatedAt),url:At(t.url),canComment:os(t.canComment),stats:{likes:Sr(r.likes),comments:Sr(r.comments),favorites:Sr(r.favorites)},viewer:{liked:os(n.liked),favorited:os(n.favorited)}}}const Hb=new Set(["address","article","aside","blockquote","div","dl","dt","dd","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","caption","td","th","tr","ul"]);function Fb(e){const t=[];let r=!1,n=!1;const i=()=>t.length===0||t[t.length-1].endsWith(`
6
- `),s=()=>{r&&!i()&&t.push(`
7
- `),r&&(n=!1),r=!1};function a(c,u=!1){const d="tagName"in c?c.tagName:"";if(["script","style","video"].includes(d))return;if(d==="br"){s(),n=!1,t.push(`
8
- `);return}const l=Hb.has(d);if(l&&t.length>0&&(r=!0),u=u||d==="pre"||d==="textarea","value"in c){const h=c.value;if(!u&&/^[ \t\r\n\f]*$/.test(h)){if(r||i())return;n=!0;return}s(),n&&!t[t.length-1].endsWith(" ")&&t.push(" "),n=!1,t.push(h)}"childNodes"in c&&c.childNodes.forEach(h=>a(h,u)),l&&t.length>0&&(r=!0)}return a(Pb(At(e))),t.join("")}function Wt(e){if(!Le(e))throw Oe("社区评论响应无效");return e}function ur(e){const t=typeof e=="string"&&/^\d+$/.test(e)?Number(e):e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw Oe("社区评论数值无效");return t}function ei(e){if(e==null||e===""||e===0||e==="0")return"";if(typeof e!="string"&&!Number.isSafeInteger(e))throw Oe("社区评论 ID 无效");const t=String(e);if(!/^[1-9]\d{0,18}$/.test(t))throw Oe("社区评论 ID 无效");return t}function so(e){if(typeof e!="string")throw Oe("社区评论文本无效");return e}function Wo(e,t,r,n){const i=Wt(e),s=ei(i.commentid);if(!s)throw Oe("社区评论缺少 ID");const a=i.user==null?{}:Wt(i.user),c=ei(i.userid??a.userid),u=i.is_support==null?void 0:ur(i.is_support);if(u!==void 0&&![0,1,2].includes(u))throw Oe("社区评论点赞状态无效");const d=i.imgs==null?void 0:(()=>{if(!Array.isArray(i.imgs))throw Oe("社区评论图片无效");return i.imgs.map(h=>{const f=Wt(h);return{url:so(f.url),width:ur(f.width??0),height:ur(f.height??0)}})})(),l=(d?.length??0)>0||ur(i.has_imgs??0)>0;return{id:s,rootCommentId:t||s,replyToCommentId:ei(i.replyid),author:{id:c,name:so(a.username??""),avatar:so(a.avatar??""),isMe:c===r},text:Fb(i.text),hasImages:l,...d?.length||!l?{images:d??[]}:{},createdAt:ur(i.create_at),likes:ur(i.up??0),replies:ur(i.child_num??0),...u!==void 0?{liked:u===1}:{},canDelete:c===r||n===r}}function zb(e,t,r,n,i,s){const a=Wt(t),c=a.comments??[];if(!Array.isArray(c))throw Oe("社区评论列表无效");const u=c.map(h=>{if(r)return Wo(h,r,n,i);const f=Wt(h).comment;if(!Array.isArray(f)||!f.length)throw Oe("社区评论楼层无效");return Wo(f[0],"",n,i)});if(r){if(typeof a.has_more!="boolean")throw Oe("社区回复分页无效");const h=ei(a.lastval);if(a.has_more&&!h)throw Oe("社区回复缺少游标");return{items:u,cursor:a.has_more?h:"",hasMore:a.has_more}}const d=a.total_page??Wt(e).total_page,l=d==null?u.length>0:s<ur(d);return{items:u,cursor:l?String(s+1):"",hasMore:l}}function jb(e,t,r,n,i,s){const a=Wt(t),c=a.current_comment??Wt(e).current_comment,u=[...c==null?[]:[c],...Array.isArray(a.comments)?a.comments:[]];for(const d of u){const l=Wt(d).comment;if(!Array.isArray(l))continue;const h=l.find(f=>ei(Wt(f).commentid)===r);if(h)return Wo(h,n,i,s)}throw{code:"COMMENT_UNAVAILABLE",message:"评论不存在或不可访问"}}const Uh=3e4;function Vb(e){let t=!1,r=!0,n=!1,i=!1,s;const a=()=>t&&r&&!n,c=()=>{clearTimeout(s),s=void 0},u=()=>{c(),a()&&(s=setTimeout(d,Uh*(1+(e.random??Math.random)()*.1)))};async function d(){if(c(),!(!a()||i)){i=!0;try{await e.refresh()}catch{}finally{i=!1,u()}}}return{setEnabled(l){n||t===l||(t=l,t?u():c())},setVisible(l){n||r===l||(r=l,r?d():c())},reset:d,invalidate(l){if(!(!t||n))try{e.emit(l)}catch{}},dispose(){n=!0,c()}}}function Gb(e){const t=new Set;let r=0,n=!1,i,s,a=!1,c=new AbortController,u,d=!1,l,h=0,f=0,_,p,y,w;const N=R=>{if(n||e.operationContext.signal.aborted)throw oe("RUNTIME_DESTROYED","小程序已关闭");if(r!==R)throw oe("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")};function O(){if(d)throw oe("BINDING_CHANGED","关联帖子已更换,请重新打开小程序")}function I(R){throw Le(R)&&R.code==="BINDING_CHANGED"&&(H(),O()),R}function H(){if(!d){d=!0,l=void 0,y?.abort(),c.abort(),z.setEnabled(!1);try{e.emit({changed:["binding"]})}catch{}}}function Q(R){return O(),u&&(u.revision!==R.revision||u.postId!==R.postId)&&(H(),O()),u??=R,u}async function M(R,K){N(R),O();const Z=await e.account.getCurrentUserId(K);if(N(R),O(),i!==void 0&&i!==Z)throw V(),oe("AUTHORIZATION_CONTEXT_CHANGED","账号已变化,请重试");if(!Z)throw oe("UNAUTHORIZED","请先登录小黑盒");if(a&&s!==Z)throw oe("AUTHORIZATION_CONTEXT_CHANGED","账号已变化,请重试");i=Z}async function x(R,K,Z,ee=r){const se=Ue(Ue(e.operationContext,c.signal),Z);await M(ee,se);const fe=await K(se);await M(ee,se);const we=await Ri({network:e.network,operationContext:se,subject:"关联帖子",assertUsable:()=>{N(ee),O()},...e.requestGate?{gate:{capability:"post",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},R,fe);return await M(ee,se),we}async function v(R,K,Z){try{const ee=await x(nA,async fe=>{if(!e.authorizationContext)throw oe("METHOD_FORBIDDEN","宿主不支持关联帖子授权上下文");const we=await e.authorizationContext.get(fe);if(!we.token||we.expiresAt<=Date.now())throw oe("UNAUTHORIZED","小程序运行上下文已过期");return{runtime_auth_context_token:we.token,action:R,payload:JSON.stringify(K)}},Z),se=at(ee,R,"关联帖子");if(!Le(se)||!Le(se.data))throw oe("INVALID_RESPONSE","关联帖子响应缺少数据");return se.data}catch(ee){return I(ee)}}function W(){if(p)return p;const R=r,K=f,Z=v("get",{},e.operationContext.signal).then(ee=>{if(N(R),K!==f)return p=void 0,W();Q(kb(ee.binding));const se=Bb(ee);if(ee.commentsRevision!==void 0&&(typeof ee.commentsRevision!="string"||!/^\d+$/.test(ee.commentsRevision)))throw oe("INVALID_RESPONSE","评论版本无效");const fe=[];if(l){const{stats:we,viewer:Pe,...E}=l,{stats:m,viewer:S,...D}=se;JSON.stringify(E)!==JSON.stringify(D)&&fe.push("content"),JSON.stringify([we,Pe])!==JSON.stringify([m,S])&&fe.push("stats")}return ee.commentsRevision!==void 0&&_!==void 0&&_!==ee.commentsRevision&&fe.push("comments"),l=se,h=Date.now(),ee.commentsRevision!==void 0&&(_=ee.commentsRevision),fe.length&&z.invalidate({changed:fe}),se}).catch(ee=>{if(r===R&&f===K&&Le(ee)&&["POST_UNAVAILABLE","POST_NOT_BOUND","POST_TYPE_UNSUPPORTED"].includes(String(ee.code))){const se=l!==void 0;l=void 0,se&&z.invalidate({changed:["content","stats"]})}throw ee}).finally(()=>{p===Z&&(p=void 0)});return p=Z,Z}function q(R){N(R),O(),f++,h=0}async function te(R,K){const Z=r;try{await K()}catch(ee){if(n||e.operationContext.signal.aborted||r!==Z||ee instanceof Error&&ee.name==="AbortError")return;try{e.onBackgroundError?.(R,ee)}catch{}}}function F(R,K){return q(R),z.invalidate({changed:["comments"]}),v("comments.changed",{bindingRevision:u.revision},K)}async function G(R){const K=r;await M(K,Ue(e.operationContext,R));const Z=l&&Date.now()-h<Uh?l:await Se(W,R).catch(ee=>{throw O(),ee});return N(K),O(),Z}async function j(R,K,Z,ee,se){const we=await x(R==="post.setLiked"?rA:tA,()=>({targetId:Z,enabled:K.liked===!0||K.favorited===!0}),ee,se);(!Le(we)||we.status!=="ok")&&at(we,R,"帖子互动")}const z=Vb({emit:e.emit,refresh:W});function V(){r++,l&&z.invalidate({changed:["content","stats"]}),l=void 0,h=0,_=void 0,p=void 0,y?.abort(),c.abort(),c=new AbortController,i=void 0,z.reset()}const U=Ci(e.account,R=>{s=R,a=!0,i!==void 0&&R!==i&&V()}),k=e.authorization.onEvent(V),Y={};for(const R of[...ga,...ai])Y[R]=async(K,Z)=>{if(N(r),R==="post.watch"){if(K!==void 0)throw oe("INVALID_ARGUMENT","变化订阅无需参数");if(t.size>=32)throw oe("RATE_LIMITED_BY_RUNTIME","帖子订阅过多");const m=r;if(O(),await G(Z.signal),N(m),O(),Z.signal.aborted)return;if(t.size>=32)throw oe("RATE_LIMITED_BY_RUNTIME","帖子订阅过多");return new Promise((S,D)=>{const P=()=>{Z.signal.removeEventListener("abort",P),t.delete(P),z.setEnabled(t.size>0&&!d),S()};t.add(P),Z.signal.addEventListener("abort",P,{once:!0}),z.setEnabled(!0);try{Z.postProgress({watching:!0})}catch(X){Z.signal.removeEventListener("abort",P),t.delete(P),z.setEnabled(t.size>0&&!d),D(X)}})}if(ai.includes(R)&&!Z.trustedUserGesture)throw oe("USER_GESTURE_REQUIRED","请通过用户操作发起帖子互动");const se=Yb(R,K);O();const fe=r;if(R==="post.get")return JSON.parse(JSON.stringify(await G(Z.signal)));let we;R==="post.comments.openEditor"&&(y?.abort(),y=we=new AbortController,w=Z.requestId,Z={...Z,...Ue(Z,we.signal)});const Pe=await G(Z.signal),E=i;if(N(fe),O(),R==="post.comments.delete"||R==="post.comments.setLiked"){const m=await x(R==="post.comments.delete"?eA:JT,()=>({body:{comment_id:se.commentId,...R==="post.comments.setLiked"?{support_type:se.liked?1:2}:{}}}),Z.signal,fe);(!Le(m)||m.status!=="ok")&&at(m,R,"帖子评论"),te("post.comments.changed",()=>F(fe,c.signal));return}if(R.startsWith("post.comments.")){const{cursor:m,limit:S}=se,D=Z.signal;if(R==="post.comments.list"){const P=String(se.rootCommentId??""),X=P?1:Number(m||1),ce=P?{root_comment_id:P,lastval:m||"",limit:S??20}:{link_id:Pe.id,page:X,limit:S??20,owner_only:0,hide_cy:1,sort_filter:0,index:2},_e=await x(P?XT:gd,()=>ce,D,fe);return zb(_e,at(_e,R,"帖子评论"),P,E,Pe.author.id,X)}if(R==="post.comments.openEditor"){const P=e.presentation?.openPostCommentEditor;if(!P||!we)throw oe("METHOD_FORBIDDEN","当前宿主不支持评论编辑器");let X;if(se.replyToCommentId){const ye=String(se.replyToCommentId),Ee=String(se.rootCommentId??ye),Ce=await x(gd,()=>({link_id:Pe.id,root_comment_id:Ee,comment_id:ye,page:1,limit:20,owner_only:0,hide_cy:1,sort_filter:0,index:2}),D,fe);X=jb(Ce,at(Ce,R,"帖子评论"),ye,Ee,E,Pe.author.id)}const ce=Ue(Ue(e.operationContext,c.signal),we.signal),_e=Ue(ce,D);await M(fe,_e),await Se(()=>P({postId:Pe.id,...X?{reply:X}:{},lifetimeSignal:ce.signal,onSubmitted(){y!==we||ce.signal.aborted||r!==fe||te("post.comments.changed",async()=>{await M(fe,ce),!ce.signal.aborted&&await F(fe,ce.signal)})}},_e),_e.signal),await M(fe,_e);return}}await j(R,se,Pe.id,Z.signal,fe),q(fe),te("post.get",W)};return{handlers:Y,setVisible:z.setVisible,dismissEditor(R){R===w&&(w=void 0,y?.abort())},dispose(){if(!n){n=!0;for(const R of[...t])R();r++,c.abort(),z.dispose(),U(),k()}}}}const Gi={"post.get":[],"post.comments.list":["rootCommentId","cursor","limit"],"post.comments.openEditor":["replyToCommentId","rootCommentId"],"post.comments.delete":["commentId"],"post.comments.setLiked":["commentId","liked"],"post.setLiked":["liked"],"post.setFavorited":["favorited"]};function Yb(e,t){if(Gi[e].length===0&&t===void 0)return{};if(!Le(t)||Object.keys(t).some(r=>!Gi[e].includes(r)))throw oe("INVALID_ARGUMENT","帖子操作参数无效");for(const r of["liked","favorited"])if(Gi[e].includes(r)&&typeof t[r]!="boolean")throw oe("INVALID_ARGUMENT","请提供目标状态");for(const r of["rootCommentId","replyToCommentId","commentId"])if(t[r]!==void 0&&(typeof t[r]!="string"||!/^[1-9]\d{0,18}$/.test(t[r])))throw oe("INVALID_ARGUMENT","评论 ID 无效");if(Gi[e].includes("commentId")&&t.commentId===void 0)throw oe("INVALID_ARGUMENT","缺少评论 ID");if(e==="post.comments.openEditor"&&t.rootCommentId!==void 0&&t.replyToCommentId===void 0)throw oe("INVALID_ARGUMENT","根评论 ID 需要同时指定回复目标");if(t.limit!==void 0&&(!Number.isInteger(t.limit)||Number(t.limit)<1||Number(t.limit)>50))throw oe("INVALID_ARGUMENT","分页数量须为 1–50");if(t.cursor!==void 0&&(typeof t.cursor!="string"||!/^(|[1-9]\d{0,18})$/.test(t.cursor)))throw oe("INVALID_ARGUMENT","评论游标无效");if(!t.rootCommentId&&t.cursor&&!Number.isSafeInteger(Number(t.cursor)))throw oe("INVALID_ARGUMENT","评论页码无效");return{...t}}const qb=new Set(["stdio","attachments","notifications"]),Bh=new Set(["windows-x64","macos-arm64"]),Qb=new Set(["unsigned","valid","invalid","unknown"]),Wb=/^[a-f0-9]{64}$/,$b=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Kb=new Set(df),Zb=new Set([...df,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Hh=Object.freeze({COMPANION_UNSUPPORTED:"当前 Host 不支持 Companion",COMPANION_PREVIEW_UNSUPPORTED:"当前 Host 不支持预览 Companion",COMPANION_NOT_DECLARED:"当前版本未声明该 Companion",COMPANION_TARGET_UNSUPPORTED:"当前平台不支持该 Companion target",COMPANION_NOT_PREPARED:"Companion 尚未准备完成",COMPANION_PREPARATION_CANCELLED:"Companion 准备已取消",COMPANION_DOWNLOAD_FAILED:"Companion 下载失败",COMPANION_DESCRIPTOR_UNAVAILABLE:"Companion 授权或描述符暂不可用",COMPANION_ARCHIVE_INVALID:"Companion 归档不合法",COMPANION_INTEGRITY_FAILED:"Companion 完整性校验失败",COMPANION_ENTRYPOINT_INVALID:"Companion 入口不合法",COMPANION_USER_CANCELLED:"用户取消了 Companion 操作",COMPANION_ELEVATION_DENIED:"用户未授予 Companion 管理员权限",COMPANION_OS_BLOCKED:"操作系统安全策略阻止了 Companion",COMPANION_LAUNCH_FAILED:"Companion 启动失败",COMPANION_SESSION_VERSION_MISMATCH:"Companion Session 版本不匹配",COMPANION_SESSION_OWNERSHIP_LOST:"Companion Session 控制权已转移",COMPANION_SESSION_EXITED:"Companion Session 已退出",COMPANION_PIPE_CLOSED:"Companion 通信管道已关闭",COMPANION_OUTPUT_LIMIT:"Companion 输出超过限制",COMPANION_PROCESS_CRASHED:"Companion 进程异常退出",COMPANION_ATTACHMENT_NOT_FOUND:"Companion Attachment 不存在",COMPANION_NOTIFICATION_UNAVAILABLE:"Companion 通知不可用",COMPANION_TERMINATE_FAILED:"Companion 终止失败",PERMISSION_DENIED:"桌面辅助应用权限未启用或已撤销",USER_GESTURE_REQUIRED:"当前操作需要新的可信用户手势"});function Xb(e){const t=async(n,i,s,a)=>{const c=Jb(n);try{Gt(i.signal);const u=await s(c,{...e.operationContext,signal:i.signal});return Gt(i.signal),u}catch(u){throw Ko(u,a)}},r=async(n,i,s)=>{if(!s.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw T("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const a={...e.operationContext,signal:s.signal},c=await e.companion.getInfo(i,a).then(d=>ey(d,i)).catch(d=>{throw Ko(d)});Gt(s.signal);const u=await e.companionPresentation.confirmCompanionOperation({action:n,companion:c,miniProgram:e.miniProgramPresentation,signal:s.signal});if(Gt(s.signal),u.status!=="granted")throw T("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[pa]:(n,i)=>t(n,i,async(s,a)=>$o(await e.companion.getInfo(s,a),s)),[_a]:(n,i)=>t(n,i,async(s,a)=>Od(await e.companion.getPreparationStatus(s,a))),[Ta]:(n,i)=>t(n,i,async(s,a)=>{const c=Od(await e.companion.getPreparationStatus(s,a));return Gt(i.signal),c.state!=="ready"&&c.state!=="preparing"&&await r("prepare",s,i),Gt(i.signal),$o(await e.companion.prepare(s,{...a,onProgress:u=>i.postProgress(zh(u))}),s)},"COMPANION_PREPARATION_CANCELLED"),[Aa]:(n,i)=>t(n,i,(s,a)=>e.companion.cancelPreparation(s,a)),[Ia]:(n,i)=>t(n,i,async(s,a)=>Md(await e.companion.getActiveSession(s,a),s)),[ba]:(n,i)=>t(n,i,async(s,a)=>{const c=Md(await e.companion.getActiveSession(s,a),s);return Gt(i.signal),c||(await r("launch",s,i),Gt(i.signal),jh(await e.companion.launch(s,a),s))}),[ya]:(n,i)=>en(n,i,e,"write"),[Na]:(n,i)=>en(n,i,e,"closeStdin"),[wa]:(n,i)=>en(n,i,e,"terminate"),[Da]:(n,i)=>en(n,i,e,"ackOutput"),[Sa]:async(n,i)=>{const s=await en(n,i,e,"openAttachment");return e.fileRegistry.registerFile(s,"companion-attachment","read")},[Oa]:(n,i)=>en(n,i,e,"showNotification")}}function Jb(e){if(!pe(e)||typeof e.alias!="string"||!uE.test(e.alias))throw T("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Gt(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function en(e,t,r,n){if(!pe(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw T("INVALID_PARAMS","Companion Session controller 不合法");try{Gt(t.signal);const i=await r.companion[n](ty(e,n),{...r.operationContext,signal:t.signal});return Gt(t.signal),i}catch(i){throw Ko(i)}}function xt(){throw T("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Fh(e){return!Array.isArray(e)||e.some(t=>!qb.has(t))?xt():Object.freeze([...new Set(e)])}function $o(e,t){return!pe(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Bh.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!Qb.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?xt():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Fh(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function ey(e,t){const r=$o(e,t);return!pe(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!Wb.test(e.sha256)?xt():Object.freeze({...r,sha256:e.sha256})}function zh(e){return pe(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}):xt():xt()}function Od(e){return pe(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:zh(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&pe(e.error)&&typeof e.error.code=="string"&&Kb.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:Hh[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):xt():xt()}function jh(e,t){return!pe(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Bh.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?xt():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Fh(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Md(e,t){return e===void 0?void 0:jh(e,t)}function ty(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!rf(r.data))throw T("INVALID_PARAMS","Companion write data 不合法");return{...n,data:new Uint8Array(r.data)}}if(t==="ackOutput"){if(r.stream!=="stdout"&&r.stream!=="stderr"||!Number.isSafeInteger(r.sequence)||Number(r.sequence)<0)throw T("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw T("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw T("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function ry(e){return!pe(e)||!$b.has(String(e.reason))?xt():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):xt():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?xt():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function ny(e){if(!pe(e)||!pe(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,r=t.sessionId;if(e.type==="companion.session.output")return!Number.isSafeInteger(t.controllerGeneration)||Number(t.controllerGeneration)<0||t.stream!=="stdout"&&t.stream!=="stderr"||!Number.isSafeInteger(t.sequence)||Number(t.sequence)<0||!rf(t.data)?void 0:{type:e.type,payload:{sessionId:r,controllerGeneration:t.controllerGeneration,stream:t.stream,sequence:t.sequence,data:new Uint8Array(t.data)}};if(e.type==="companion.session.exit")try{return{type:e.type,payload:{sessionId:r,exit:ry(t.exit)}}}catch{return}if(e.type==="companion.session.ownershipLost"&&Number.isSafeInteger(t.controllerGeneration)&&Number(t.controllerGeneration)>=0)return{type:e.type,payload:{sessionId:r,controllerGeneration:t.controllerGeneration}}}function Ko(e,t){return pe(e)&&typeof e.code=="string"&&Zb.has(e.code)?T(e.code,Hh[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&pe(e)&&e.name==="AbortError"?T(t,"Companion 准备已取消"):T("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Rd=5e3,Cd=1e4;function lt(e){throw{code:"INVALID_PARAMS",message:e}}function Jc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vh(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&lt(`${r} 不支持字段: ${n.join(", ")}`)}function iy(e){if(e===void 0)return{intensity:"light",delay:0};if(!Jc(e))return lt("device.vibrate 参数必须是对象");Vh(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return lt("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Rd?lt(`device.vibrate delay 必须是 0-${Rd} 的整数毫秒`):{intensity:r,delay:n}}function sy(e){return Jc(e)?(Vh(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?lt("device.setClipboard text 必须是非空字符串"):e.text.length>Cd?lt(`device.setClipboard text 不能超过 ${Cd} 字符`):{text:e.text}):lt("device.setClipboard 参数必须是对象")}function ay(e){return typeof e=="string"?e.trim()?e:lt("device.executeProtocol 协议字符串不能为空"):Jc(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?lt("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(Zo(e,new Set),e):lt("device.executeProtocol 参数必须是协议字符串或协议对象")}function Zo(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||lt("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":lt("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":lt(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&lt("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)Zo(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&lt("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))Zo(i,t);t.delete(r)}function oy(e){return{[qs]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),await Se(()=>e.presentation.vibrate(iy(t),n),n.signal)},[Qs]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),await Se(()=>e.presentation.setClipboard(sy(t),n),n.signal)},[Ws]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal);const i=ay(t);await Se(()=>e.protocol.invoke(i,n),n.signal)}}}const Ld=1e3,cy=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function uy(e){const t=r=>Ue(e.operationContext,r.signal);return{files:{[vs]:async(r,n)=>{ao(n);const i=oo(e.picker),s=dy(r),a=await Tt(()=>i.pickFiles(s,t(n)));return e.registry.registerFiles(a,"external",s.mode,s.multiple?void 0:1)},[ks]:async(r,n)=>{ao(n);const i=oo(e.picker),s=ly(r),a=await Tt(()=>i.pickDirectory(s,t(n)));return e.registry.registerDirectory(a,"external",s.mode)},[xs]:async(r,n)=>{ao(n);const i=oo(e.picker),s=fy(r).suggestedName,a=t(n);if(!i.saveFile)throw Ot("files.saveFile");const c=await Tt(()=>i.saveFile({suggestedName:s},a));return e.registry.registerFile(c,"external","readwrite")}},file:{[di]:async(r,n)=>{const i=yt(r,["recursive","exclusive"]),s=e.registry.resolveFile(i.target);tn(s.mode),await Tt(()=>s.create(Pd(i),t(n)))},[li]:async(r,n)=>{const i=yt(r),s=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(s),tn(s.handle.mode),!s.handle.remove)throw Ot(li);await Tt(()=>s.handle.remove(t(n)))},[Us]:async(r,n)=>{const i=yt(r);return vd(async()=>{const s=await e.registry.resolveFile(i.target).stat(t(n));if(!pe(s)||s.kind!=="file")throw xd()})},[fi]:async(r,n)=>{const i=yt(r),s=kd(await Tt(()=>e.registry.resolveFile(i.target).read(t(n))));try{const a=new TextDecoder("utf-8",{fatal:!0}).decode(s);return a.charCodeAt(0)===65279?a.slice(1):a}catch{throw T("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Bs]:async(r,n)=>{const i=yt(r,["content"]);typeof i.content!="string"&&Mt("content 必须是字符串");const s=e.registry.resolveFile(i.target);tn(s.mode),await Tt(()=>s.write(new TextEncoder().encode(i.content),t(n)))},[hi]:async(r,n)=>{const i=yt(r),s=await Tt(()=>e.registry.resolveFile(i.target).read(t(n)));return kd(s)},[Hs]:async(r,n)=>{const i=yt(r,["content"]),s=e.registry.resolveFile(i.target);tn(s.mode),await Tt(()=>s.write(my(i.content),t(n)))},[mi]:async(r,n)=>{const i=yt(r),s=await Tt(()=>e.registry.resolveFile(i.target).stat(t(n)));return Ey(s)}},directory:{[Fs]:async(r,n)=>{const i=yt(r,["recursive","exclusive"]),s=e.registry.resolveDirectory(i.target);tn(s.mode),await Tt(()=>s.create(Pd(i),t(n)))},[Ei]:async(r,n)=>{const i=yt(r,["recursive"]);if(pe(i.target)&&i.target.relativePath===".")throw T("FILE_ACCESS_DENIED","不能删除根目录");const s=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(s),tn(s.handle.mode),!s.handle.remove)throw Ot(Ei);await Tt(()=>s.handle.remove({recursive:i.recursive===void 0?!1:ua(i.recursive,"recursive")},t(n)))},[zs]:async(r,n)=>{const i=yt(r);return vd(async()=>{const s=await e.registry.resolveDirectory(i.target).stat(t(n));if(!pe(s)||s.kind!=="directory")throw xd()})},[js]:async(r,n)=>{const i=yt(r,["limit"]),s=hy(i.limit),a=e.registry.resolveDirectoryEntry(i.target),c=await Tt(()=>a.handle.list({limit:s},t(n)));return e.registry.describeListedEntries(a,c,s)}}}}function dy(e){if(e===void 0)return{mode:"read",multiple:!1};pe(e)||Mt("pickFiles 参数必须是对象"),Fa(e,["mode","accept","multiple"]);const t=Gh(e.mode,"read"),r=e.multiple===void 0?!1:ua(e.multiple,"multiple");let n;return e.accept!==void 0&&((!Array.isArray(e.accept)||e.accept.some(i=>typeof i!="string"||!/^\.[a-z0-9][a-z0-9._-]*$/i.test(i)))&&Mt("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function ly(e){return e===void 0?{mode:"read"}:(pe(e)||Mt("pickDirectory 参数必须是对象"),Fa(e,["mode"]),{mode:Gh(e.mode,"read")})}function fy(e){return pe(e)||Mt("saveFile 参数必须是对象"),Fa(e,["suggestedName"]),{suggestedName:Di(e.suggestedName,"suggestedName")}}function yt(e,t=[]){return(!pe(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Mt("文件操作参数必须包含 target"),Fa(e,["target",...t]),e}function Pd(e){return{recursive:e.recursive===void 0?!1:ua(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:ua(e.exclusive,"exclusive")}}function Gh(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&Mt("mode 必须是 read 或 readwrite"),e)}function ua(e,t){return typeof e!="boolean"&&Mt(`${t} 必须是布尔值`),e}function hy(e){if(e===void 0)return Ld;if((!Number.isSafeInteger(e)||e<=0)&&Mt("limit 必须是正整数"),e>Ld)throw T("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Fa(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&Mt(`不支持字段: ${r.join(", ")}`)}function tn(e){if(e!=="readwrite")throw T("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function ao(e){if(!e.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function oo(e){if(!e)throw Ot("files.external");return e}async function vd(e){try{return await e(),!0}catch(t){if(cy.has(jc(t)??""))return!1;throw gn(t)}}async function Tt(e){try{return await e()}catch(t){throw gn(t)}}function my(e){return e instanceof Uint8Array||Mt("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Mt("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function kd(e){if(!(e instanceof Uint8Array))throw T("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function xd(){return T("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Ey(e){if(!pe(e)||e.kind!=="file"||!gy(e.size))throw T("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!py(e[t]))throw T("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 gy(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function py(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Mt(e){throw T("INVALID_PARAMS",e)}const Ud=16*1024,Bd=200;function _y(e){const t=Rf(e.runtimePermissions);function r(n,i){e.capabilities&&Nf(i,e.capabilities);const s=t({kind:"all",permissions:["filesystem"]},i);if(!s.allowed)throw T(s.code,s.message);const a=Ue(e.operationContext,n);return Xo(a),a}return{async list(n,i={}){const s=r(i.signal,"directory.list"),a=e.registry.resolveDirectoryEntry({kind:"directory",root:{kind:"sandbox"},relativePath:n}),c=await Hd(()=>a.handle.list({limit:Bd},s),s);return e.registry.describeListedEntries(a,c,Bd).map(({name:u,kind:d})=>({name:u,kind:d}))},async read(n,i={}){const s=i.maxBytes??Ud;if(!Number.isSafeInteger(s)||s<1||s>Ud)throw T("INVALID_PARAMS","诊断读取最多允许 16384 bytes");const a=r(i.signal,"file.readBytes"),c=e.registry.resolveFile({kind:"file",root:{kind:"sandbox"},relativePath:n});if(!c.readPrefix)throw T("DIAGNOSTICS_UNSUPPORTED","当前 Host 不支持有界文件诊断读取");const u=await Hd(()=>c.readPrefix({maxBytes:s},a),a);if(!u||!(u.bytes instanceof Uint8Array)||u.bytes.byteLength>s||typeof u.truncated!="boolean")throw T("FILE_IO_FAILED","Host 返回了无效的有界读取结果");return{bytes:new Uint8Array(u.bytes),truncated:u.truncated}}}}function Xo(e){if(e.signal.aborted)throw T("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")}async function Hd(e,t){let r;try{const n=await Promise.race([e(),new Promise((i,s)=>{r=()=>s(T("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")),t.signal.addEventListener("abort",r,{once:!0}),t.signal.aborted&&r()})]);return Xo(t),n}catch(n){throw t.signal.aborted&&Xo(t),gn(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const Ty=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),co={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function Ay(e){if(e instanceof Je)return T("REQUEST_UNSUPPORTED",co.REQUEST_UNSUPPORTED);const t=Yh(e);return t!==void 0&&Ty.has(t)?T(t,co[t]??"媒体操作失败"):T("MEDIA_PREPARE_FAILED",co.MEDIA_PREPARE_FAILED)}function Yh(e){try{if(!pe(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Iy=["source","mediaType","maxCount"],cs=Object.freeze({source:"album",mediaType:"all",maxCount:1});function by(e){if(e===void 0)return cs;if(!j0(e))throw T("INVALID_PARAMS",Ny(e));return yy(e)}function yy(e){return Object.freeze({source:e.source??cs.source,mediaType:e.mediaType??cs.mediaType,maxCount:e.maxCount??cs.maxCount})}function Ny(e){if(!pe(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!Iy.includes(r));if(t.length>0)return`media.pick 不支持字段: ${t.join(", ")}`;if(e.source!==void 0&&e.source!=="album"&&e.source!=="camera")return"source 必须是 album 或 camera";if(e.mediaType!==void 0&&e.mediaType!=="image"&&e.mediaType!=="video"&&e.mediaType!=="all")return"mediaType 必须是 image、video 或 all";if(e.maxCount!==void 0){if(typeof e.maxCount!="number"||!Number.isSafeInteger(e.maxCount))return"maxCount 必须是安全整数";if(e.source==="camera"&&e.maxCount!==1)return"相机只支持 maxCount 为 1 或省略,不能静默收窄"}return"media.pick 参数不合法"}const wy=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),Dy={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class Sy{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=Oy(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const s=n.map((a,c)=>Ry(a,i[c]));if(!V0(s))throw Qt("Host 返回的媒体结果未通过协议校验");for(const a of n)this.committed.add(a);return s}catch(s){throw this.registry.revokeFiles(i.map(Cy).filter(a=>a!==void 0)),s}}releaseBatch(t,r){this.releaseItems(t,r)}dispose(){if(this.disposed)return;this.disposed=!0;const t=[...this.committed];this.committed.clear(),this.releaseItems(t,{...this.operationContext,lifecycle:"cleanup"})}registerBatch(t,r){try{return this.registry.registerFiles(t.map(n=>n.file),"external","read",r)}catch(n){const i=Yh(n);throw i!==void 0&&wy.has(i)?n:Qt("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function Fd(e,t){if(e.signal.aborted)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw T("REQUEST_CANCELLED","media.pick 已取消")}function Oy(e,t){if(!Array.isArray(e))throw Qt("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw Qt("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw Qt("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw Qt("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw Qt("Host 返回了稀疏媒体结果");My(e[n],n)}return e}function My(e,t){if(!pe(e))throw Qt(`第 ${t+1} 项不是对象`);if(!tf({...e,file:Dy}))throw Qt(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!pe(e.file))throw Qt(`第 ${t+1} 项缺少文件句柄`)}function Ry(e,t){const r={mimeType:e.mimeType,size:e.size,width:e.width,height:e.height,previewUrl:e.previewUrl,file:t};return e.type==="video"?{...r,type:"video",durationMs:e.durationMs}:{...r,type:"image"}}function Cy(e){return"handleId"in e.ref?e.ref.handleId:void 0}function Qt(e){return T("MEDIA_PREPARE_FAILED",e)}function Ly(e){const t=e.media?new Sy(e.registry,e.media,e.operationContext):void 0;return{handlers:{[gi]:async(n,i)=>{const s=by(n);vy(i);const a=e.media,c=t;if(!a||typeof a.pick!="function"||!c)throw Ot(gi);const u=Ue(e.operationContext,i.signal);Fd(e.operationContext,i.signal);const d=await Py(a,s,u,e.operationContext,i.signal);Fd(e.operationContext,i.signal);try{return c.commit(d,s)}catch(l){throw c.releaseBatch(d,u),l}}},dispose(){t?.dispose()}}}async function Py(e,t,r,n,i){try{return await Se(()=>e.pick(t,r),r.signal)}catch(s){throw n.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?T("REQUEST_CANCELLED","media.pick 已取消"):Ay(s)}}function vy(e){if(!e.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Yi=4294967296;function ky(e){const t=new xy;return t.write(e),t.finish()}class xy{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<Yi?(this.writeUint8(206),this.writeUint32(t)):(this.writeUint8(207),this.writeUint64(t));return}t>=-32?this.writeUint8(224|t+32):t>=-128?(this.writeUint8(208),this.writeInt8(t)):t>=-32768?(this.writeUint8(209),this.writeInt16(t)):t>=-2147483648?(this.writeUint8(210),this.writeInt32(t)):(this.writeUint8(211),this.writeInt64(t))}writeString(t){const r=Uy(t),n=r.byteLength;if(n<32)this.writeUint8(160+n);else if(n<256)this.writeUint8(217),this.writeUint8(n);else if(n<65536)this.writeUint8(218),this.writeUint16(n);else if(n<Yi)this.writeUint8(219),this.writeUint32(n);else throw new Error("share extra string is too long");this.writeBytes(r)}writeArray(t){const r=t.length;r<16?this.writeUint8(144+r):r<65536?(this.writeUint8(220),this.writeUint16(r)):(this.writeUint8(221),this.writeUint32(r));for(const n of t)this.write(n)}writeMap(t){const r=Object.keys(t),n=r.length;n<16?this.writeUint8(128+n):n<65536?(this.writeUint8(222),this.writeUint16(n)):(this.writeUint8(223),this.writeUint32(n));for(const i of r)this.writeString(i),this.write(t[i])}ensureCapacity(t){const r=this.offset+t;if(r<=this.bytes.byteLength)return;const n=new Uint8Array(Math.max(r,this.bytes.byteLength*2));n.set(this.bytes),this.bytes=n,this.view=new DataView(n.buffer)}writeBytes(t){this.ensureCapacity(t.byteLength),this.bytes.set(t,this.offset),this.offset+=t.byteLength}writeUint8(t){this.ensureCapacity(1),this.view.setUint8(this.offset,t),this.offset+=1}writeInt8(t){this.ensureCapacity(1),this.view.setInt8(this.offset,t),this.offset+=1}writeUint16(t){this.ensureCapacity(2),this.view.setUint16(this.offset,t),this.offset+=2}writeInt16(t){this.ensureCapacity(2),this.view.setInt16(this.offset,t),this.offset+=2}writeUint32(t){this.ensureCapacity(4),this.view.setUint32(this.offset,t),this.offset+=4}writeInt32(t){this.ensureCapacity(4),this.view.setInt32(this.offset,t),this.offset+=4}writeFloat64(t){this.ensureCapacity(8),this.view.setFloat64(this.offset,t),this.offset+=8}writeUint64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,t/Yi),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Yi)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Uy(e){const t=new Uint8Array(By(e));let r=0,n=0;for(;r<e.length;){let i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<e.length){const s=e.charCodeAt(r);s>=56320&&s<=57343&&(r+=1,i=((i&1023)<<10)+(s&1023)+65536)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6&31|192,t[n++]=i&63|128):i<65536?(t[n++]=i>>12&15|224,t[n++]=i>>6&63|128,t[n++]=i&63|128):(t[n++]=i>>18&7|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=i&63|128)}return t}function By(e){let t=0,r=0;for(;r<e.length;){let n=e.charCodeAt(r++);if(n<128)t+=1;else if(n<2048)t+=2;else{if(n>=55296&&n<=56319&&r<e.length){const i=e.charCodeAt(r);i>=56320&&i<=57343&&(r+=1,n=((n&1023)<<10)+(i&1023)+65536)}t+=n<65536?3:4}}return t}function qh(e){Jo(e);const t=ky(e);if(t.byteLength>128)throw new Error("launch extra is too large");return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Jo(e,t=0,r=new WeakSet){if(t>8)throw new Error("extra nesting depth exceeded");if(e===null||typeof e=="string"||typeof e=="boolean")return;if(typeof e=="number"){if(Number.isFinite(e))return;throw new Error("extra number must be finite")}if(typeof e!="object")throw new Error("extra value must be JSON-compatible");if(r.has(e))throw new Error("extra value must not contain cycles");if(r.add(e),Array.isArray(e)){if(e.length>64)throw new Error("extra array is too large");for(const s of e)Jo(s,t+1,r);r.delete(e);return}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new Error("extra object must be a plain object");const i=Object.entries(e);if(i.length>64)throw new Error("extra object has too many fields");for(const[s,a]of i){if(s==="__proto__")throw new Error("extra object key is not supported");Jo(a,t+1,r)}r.delete(e)}const Hy=["pc","console","mobile"],Fy=["game","wiki"];function da(e){throw{code:"INVALID_PARAMS",message:e}}function zy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _r(e,t){return typeof e!="string"||!e.trim()?da(t):e.trim()}function zd(e,t,r){return typeof e!="string"||!t.includes(e)?da(r):e}function jy(e){const t={target:"game_detail",appId:_r(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:zd(e.gameType,Hy,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=zd(e.page,Fy,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=_r(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=_r(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Vy(e){return{target:"user_detail",userId:_r(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Gy(e){const t={target:"post_detail",linkId:_r(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=_r(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=_r(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Yy(e){const t={target:"mini_program",miniProgramId:_r(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function qy(e){return zy(e)?e.target==="game_detail"?jy(e):e.target==="user_detail"?Vy(e):e.target==="post_detail"?Gy(e):e.target==="mini_program"?Yy(e):da("navigation.openAppPage target 不支持"):da("navigation.openAppPage options 必须是对象")}function Qy(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 Wy(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function $y(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 Ky(e){const t=e;return t.target==="game_detail"?Qy(t):t.target==="user_detail"?Wy(t):$y(t)}const Zy="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",Xy="data-hb-sdk-fullscreen-exit",Jy=3e3,eN=2e3,jd="var(--white-70a,rgba(255,255,255,.7))",Vd="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function tN(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(Xy,""),t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true");const r=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;t.style.cssText=["position:fixed","right:0","top:50%","z-index:2147483647","box-sizing:border-box","width:48px","height:44px","padding:5px 0",`border:1px solid ${jd}`,`box-shadow:${Vd}`,"border-radius:var(--radius-m-token,5px)","display:flex","flex-direction:column","align-items:center","justify-content:center","gap:3px","background:var(--general-color-text-2,#64696e)","color:var(--white-100a,#fff)",'font:400 var(--font-size-9,9px)/var(--line-height-12,12px) "PingFang SC",sans-serif',"cursor:pointer","touch-action:manipulation","opacity:1","transform:translateY(-50%)",r?"transition:none":"transition:width var(--token-transition-arrow,220ms cubic-bezier(.2,.8,.2,1))"].join(";");const n=document.createElement("img");n.src=Zy,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let s=!0,a=!1,c=!1,u,d;function l(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function h(){s||(t.style.width=l())}function f(){d?.cancel(),d=void 0}function _(w=eN){clearTimeout(u),u=setTimeout(()=>{f(),s=!1,t.style.width=l(),t.style.opacity="0.5",t.style.borderColor="var(--white-40a,rgba(255,255,255,.4))",t.style.boxShadow="none",n.style.visibility="hidden",i.style.display="none",t.setAttribute("aria-label","展开退出全屏按钮"),t.setAttribute("aria-expanded","false")},w)}function p(){f(),s=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=jd,t.style.boxShadow=Vd,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),_()}async function y(){if(!(a||c)){if(!s){p();return}c=!0,clearTimeout(u),f();try{await e()}catch{}finally{c=!1,a||p()}}}return t.addEventListener("click",y),window.addEventListener("resize",h),document.body.append(t),!r&&t.animate&&(d=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),_(Jy),{dispose(){a=!0,clearTimeout(u),f(),t.removeEventListener("click",y),window.removeEventListener("resize",h),t.remove()}}}const Qh=1e4;function Wh(e,t){const r=new AbortController;let n;const i=()=>{n??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},r.abort()};e.addEventListener("abort",i,{once:!0}),t?.addEventListener("abort",i,{once:!0}),(e.aborted||t?.aborted)&&i();const s=setTimeout(()=>{n??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},r.abort()},Qh);return{signal:r.signal,async run(a){try{return await Se(a,r.signal)}catch(c){throw n??c}},dispose(){clearTimeout(s),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function Gd(e){if(typeof e!="object"||e===null||Array.isArray(e))throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 参数必须是对象"};const{orientation:t,fullscreen:r}=e;if(t!==void 0&&t!=="portrait"&&t!=="landscape")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay orientation 必须是 portrait 或 landscape"};if(r!==void 0&&typeof r!="boolean")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay fullscreen 必须是布尔值"};if(t===void 0&&r===void 0)throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 至少设置 orientation 或 fullscreen"};return{orientation:t,fullscreen:r}}function uo(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Un(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function rN(e){let t=0,r=0,n,i,s={mode:"portrait",hideCapsule:!1},a={mode:"portrait",hideCapsule:!1},c;function u(){c?.dispose(),c=void 0}function d(p){if(!p.hideCapsule){u();return}c??=tN(()=>_.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",u,{once:!0});function l(p,y){if(n===p){if(n=void 0,clearTimeout(p.timer),e.operationContext.signal.removeEventListener("abort",h),"error"in y)p.controller.abort();else if(i={options:p.options,result:y.result},s=p.options,d(p.options),e.onApplied?.(p.options),y.result.supported&&!uo(a,p.options)){a={...p.options};try{e.onDisplayChange?.({orientation:a.mode,fullscreen:a.hideCapsule,source:p.source})}catch{}}for(const w of p.subscribers)w.dispose(),"error"in y?w.reject(y.error):w.resolve(y.result);p.subscribers.clear()}}function h(){n&&l(n,{error:Un()})}function f(p,y){return new Promise((w,N)=>{const O=()=>{p.subscribers.delete(I),I.dispose(),N(Un()),p.subscribers.size===0&&l(p,{error:Un()})},I={resolve:w,reject:N,dispose:()=>y?.removeEventListener("abort",O)};p.subscribers.add(I),y?.addEventListener("abort",O,{once:!0}),y?.aborted&&O()})}const _={async runDisplayRequest(p,y,w){const N=++t,O=Wh(y,e.operationContext.signal);try{return await O.run(async()=>{if(await w(O.signal),O.signal.aborted)throw Un();if(Gd(p),N<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=N,_.apply(p,O.signal)})}finally{O.dispose()}},async apply(p,y,w="api"){if(ve(e.operationContext.signal),y?.aborted)throw Un();const N=Gd(p),O=n?.options??s,I={mode:N.orientation??O.mode,hideCapsule:N.fullscreen??O.hideCapsule};I.mode==="landscape"&&(I.hideCapsule=!0);const H=e.presentation.applyOrientation;if(!H)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&uo(n.options,I))return f(n,y);if(n&&l(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&uo(i.options,I))return i.result;i=void 0;const Q={options:I,source:w,controller:new AbortController,subscribers:new Set};n=Q;const M=f(Q,y);return e.operationContext.signal.addEventListener("abort",h,{once:!0}),y||(Q.timer=setTimeout(()=>{l(Q,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Qh)),Se(()=>H.call(e.presentation,I,{...e.operationContext,signal:Q.controller.signal}),Q.controller.signal).then(x=>l(Q,{result:x??{supported:!0}}),x=>l(Q,{error:x})),M},dispose(){e.operationContext.signal.removeEventListener("abort",u),u()}};return _}function $h(e){throw{code:"INVALID_PARAMS",message:e}}function Yd(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&$h(`${t} 不支持参数`)}function nN(e){return{[$s]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),Yd(t,"navigation.close"),await Se(()=>e.presentation.close(n),n.signal)},[Ks]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),Yd(t,"navigation.reload"),await Se(()=>e.presentation.reload(n),n.signal)},[Zs]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal);const i=qy(t);if(i.target==="mini_program"){let s;if(i.extra!==void 0)try{s=qh(i.extra)}catch{$h("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const a=e.resetDisplay;if(a){const c=Wh(n.signal);try{await c.run(()=>a(c.signal))}finally{c.dispose()}}ve(n.signal),await Se(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...s===void 0?{}:{extra:s}},n),n.signal);return}await Se(()=>e.presentation.openAppPage(Ky(i),n),n.signal)}}}const qd={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function iN(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw Ot("network.upload");const s=Ue(r.operationContext,t.signal),a=()=>{if(s.signal.aborted)throw T("UPLOAD_CANCELLED","上传已取消")};a();let c,u;try{c=i.resolveFileEntry(e.from).hostHandle,u=await c.stat(s)}catch(f){throw a(),gn(f)}if(a(),u.kind!=="file"||!Number.isSafeInteger(u.size)||u.size<0)throw T("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&u.size>e.maxBytes)throw T("FILE_TOO_LARGE","文件超过大小限制");let d=0,l=!1;const h=f=>{l||s.signal.aborted||!Number.isSafeInteger(f)||f<d||f>u.size||(d=f,t.postProgress({loaded:d,total:u.size,lengthComputable:!0}))};try{const{from:f,..._}=e,p=await n.upload(c,{..._,expectedBytes:u.size,...e.format==="multipart"?{fileName:e.fileName??c.name}:{}},{...s,onProgress:h});if(l=!0,!Number.isSafeInteger(p.uploadedBytes)||p.uploadedBytes<d||p.uploadedBytes>u.size)throw T("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(p.status>=200&&p.status<300&&p.uploadedBytes!==u.size)throw T("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:p.uploadedBytes,total:u.size,lengthComputable:!0}),p}catch(f){l=!0;const _=jc(f);throw _&&qd[_]?T(_,qd[_]):s.signal.aborted?T("UPLOAD_CANCELLED","上传已取消"):_?.startsWith("FILE_")||_?.startsWith("DIRECTORY_")?gn(f):T("UPLOAD_NETWORK_FAILED","上传网络失败")}}const eu="withCredentials",sN=new Set(["url","method","params","data","headers","timeout",eu]),aN=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",eu]),oN=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Qd=3e4,ec=2*1024*1024,cN=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Kh=/[\u0000-\u0008\u000A-\u001F\u007F]/,uN=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,dN="network.request 不支持 multipart/form-data,请使用专用上传能力";function lN(e){const t=fN(e.runtimePermissions);t.allowDevelopmentHttp=e.allowDevelopmentHttp===!0,t.firstParty=e.firstParty===!0,t.networkPolicy=t.firstParty?void 0:Df(e.networkPolicy);const r=DN(e.allowedHttpOrigins);return{[Ps]:async(n,i)=>{const s=mN(n,{permission:t,allowedHttpOrigins:r}),a=await iN(s,i,e),{uploadedBytes:c,...u}=a;return $d(u)},[Ls]:async(n,i)=>{const s=EN(n,{permission:t,allowedHttpOrigins:r});return Uf(s,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Cs]:async(n,i)=>{const s=Ue(e.operationContext,i?.signal);ve(s.signal);const a=hN(n,{permission:t,allowedHttpOrigins:r});let c;try{c=await Se(()=>e.network.request(a,s),s.signal)}catch(u){throw ON(u)?u:MN(u,"REQUEST_UNSUPPORTED")?Re("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):Re("REQUEST_FAILED","网络请求失败")}return $d(c)}}}function fN(e){const t=ft(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function hN(e,t){const r=Tn(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(u=>!sN.has(u));if(n.length>0)throw Re("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Zh(r,"network.request");const i=tu(r,t,"network.request"),s=pN(r.method),a=r.data;a!==void 0&&AN(a),bN(i.headers,a);const c=yN(i.headers,a,i.official);return{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:i.official?"official":"external",...s===void 0?{}:{method:s},...i.params===void 0?{}:{params:i.params},...a===void 0?{}:{data:a},...i.headers===void 0?{}:{headers:i.headers},...c===void 0?{}:{bodyEncoding:c},...i.timeout===void 0?{}:{timeout:i.timeout}}}function mN(e,t){const r=Tn(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(l=>!n.has(l)))throw Re("INVALID_PARAMS","network.upload 包含不支持的字段");const i=tu(r,t,"network.upload");if(!t.permission.firstParty&&i.official)throw Re("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw Re("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!kr(r.from))throw Re("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Re("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw Re("INVALID_PARAMS","format 必须是 raw 或 multipart");const s=r.method??(r.format==="raw"?"PUT":"POST");if(s!=="POST"&&(r.format!=="raw"||s!=="PUT"))throw Re("INVALID_PARAMS","上传 HTTP 方法不支持");const a={from:r.from,format:r.format,request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"upload",method:s,...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}};if(r.format==="raw"){if(["fieldName","fields","fileName","contentType"].some(l=>r[l]!==void 0))throw Re("INVALID_PARAMS","raw 不接受 multipart 字段");return a}if(Object.keys(i.headers??{}).some(l=>l.toLowerCase()==="content-type"))throw Re("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const c=Wd(r.fieldName),u=r.fields===void 0?void 0:Tn(r.fields,"fields 必须是字符串字典");for(const[l,h]of Object.entries(u??{}))if(Wd(l),typeof h!="string"||l===c)throw Re("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw Re("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||Kh.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw Re("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:c,fields:u,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>ec)throw Re("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...a,fieldName:c,...u===void 0?{}:{fields:{...u}},...r.fileName===void 0?{}:{fileName:Gc(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function Wd(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw Re("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function EN(e,t){const r=Tn(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(u=>!aN.has(u));if(n.length>0)throw Re("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Zh(r,"network.download");const i=tu(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw Re("INVALID_PARAMS","network.download timeout 必须是有限正数");e_(i.headers);const s=kr(r.to),a=Jl(r.to);if(!s&&!a)throw Re("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(s&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw Re("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let c;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw Re("INVALID_PARAMS","suggestedName 必须是字符串");c=Gc(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw Re("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Re("INVALID_PARAMS","maxBytes 必须是正的 safe integer");return{request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"download",method:"GET",...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},url:i.url,to:r.to,targetKind:s?"file":"directory",...c===void 0?{}:{suggestedName:c},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function tu(e,t,r){const n=gN(e.url,t.allowedHttpOrigins,r,t.permission.allowDevelopmentHttp===!0),i=qg(n);if(!t.permission.firstParty){const s=t.permission.networkPolicy,a=s?.enforcement==="approved_domains"&&n.protocol==="http:"&&(t.permission.allowDevelopmentHttp===!0||t.allowedHttpOrigins.has(n.origin));if(s&&!a&&(n.protocol!=="https:"||n.port!==""||!s.entries.some(c=>c.domain===n.hostname.toLowerCase())))throw Re("PERMISSION_DENIED",`${r} 目标不在平台批准的域名清单中`);if(i&&!t.permission.useOfficialDomain)throw Re("PERMISSION_DENIED","当前小程序暂不支持访问官方域名")}if(Yg(n.pathname,i))throw Re("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Tn(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:_N(e.headers,r),timeout:TN(e.timeout,r)}}function gN(e,t,r="network.request",n=!1){if(typeof e!="string"||!e.trim())throw Re("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let i;try{i=new URL(e)}catch{throw Re("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw Re("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(i.username||i.password)throw Re("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(i.protocol==="http:"&&!n&&!t.has(i.origin))throw Re("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return i}function pN(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw Re("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!oN.has(t))throw Re("INVALID_PARAMS","network.request method 不合法");return t}function _N(e,t="network.request"){const r=Tn(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,s]of Object.entries(r)){const a=i.trim();if(!a||a!==i||!cN.test(a)||typeof s!="string"||Kh.test(s))throw Re("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Qg(a))throw Re("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[a]=s}return n}function Zh(e,t){const r=e[eu];if(r!==void 0&&typeof r!="boolean")throw Re("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function TN(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw Re("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Qd)throw Re("INVALID_PARAMS",`${t} timeout 不能超过 ${Qd}ms`);return e}}function AN(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw Re("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(IN(e)>ec)throw Re("INVALID_PARAMS",`network.request data 不能超过 ${ec} 字节`)}function IN(e){if(typeof e=="string")return lo(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return lo(e.toString());try{const t=JSON.stringify(e);return t?lo(t):0}catch{throw Re("INVALID_PARAMS","network.request data 必须可序列化")}}function bN(e,t){const r=Xh(e),n=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(r?.includes("multipart/form-data")||n)throw Re("INVALID_PARAMS",dN)}function yN(e,t,r){if(t===void 0)return;const n=Xh(e);return n?.includes("application/x-www-form-urlencoded")?"form":n?.includes("application/json")?"json":typeof URLSearchParams<"u"&&t instanceof URLSearchParams||r&&(Array.isArray(t)||wN(t))?"form":NN(t)?"json":void 0}function Xh(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function NN(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function wN(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function DN(e){const t=new Set;for(const r of e??[])try{const n=new URL(r);n.protocol==="http:"&&!n.username&&!n.password&&n.pathname==="/"&&!n.search&&!n.hash&&SN(n.hostname)&&t.add(n.origin)}catch{}return t}function SN(e){const t=e.toLowerCase();if(t==="[::1]")return!0;const r=t.split(".").map(Number);return r.length!==4||r.some((n,i)=>!/^\d+$/.test(t.split(".")[i])||n<0||n>255)?!1:r[0]===127||r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}function $d(e){return Object.keys(e.headers).some(Kd)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Kd(t)))}:e}function Kd(e){const t=e.trim().toLowerCase();return uN.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function ON(e){return e instanceof Error&&e.name==="AbortError"}function MN(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Tn(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Re("INVALID_PARAMS",t);return e}function lo(e){return new TextEncoder().encode(e).length}function Re(e,t){return{code:e,message:t}}function RN(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function CN(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 LN(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topicIds 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const s=CN(i);s?r.has(s)||(r.add(s),n.push(s)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function PN(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topics 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const s=typeof i=="string"?i.trim():"";!s||s.startsWith("#")||s.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):r.has(s)||(r.add(s),n.push(s))}return{invalidMessages:t,values:n}}function Jh(e,t){if(e==null)return{};if(!RN(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=LN(e.topicIds),n=PN(e.topics),i=[...r.invalidMessages,...n.invalidMessages];let s=r.values;t.maxTopicIds!==void 0&&s.length>t.maxTopicIds&&(i.push(`${t.method} post.topicIds 最多允许 ${t.maxTopicIds} 项`),s=s.slice(0,t.maxTopicIds));const a=s.length||n.values.length?{...s.length?{topicIds:s}:{},...n.values.length?{topics:n.values}:{}}:void 0;return a||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:a}}function vN(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function kN(e){try{if(vN(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function nt(e){throw{code:"INVALID_PARAMS",message:e}}function Pi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tc(e,t){return typeof e!="string"||!e.trim()?nt(t):e}function xN(e,t){const r=tc(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?nt(t):r}catch{return nt(t)}}function UN(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function em(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return nt(`${t} 缺少有效的小程序分享地址`);try{const s=new URL(e.environment.getCurrentHref()),a=new URL("/tools/common_share",s);a.searchParams.set("user_miniprogram_id",i);const c=n?.version?.trim();c&&a.searchParams.set("miniprogram_version",c);const u=s.searchParams.get("h_src");return u?.trim()&&a.searchParams.set("h_src",u),r!==void 0&&a.searchParams.set("extra",r),a.href}catch{return nt(`${t} 缺少有效的小程序分享地址`)}}function BN(e,t){if(!Pi(e))return nt("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return nt("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!UN(r))return nt("share.showShareMenu channel 不合法");const n=tm(e.extra,"share.showShareMenu");return{title:tc(e.title,"share.showShareMenu title 必须是非空字符串"),description:tc(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:em(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:xN(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function tm(e,t){if(e!==void 0)try{return qh(e)}catch{return nt(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function rm(e,t){return e.invalidMessage&&await Se(()=>kN(t.environment),t.operationContext.signal)?nt(e.invalidMessage):e.post}function Zd(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function HN(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Zd(t.windowWidth,0),height:Zd(t.windowHeight,0)}}function rc(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?nt(t):r}function Xd(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?nt(t):r}function FN(e){return Pi(e)?{left:rc(e.left,"share.screenshot rect.left 必须是非负数字"),top:rc(e.top,"share.screenshot rect.top 必须是非负数字"),width:Xd(e.width,"share.screenshot rect.width 必须是正数"),height:Xd(e.height,"share.screenshot rect.height 必须是正数")}:nt("share.screenshot rect 必须是对象")}function Jd(e,t){if(e!=null&&!Pi(e))return nt("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?nt("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?nt("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?HN(t):FN(r.rect),...r.delay===void 0?{}:{delay:rc(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function zN(e,t){ve(t.operationContext.signal);const r=BN(e,t);let n=Jh(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await rm(n,t);return Se(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function jN(e,t){if(ve(t.operationContext.signal),e!==void 0&&!Pi(e))return nt("share.copyLink 参数必须是对象");const r=tm(e?.extra,"share.copyLink"),n=em(t,"share.copyLink",r);return await Se(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function el(e,t,r,n=!1){ve(t.operationContext.signal);const i=Jh(Pi(e)?e.post:void 0,{method:"share.screenshot"}),s=await rm(i,t),a=t.identity.get()?.miniProgramId.trim()||void 0,c=VN(),{watermarkTheme:u,...d}=r;let l=!1,h,f,_;try{if(n&&(!t.presentation.supportsLongScreenshot||!t.prepareLongScreenshot))throw{code:"REQUEST_UNSUPPORTED",message:"当前宿主不支持 DOM 长图,请更新宿主"};if(l=!0,await Se(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),n){const w=await t.prepareLongScreenshot(r.rect,t.operationContext.signal);h=w.restore,d.rect=w.rect}f=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,u),_={status:"fulfilled",value:await Se(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:s,...a?{sourceMiniProgramId:a}:{}},t.operationContext),t.operationContext.signal)}}catch(y){_={status:"rejected",error:y}}finally{try{f?.()}finally{h?.()}}const p=l?await GN(t.presentation,c,t.operationContext.signal):void 0;if(_.status==="rejected")throw _.error;if(p)throw p;return _.value}function VN(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function GN(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await Se(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function YN(e){let t=Promise.resolve();const r=async(n,i)=>{const s=Ue(e.operationContext,i.signal,i.requestId),a=Jd(n,e.presentation);(a.rect.top+a.rect.height>1e4||a.rect.left+a.rect.width>2048||a.rect.width*a.rect.height>4e6)&&nt("长图尺寸超出限制");const c=t.then(()=>el(n,{...e,operationContext:s},a,!0));return t=c.then(()=>{},()=>{}),c};return{[Os]:r,[ws]:(n,i)=>jN(n,{...e,operationContext:Ue(e.operationContext,i.signal,i.requestId)}),[Ds]:(n,i)=>zN(n,{...e,operationContext:Ue(e.operationContext,i.signal,i.requestId)}),[Ss]:async(n,i)=>{const s=Ue(e.operationContext,i.signal,i.requestId);ve(s.signal);const a=Jd(n,e.presentation),c=t.then(()=>el(n,{...e,operationContext:s},a));return t=c.then(()=>{},()=>{}),Se(()=>c,s.signal)}}}const tl=new WeakMap,qi=new Map;function nm(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return fg(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${yf(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function im(e){const t=e.coordinationKey??e.storage;let r;const n=()=>r??=Promise.resolve().then(e.resolveScope).catch(u=>{throw r=void 0,u}),i=async(u,d)=>{const l=await n();let h=tl.get(t);h||(h=new Map,tl.set(t,h));const f=h.get(l)??Promise.resolve(),_=async()=>(ve(u.signal,{preserveReason:!0}),d(l)),p=f.catch(()=>{}).then(()=>e.lock?e.lock(l,_):_());h.set(l,p);try{return await p}finally{h.get(l)===p&&h.delete(l)}},s=async(u,d,l=!1)=>{const h=Wr(u,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(p=>p.key.startsWith(h)&&p.value!=="").map(p=>p.key.slice(h.length)))];const f=await e.storage.getRaw(Ui(u),d);if((f===void 0||f==="")&&!l)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let _;try{_=f?JSON.parse(f):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(_)||_.length>Ru||_.some(p=>typeof p!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(p)))throw new Error("本地数据索引异常");return[...new Set(_)]},a=async(u,d)=>{if(e.diagnostics){const f=Wr(u,"");return(await e.diagnostics.listRaw(d)).filter(_=>_.key.startsWith(f)&&_.value!=="").map(_=>({..._,key:_.key.slice(f.length)}))}const l=[],h=await s(u,d);for(let f=0;f<h.length;f+=16){ve(d.signal,{preserveReason:!0});const _=await Promise.all(h.slice(f,f+16).map(async p=>{const y=await e.storage.getRaw(Wr(u,p),d);return y!==void 0&&y!==""?{area:"local",key:p,value:y}:void 0}));for(const p of _)p&&l.push(p)}return l},c=u=>{if(!/^[A-Za-z0-9_-]{1,128}$/.test(u))throw Object.assign(new Error("storage key 不合法"),{code:"INVALID_REQUEST"})};return{get(u,d){return c(u),i(d,l=>e.storage.getRaw(Wr(l,u),d))},set(u,d,l){return c(u),i(l,async h=>{const f=await s(h,l,!0);if(!f.includes(u)&&f.length>=Ru)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const _=[...new Set([...f,u])];await e.storage.setRaw(Ui(h),JSON.stringify(_),l)}ve(l.signal,{preserveReason:!0}),await e.storage.setRaw(Wr(h,u),d,l),ve(l.signal,{preserveReason:!0})})},list(u){return i(u,d=>a(d,u))},clear(u){return i(u,async d=>{const l=await s(d,u);e.diagnostics||await e.storage.setRaw(Ui(d),JSON.stringify(l),u);for(let h=0;h<l.length;h+=16){ve(u.signal,{preserveReason:!0});const _=(await Promise.allSettled(l.slice(h,h+16).map(p=>e.storage.setRaw(Wr(d,p),"",u)))).find(p=>p.status==="rejected");if(_)throw _.reason}ve(u.signal,{preserveReason:!0}),await e.storage.setRaw(Ui(d),"[]",u)})}}}function sm(e,t){if(typeof navigator<"u"&&navigator.locks)return new Promise((n,i)=>{navigator.locks.request(`hb-miniprogram-storage:${e}`,()=>t().then(n,i)).catch(i)});const r=(qi.get(e)??Promise.resolve()).catch(()=>{}).then(t);return qi.set(e,r),r.finally(()=>{qi.get(e)===r&&qi.delete(e)})}const qN=128,QN=/^[A-Za-z0-9_-]+$/;function WN(e){const t=e.scopedStorage??im({storage:e.storage,resolveScope:()=>nm({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[ci]:async n=>{ve(e.operationContext.signal);const i=rl(n,ci,e.storageLimits?.maxKeyLength),s=await Se(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:nl(s)}},[ui]:async n=>{ve(e.operationContext.signal);const i=am(n,"storage.setStorage 参数必须是对象"),s=rl(i,ui,e.storageLimits?.maxKeyLength),a=$N(i.data,e.storageLimits?.maxValueBytes);await Se(()=>t.set(s,a,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(ve(e.operationContext.signal),(await Se(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?Ur("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const s=i.value;return{area:i.area,key:i.key,value:nl(s),serializedValue:s,bytes:om(s)}}).sort((i,s)=>i.key.localeCompare(s.key)))}}}function rl(e,t,r=qN){const i=am(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Ur("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!QN.test(i))throw Ur("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function $N(e,t){let r;try{r=JSON.stringify(e)}catch{throw Ur("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw Ur("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&om(r)>t)throw Ur("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function nl(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function am(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Ur("INVALID_PARAMS",t);return e}function om(e){return new TextEncoder().encode(e).length}function Ur(e,t){return{code:e,message:t}}const il=120;function mr(e){throw{code:"INVALID_PARAMS",message:e}}function ru(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cm(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&mr(`${r} 不支持字段: ${n.join(", ")}`)}function KN(e){if(!ru(e))return mr("ui.showToast 参数必须是对象");if(cm(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return mr("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>il)return mr(`ui.showToast message 不能超过 ${il} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return mr("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function ZN(e){return e===void 0?{dismissible:!1}:ru(e)?(cm(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?mr("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):mr("ui.showLoading 参数必须是对象")}function XN(e){e!==void 0&&(!ru(e)||Object.keys(e).length)&&mr("ui.hideLoading 不支持参数")}function JN(e){return{[Vs]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),await Se(()=>e.presentation.showToast(KN(t),n),n.signal)},[Gs]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),await Se(()=>e.presentation.showLoading(ZN(t),n),n.signal)},[Ys]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),XN(t),await Se(()=>e.presentation.hideLoading(n),n.signal)}}}const ew={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return Ve(e,"当前用户首页资料接口响应异常")}},tw=3e4;function rw(e,t,r={}){const n=r.ttlMs??tw,i=r.requestPolicyEnabled!==!1,s=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let a=0,c,u;async function d(){let h;try{h=await Pa(e,ew,void 0,{...t,credentials:"heybox-session",...s?{gate:s}:{}})}catch(f){throw t.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):f instanceof Je?T("REQUEST_UNSUPPORTED",f.message):f instanceof Mi?T("INVALID_RESPONSE","user home_v2 响应不合法"):f instanceof pn?T("REQUEST_FAILED","user home_v2 请求失败"):f instanceof Oi?i&&(f.status===403||f.status===429)?T("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:f.status,...f.retryAfterMs===void 0?{}:{retryAfterMs:f.retryAfterMs}}):T("REQUEST_FAILED",f.message):iw(f)?f:T("REQUEST_FAILED","user home_v2 请求失败")}return nw(h,"user home_v2")}function l(h){const f=Date.now();if(c?.userId===h&&c.expiresAt>f)return Promise.resolve(c.value);if(u?.userId===h&&u.generation===a)return u.promise;const _=a,p=d().then(y=>(a===_&&(c={userId:h,value:y,expiresAt:Date.now()+n}),y)).finally(()=>{u?.promise===p&&(u=void 0)});return u={userId:h,generation:_,promise:p},p}return{get:l,clear(){a+=1,c=void 0,u=void 0}}}function nw(e,t){if(!pe(e))throw T("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw T(n,r)}if(!pe(e.result))throw T("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function iw(e){return pe(e)&&typeof e.code=="string"&&typeof e.message=="string"}const sw={auth:"optional",channel:"api",id:"heybox.bbs.app.profile.follow.user.post",method:"POST",path:"/bbs/app/profile/follow/user",bodyEncoding:"form",failurePresentation:"none",query(e){return e.query?{...e.query}:void 0},body(e){return{...e.body??{}}},parse(e,t){return Ve(e,"关注用户接口响应异常")}},aw={auth:"none",channel:"api",id:"heybox.user_miniprogram.runtime.author.follow_status.post",method:"POST",path:"/user_miniprogram/runtime/author/follow_status",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return Ve(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowStatus 接口响应异常")}},ow={auth:"none",channel:"api",id:"heybox.user_miniprogram.runtime.author.follow_guidance.begin.post",method:"POST",path:"/user_miniprogram/runtime/author/follow_guidance/begin",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return Ve(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowGuidanceBegin 接口响应异常")}},cw={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 Ve(e,"Steam 游戏库接口响应异常")}};function uw(e,t=Ho){const r=a_({version:"2",validate:lw}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):Ho,memoryMaxEntries:64,diskMaxEntries:256,diskMaxBytes:10*1024*1024,maxEntryBytes:512*1024};return{persistent:e.register({namespace:"user.steam-game-list",codec:r,policy:{...n,persistence:"memory-and-disk"}}),unresolved:e.register({namespace:"user.steam-game-list.unresolved",codec:r,policy:{...n,persistence:"memory"}})}}function sl(e,t){if(e.steamId)return e.steamId;for(const r of["steamid","steam_id","steamId"]){const n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}function dw(e){const{query:t}=e;return JSON.stringify([e.miniProgramId,e.userId,e.effectiveSteamId??null,e.personalInformationOpen??null,t.limit,t.offset,t.sort,t.q??"",t.includeHidden])}function lw(e){if(!pe(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(al(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw on();for(const t of e.gameList){if(!pe(t)||!nc(t.appid)||!nc(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw on();for(const r of["image","portraitImage","icon"])fw(t,r);for(const r of["playtimeForever","playtime2Weeks"])al(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw on()}return e}function nc(e){return typeof e=="number"&&Number.isFinite(e)}function al(e,t){if(e[t]!==void 0&&!nc(e[t]))throw on()}function fw(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw on()}function on(){return T("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const um=20,hw=100,mw=128,dm=0,lm="weeks",Ew=100,gw=new Set(["weeks","all","achieved"]);function pw(){return{nickname:"",avatar:""}}function _w(e){const t=rw(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??Ff(),i=uw(n,r?e.steamGameListTtlMs:0);let s;const a=new Map;let c=Promise.resolve();function u(j,z){const V=JSON.stringify([j,z]);return(!s||s.key!==V)&&(s={key:V,scope:n.createScope(z,n.createScope(j))}),s.scope}function d(){const j=s;s=void 0,j&&n.invalidateScope(j.scope).catch(()=>{}),a.clear()}const l=Jf({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??$f))}),h=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let f,_,p=0,y=!1;const w=e.account.onChange(()=>{p+=1,t.clear(),l.invalidate(),d()}),N=e.authorization.onEvent((j,z)=>{j==="user_info_authorization_change"&&Object.values(z).some(V=>V==="denied")&&(p+=1,t.clear(),l.invalidate(),d(),c=c.then(async()=>{if(y)return;const V=await e.account.getCurrentUserId(e.operationContext);typeof V=="string"&&V.trim()&&await n.invalidateScope(u(I(),V.trim()))}).catch(()=>{}))});function O(){if(y||e.operationContext.signal.aborted)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function I(){const j=e.identity.get()?.miniProgramId?.trim();if(!j)throw T("INVALID_STATE","用户能力缺少 canonical 小程序身份");return j}async function H(){O(),await c,O();let j;try{j=await e.account.getCurrentUserId(e.operationContext)}catch(z){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Bn(z)?z:T("REQUEST_FAILED","读取小黑盒账号失败")}return typeof j=="string"&&j.trim()?j.trim():void 0}async function Q(j,z){const V=await H();if(p!==z||V!==j)throw T("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function M(j,z,V=e.operationContext.signal){try{return await Pa(e.network,j,z,{...e.operationContext,signal:V,credentials:"heybox-session",...h?{gate:h}:{}})}catch(U){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):U instanceof Je?T("REQUEST_UNSUPPORTED",U.message):U instanceof Mi?T("INVALID_RESPONSE","用户接口响应不合法"):U instanceof pn?T("REQUEST_FAILED","用户请求失败"):U instanceof Oi?r&&(U.status===403||U.status===429)?T("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:U.status,...U.retryAfterMs===void 0?{}:{retryAfterMs:U.retryAfterMs}}):T("REQUEST_FAILED",U.message):Bn(U)?U:T("REQUEST_FAILED","用户请求失败")}}async function x(j,z){if(!e.authorizationContext)return{mini_program_id:j};let V;try{V=await Se(()=>e.authorizationContext.get({...e.operationContext,signal:z}),z)}catch(U){if(Bn(U))throw U;const k=T("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(k,"cause",{configurable:!0,value:U}),k}if(!V.token?.trim())throw T("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:j,runtime_auth_context_token:V.token}}async function v(){O();const j=I(),z=p,V=await H();if(!V){if(p!==z)throw T("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const U=await x(j,e.operationContext.signal);await Q(V,z);const k=await M(aw,U);if(await Q(V,z),I()!==j)throw T("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return ul(cl(k))}function W(j,z){if(!j)return Promise.reject(T("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(z?.aborted)return Promise.reject(T("REQUEST_CANCELLED","关注操作已取消"));if(f)return Promise.reject(T("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(T("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const V=q(z).finally(()=>{f===V&&(f=void 0)});return f=V,V}async function q(j){O();const z=I(),V=new AbortController;_=V;const U=()=>V.abort();e.operationContext.signal.addEventListener("abort",U,{once:!0}),j?.addEventListener("abort",U,{once:!0});let k=()=>{},Y=!1;try{try{await Se(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:V.signal}),V.signal)}catch(S){throw Bn(S)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(S.code)?T("FOLLOW_CANCELLED","已取消小黑盒登录"):S}O();const R=p;k=e.account.onChange(()=>{Y=!0,U()});const K=await Se(H,V.signal);if(!K)throw T("FOLLOW_CANCELLED","未完成小黑盒登录");const Z=async()=>{if(await Se(()=>Q(K,R),V.signal),O(),I()!==z)throw T("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await Z();const ee=await x(z,V.signal);await Z();const se=Sw(),fe=await Se(()=>M(ow,{...ee,request_id:se},V.signal),V.signal);await Z();const we=cl(fe);if(we.status!=="notFollowing")return ul(we);if(we.rateLimited)throw T("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const Pe=await Se(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:z,signal:V.signal}),V.signal);if(await Z(),Pe!=="confirmed")throw T("FOLLOW_CANCELLED","已取消关注作者");const E=we.authorId,m=await Se(()=>M(sw,{body:{following_id:E}},V.signal),V.signal);if(await Z(),m.status!=="ok"){const S=["login","relogin","lack_token"].includes(m.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw T(S,typeof m.msg=="string"&&m.msg.trim()?m.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(R){throw O(),Y?T("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):j?.aborted?T("REQUEST_CANCELLED","关注操作已取消"):Bn(R)?R:T("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{k(),e.operationContext.signal.removeEventListener("abort",U),j?.removeEventListener("abort",U),_===V&&(_=void 0)}}async function te(){I();const j=p,z=await H();if(!z)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[V,U]=await Promise.all([e.authorization.getOrCreateLocalIdentity(z),F(z).catch(()=>pw())]);return await Q(z,j),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:V.appUserId,profile:U,...V.steamId?{steam_id:V.steamId}:{}}}}function F(j){return l.read(j,()=>M(Xf,void 0).then(z=>{const V=ic(z,"账号基础信息");if(V.display_username!==void 0&&typeof V.display_username!="string")throw T("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(V.display_avatar!==void 0&&typeof V.display_avatar!="string")throw T("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:V.display_username??"",avatar:V.display_avatar??""}}))}async function G(j){const z=Tw(j),V=I(),U=p,k=await H();if(!k)return d(),{isLogin:!1,isBound:!1,data:null};const Y=await t.get(k);await Q(k,U);const R=fm(Y.steam_id_info);if(Object.keys(R).length===0)return await n.invalidateScope(u(V,k)).catch(()=>{}),await Q(k,U),a.delete(JSON.stringify([V,k])),{isLogin:!0,isBound:!1,data:null};const K=JSON.stringify([V,k]),Z=u(V,k),ee=sl({...z,steamId:void 0},R),se=hm(R.personal_infomation_open??R.personal_information_open),fe=JSON.stringify([ee??null,se??null]),we=a.get(K);we&&we.identity!==fe&&(await n.invalidateScope(Z).catch(()=>{}),await Q(k,U));const Pe={identity:fe,scope:n.createScope(fe,Z)};a.set(K,Pe);const E=sl(z,R),m=E?i.persistent:i.unresolved,S=n.createScope(E??"unresolved",Pe.scope),D=async()=>{if(await Q(k,U),I()!==V||a.get(K)?.identity!==fe)throw T("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},P=await m.read({scope:S,key:dw({miniProgramId:V,userId:k,effectiveSteamId:E,personalInformationOpen:se,query:z}),signal:e.operationContext.signal,load:async X=>{const ce=await M(cw,{userId:k,...z,personalInformationOpen:se},X);return await D(),Nw(ic(ce,"Steam 游戏库"),z)}}).catch(async X=>{throw await D(),X});return await D(),{isLogin:!0,isBound:!0,data:P}}return{getFollowStatus:v,requestFollowAuthor:W,getInfo:te,getSteamGameList:G,async invalidateSteamGameListCache(){const j=I(),z=p,V=await H();if(!V)return;const U=u(j,V);await Promise.all([i.persistent.invalidateScope(U),i.unresolved.invalidateScope(U)]),t.clear(),a.delete(JSON.stringify([j,V])),await Q(V,z)},dispose(){y||(y=!0,_?.abort(),p+=1,w(),N(),t.clear(),l.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function Tw(e){if(e==null)return{limit:um,offset:dm,sort:lm,includeHidden:!1};if(!pe(e))throw Er("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Er(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:Aw(e.limit),offset:Iw(e.offset),sort:bw(e.sort),includeHidden:yw(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>mw)throw Er("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Er("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,Ew))}return r}function Aw(e){if(e===void 0)return um;if(!Number.isInteger(e)||Number(e)<1)throw Er("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),hw)}function Iw(e){if(e===void 0)return dm;if(!Number.isInteger(e)||Number(e)<0)throw Er("user.getSteamGameList offset 必须是非负整数");return Number(e)}function bw(e){if(e===void 0)return lm;if(typeof e!="string"||!gw.has(e))throw Er("user.getSteamGameList sort 不支持");return e}function yw(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Er("user.getSteamGameList includeHidden 必须是 boolean");return e}function Nw(e,t){if(!Array.isArray(e.game_list))throw T("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(ww).filter(c=>c!==void 0),n=la(e.total),i=t.offset+r.length,s={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(s.total=n,s.hasMore=i<n);const a=hm(e.is_me);return a!==void 0&&(s.isMe=a),s}function ww(e){const t=fm(e),r=la(t.appid),n=la(t.steam_appid)??r,i=nu(t.name);if(r===void 0||n===void 0||!i)return;const s={appid:r,steamAppid:n,name:i};fo(s,"image",t.image),typeof t.vertical_head_image=="string"&&fo(s,"portraitImage",t.vertical_head_image),fo(s,"icon",t.appicon??t.icon),ol(s,"playtimeForever",t.playtime_forever),ol(s,"playtime2Weeks",t.playtime_2weeks);const a=Dw(t.external_tags??t.tags);return a.length&&(s.tags=a),s}function ic(e,t){if(!pe(e))throw T("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw T(n,r)}if(!pe(e.result))throw T("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function fm(e){return pe(e)?e:{}}function nu(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Dw(e){return Array.isArray(e)?e.map(nu).filter(Boolean):[]}function la(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function hm(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function fo(e,t,r){const n=nu(r);n&&Object.assign(e,{[t]:n})}function ol(e,t,r){const n=la(r);n!==void 0&&Object.assign(e,{[t]:n})}function Er(e){return T("INVALID_PARAMS",e)}function Bn(e){return pe(e)&&typeof e.code=="string"&&typeof e.message=="string"}function cl(e){const t=ic(e,"关注状态");if(![0,1,2].includes(t.follow_status)||typeof t.author_id!="string"||!/^[1-9]\d*$/.test(t.author_id)||typeof t.rate_limited!="boolean")throw T("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function ul(e){return e.status}function Sw(){const e=globalThis.crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Ow(e){return{[As]:async t=>(Qi(t,"user.getFollowStatus"),e.user.getFollowStatus()),[Is]:async(t,r)=>(Qi(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[bs]:async t=>(Qi(t,"user.getInfo"),e.user.getInfo()),[ys]:async(t,r)=>{Qi(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Ns]:async t=>e.user.getSteamGameList(t)}}function Qi(e,t){if(e!==void 0)throw T("INVALID_PARAMS",`${t} 不接收入参`)}function Mw(){return T("USER_DATA_PERMISSION_STATE_INVALID","本地用户数据许可状态异常,已停止访问")}function dl(e){return T("USER_DATA_PERMISSION_SAVE_FAILED","本次运行已停止访问,设置未保存,请重试",e===void 0?void 0:{reason:e instanceof Error?e.message:String(e)})}function Rw(e){const t=e.managedResources??Rr,r=typeof e.storage.withLock=="function"||typeof navigator<"u"&&!!navigator.locks,n=e.hash??Bc,i=new Map,s=new Set;let a=!1;function c(){if(a)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function u(I,H){if(e.storage.withLock)return e.storage.withLock(l(I),H);if(typeof navigator<"u"&&navigator.locks)return sm(l(I),H);throw T("REQUEST_UNSUPPORTED","当前宿主不支持跨实例保存资料许可")}function d(I){return Ag({miniProgramId:e.resolveMiniProgramId(),userId:I,environment:e.resolveEnvironment()})}function l(I){return mg(Tg(d(I)))}function h(I,H){return e.purposeOf?n(of(I,e.revisionOf(I),H,e.purposeOf(I))):n(`${I}\0${e.revisionOf(I)}\0${H}`)}function f(I,H){return`${I}\0${H}`}async function _(I,H){let Q;try{Q=await e.storage.getRaw(l(I),H)}catch(x){throw c(),H.signal.aborted?T("REQUEST_CANCELLED","许可操作已取消"):T("USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","无法读取本地用户数据许可",{reason:x instanceof Error?x.message:String(x)})}if(c(),H.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");const M=Q===void 0||Q===""?void 0:_g(Q);if(Q!==void 0&&Q!==""&&M===void 0)throw Mw();return M??{schema_version:1,records:{}}}async function p(I,H,Q){if(c(),Q.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");await e.storage.setRaw(l(I),JSON.stringify(H),Q)}function y(I){return I?.revision??0}function w(I,H,Q){const M=new Set(Q.declared??[]),x=new Set(t);for(const q of Object.keys(H.records))dr(q)&&x.add(q);for(const q of i.keys())q.startsWith(`${I}\0`)&&x.add(q.slice(I.length+1));const W=[...x].sort((q,te)=>{const F=Rr.indexOf(q),G=Rr.indexOf(te);return(F<0?Number.MAX_SAFE_INTEGER:F)-(G<0?Number.MAX_SAFE_INTEGER:G)}).map(q=>{const te=H.records[q],F=y(te),G=Q.egressTier===void 0?void 0:h(q,Q.egressTier),j=i.get(f(I,q)),z=j!==void 0&&j.revision===F&&(G===void 0||j.consentFingerprint===G);return{resource:q,name:kc(q)?.name??q,purposeText:e.purposeOf?.(q)??"",scopeFingerprint:G??"",declared:M.has(q),available:M.has(q),decision:te?.decision??"ask",revision:F,...te?.decision==="allow"&&te.consentFingerprint?{consentFingerprint:te.consentFingerprint}:{},sessionAllowed:z,allowed:!s.has(f(I,q))&&M.has(q)&&te?.decision!=="deny"&&(z||r&&te?.decision==="allow"&&G!==void 0&&te.consentFingerprint===G)}});return Object.freeze({schema_version:1,canPersist:r,resources:Object.freeze(W),...Q.egressTier===void 0?{}:{egressTier:Q.egressTier}})}function N(I,H,Q,M){const x=H.records[Q],v=f(I,Q);if(s.has(v))return{status:"denied",reason:"tightening"};if(x?.decision==="deny")return{status:"denied",reason:"deny"};const W=h(Q,M);if(r&&x?.decision==="allow"&&x.consentFingerprint===W)return{status:"allowed",source:"persistent"};const q=i.get(v);return q&&q.revision===y(x)&&q.consentFingerprint===W?{status:"allowed",source:"session"}:{status:"ask"}}function O(I){if(typeof I!="string"||!Rr.includes(I))throw T("INVALID_PARAMS","用户数据资源标识不合法")}return{canPersist:r,async read(I,H,Q={}){c();const M=await _(I,H);return w(I,M,Q)},async evaluate(I,H,Q){c(),O(H.resource);const M=await _(I,Q);return N(I,M,H.resource,H.egressTier)},async decide(I,H){c(),O(I.resource);const Q=async()=>{c();const M=await _(I.userId,H);if(c(),H.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");const x=M.records[I.resource],v=y(x);if(I.expectedRevision!==void 0&&v!==I.expectedRevision)throw T("AUTHORIZATION_CONTEXT_CHANGED","资料许可已变化,请重新确认");const W=f(I.userId,I.resource),q=h(I.resource,I.egressTier);if(I.expectedFingerprint!==void 0&&I.expectedFingerprint!==q)throw T("AUTHORIZATION_CONTEXT_CHANGED","资料披露范围已变化,请重新确认");if(I.scope==="session"){if(I.decision!=="allow")throw T("INVALID_PARAMS","本次许可只支持允许");return i.set(W,Object.freeze({revision:v,consentFingerprint:q})),w(I.userId,M,{egressTier:I.egressTier})}const te=v+1,F=I.decision==="allow"?{decision:"allow",revision:te,consentFingerprint:q}:{decision:I.decision,revision:te},G={schema_version:1,records:{...M.records,[I.resource]:F}};I.decision!=="allow"&&(s.add(W),i.delete(W));try{await p(I.userId,G,H)}catch(j){throw dl(j)}return s.delete(W),i.delete(W),w(I.userId,G,{egressTier:I.egressTier})};return I.scope==="session"?Q():u(I.userId,Q)},async revokeSession(I,H){c(),I.resource!==void 0&&O(I.resource);for(const M of[...i.keys()])M.startsWith(`${I.userId}\0`)&&(I.resource===void 0||M===f(I.userId,I.resource))&&i.delete(M);const Q=await _(I.userId,H);return w(I.userId,Q,{})},async reset(I,H){return c(),u(I.userId,async()=>{c();const Q=await _(I.userId,H);if(c(),H.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");const M=new Set(t);for(const W of Object.keys(Q.records))M.add(W);for(const W of i.keys())W.startsWith(`${I.userId}\0`)&&M.add(W.slice(I.userId.length+1));for(const W of M)s.add(f(I.userId,W));for(const W of[...i.keys()])W.startsWith(`${I.userId}\0`)&&i.delete(W);const x={...Q.records};for(const W of M)x[W]={decision:"ask",revision:(x[W]?.revision??0)+1};const v={schema_version:1,records:x};try{await p(I.userId,v,H)}catch(W){throw dl(W)}for(const W of M)s.delete(f(I.userId,W));return w(I.userId,v,{})})},dispose(){a||(a=!0,i.clear(),s.clear())}}}const za={auth:"none",channel:"api",method:"POST",bodyEncoding:"form",failurePresentation:"none",parse(e){return Ve(e,"游戏资料接口响应异常")}};function ja(e){return{runtime_auth_context_token:e.runtime_auth_context_token,resource:e.resource,disclosure_revision:e.disclosure_revision}}const Cw={...za,id:"heybox.user_miniprogram.runtime.user_game_data.query.post",path:"/user_miniprogram/runtime/user_game_data/query",body(e){return{...ja(e),operation:e.operation,schema_version:e.schema_version,...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit}}}},Lw={...za,id:"heybox.user_miniprogram.runtime.user_game_data.sync.post",path:"/user_miniprogram/runtime/user_game_data/sync",body:ja},ll={...za,id:"heybox.user_miniprogram.runtime.user_game_data.sync_status.post",path:"/user_miniprogram/runtime/user_game_data/sync_status",body(e){return{...ja(e),task_id:e.task_id}}},Pw={...za,id:"heybox.user_miniprogram.runtime.user_game_data.file.post",path:"/user_miniprogram/runtime/user_game_data/file",body(e){return{...ja(e),save_id:e.save_id,file_id:e.file_id}}};function vw(e){const t=ah(e.storage),r=e.fileDownloads??(e.files&&e.transfer?qc({files:e.files,transfer:e.transfer,registry:e.registry,signal:e.signal}):void 0),n=new Set,i=d=>{if(e.signal.aborted||d.signal.aborted)throw oe("REQUEST_CANCELLED","资料请求已取消")};async function s(d,l){if(i(l),!e.authorizationContext)throw oe("REQUEST_UNSUPPORTED","宿主缺少受信运行上下文");const h=await e.authorizationContext.get(l);if(!h.token||!Number.isFinite(h.expiresAt)||h.expiresAt<=Date.now())throw oe("UNAUTHORIZED","受信运行上下文已过期");return{runtime_auth_context_token:h.token,resource:d.key,disclosure_revision:d.disclosureRevision}}async function a(d,l,h){i(h);const f=await Ri({network:e.network,operationContext:h,subject:"游戏资料",assertUsable:()=>i(h),requestPolicyEnabled:e.requestPolicyEnabled,...e.requestGate?{gate:{capability:"userGameData",gate:e.requestGate}}:{}},d,l),_=at(f,"user.data","游戏资料");if(!Le(_))throw oe("INVALID_RESPONSE","游戏资料响应无效");return i(h),_}const c=d=>{const l=kc(d);if(!l)throw oe("REQUEST_UNSUPPORTED","未开放资料资源");return l};async function u(d){n.delete(d),await r?.release(d)}return{releaseFile:u,invalidate(){for(const d of n)r?.release(d);n.clear()},async query(d,l){const h=c(d.resource),f=h.queries[d.operation];if(!f)throw oe("REQUEST_UNSUPPORTED","未开放资料操作");const _=await a(Cw,{...await s(h,l),operation:d.operation,schema_version:f.version,...d.cursor===void 0?{}:{cursor:d.cursor},...d.limit===void 0?{}:{limit:d.limit}},l);if(_.resource!==d.resource||_.operation!==d.operation||_.schema_version!==f.version||_.disclosure_revision!==h.disclosureRevision)throw oe("INVALID_RESPONSE","游戏资料合同不匹配");if(_.status==="ready"){if(!dg(f.schema,_.data))throw oe("INVALID_RESPONSE","游戏资料正文不匹配公开 schema");return{status:"ready",data:_.data,meta:{},schemaVersion:f.version}}if(_.status==="empty"&&(_.reason==="no_data"||_.reason==="not_ready")&&typeof _.message=="string")return{status:"empty",reason:_.reason,message:_.message,meta:{},schemaVersion:f.version};throw oe("INVALID_RESPONSE","游戏资料状态无效")},async sync(d,l,h){const f=c(d.resource);if(f.game===null||!f.operations.includes("sync"))throw oe("REQUEST_UNSUPPORTED","资源不支持同步");const _=await s(f,l),p=new AbortController,y=()=>p.abort();l.signal.addEventListener("abort",y,{once:!0}),l.signal.aborted&&y();let w=!1;const N=setTimeout(()=>{w=!0,y()},5*6e4),O={...l,signal:p.signal},I={...h,gameId:f.game,resource:d.resource};let H;try{const Q=await t.run(I,O,async()=>{const x=await t.get(I,O);if(x)return H=x,{id:x,status:await a(ll,{...await s(f,O),task_id:x},O)};const v=await a(Lw,_,O);if(typeof v.task_id!="string"||!v.task_id||v.task_id.length>128)throw oe("INVALID_RESPONSE","同步任务缺失");return await t.set(I,v.task_id,O),{id:v.task_id,status:v}});let M=Q.status;for(H=Q.id;;){if(i(O),M.state==="succeeded")return await t.remove(I,H,O),{status:"succeeded"};if(M.state==="failed")throw await t.remove(I,H,O),oe(typeof M.error_code=="string"?M.error_code:"SYNC_FAILED","存档同步失败");if(M.state!=="syncing"&&M.state!=="uploading")throw oe("INVALID_RESPONSE","同步状态无效");if(await kw(O.signal),M=await a(ll,{...await s(f,O),task_id:H},O),M.task_id!==H)throw oe("INVALID_RESPONSE","同步任务不匹配")}}catch(Q){throw H&&Le(Q)&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED"].includes(String(Q.code))&&await t.remove(I,H,O),w?oe("REQUEST_TIMEOUT","等待同步超时,后台任务可能仍在执行"):Q}finally{clearTimeout(N),l.signal.removeEventListener("abort",y)}},async file(d,l,h){const f=c(d.resource);if(!f.operations.includes("file")||!r)throw oe("REQUEST_UNSUPPORTED","宿主不支持资料文件下载");const _=async y=>{await h(y);const w=await a(Pw,{...await s(f,y),save_id:d.saveId,file_id:d.fileId},y);if(!Le(w.file)||w.file.file_id!==d.fileId)throw oe("INVALID_RESPONSE","文件标识不匹配");return await h(y),w},p=await r.download(await _(l),async y=>{await _(y)},l);try{return i(l),await h(l),i(l),n.add(p),p}catch(y){throw await u(p),y}}}}function kw(e){return new Promise((t,r)=>{const n=()=>{clearTimeout(i),e.removeEventListener("abort",n),r(oe("REQUEST_CANCELLED","已停止等待同步"))},i=setTimeout(()=>{e.removeEventListener("abort",n),t()},2e3);e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})}const Hn=["event_id","miniProgramId","environment","host_platform","host_version","sdk_version","runtime_version","egress_tier","resource","call_id","flow_id"],xw=Object.freeze({user_game_data_permission_show:new Set([...Hn,"entry","reason"]),user_game_data_permission_result:new Set([...Hn,"choice","apply_result"]),user_game_data_permission_manage:new Set([...Hn,"operation","apply_result","succeeded_count","failed_count"]),user_game_data_action:new Set([...Hn,"stage","action_type","outcome","duration_ms"]),user_game_data_access_result:new Set([...Hn,"api","trigger","status","error_code","failure_stage","duration_ms","cache_hit","sample_rate","overview_status_counts"])}),fl=10*6e4,Uw=256;function Bw(e){const t=e.now??Date.now,r=e.random??Math.random,n=e.createId??jw,i=Fw(e.sampleRate),s=new Map,a=new Map,c=new Map;let u=!1,d=0,l=0,h=0,f=0;const _={get emitted(){return d},get failed(){return l},get skipped(){return h},get deduplicated(){return f}};function p(M){return`${M}${n()}`}function y(){const M=t();for(const[x,v]of s)M-v.createdAt<=fl||(s.delete(x),a.get(v.key)===x&&a.delete(v.key));for(const[x,v]of c){if(M-v<=fl&&c.size<=Uw)break;c.delete(x)}}function w(M){const x=s.get(M);x!==void 0&&(s.delete(M),a.get(x.key)===M&&a.delete(x.key))}function N(M){w(M),c.delete(M),c.set(M,t())}function O(M,x){const v=xw[M],W={};for(const[q,te]of Object.entries(x))te===void 0||!v.has(q)||(W[q]=te);return Object.freeze(W)}function I(M){const x={event_id:p("evt_"),miniProgramId:rn(()=>e.resolveMiniProgramId())??"unknown",environment:Hw(rn(()=>e.resolveEnvironment())),host_platform:rn(e.resolveHostPlatform)??"unknown",host_version:rn(e.resolveHostVersion)??"unknown",sdk_version:rn(e.resolveSdkVersion)??"unknown",runtime_version:rn(e.resolveRuntimeVersion)??"unknown",egress_tier:zw(e)};return M.resource!==void 0&&(x.resource=M.resource),M.callId!==void 0&&(x.call_id=M.callId),M.flowId!==void 0&&(x.flow_id=M.flowId),x}function H(M,x){if(u){h+=1;return}try{if(e.sink===void 0){h+=1;return}e.sink.postEvent(M,O(M,x)),d+=1}catch{l+=1}}function Q(M,x){if(M===void 0)return!1;const v=s.get(M);return v===void 0?!1:x==="start"&&v.started||x==="shown"&&v.shown||x==="decided"&&v.decided?!0:(x==="start"&&(v.started=!0),x==="shown"&&(v.shown=!0),x==="decided"&&(v.decided=!0),!1)}return{diagnostics:_,createCallId(){return p("call_")},beginFlow(M){y();const x=`${M.resource??""}\0${M.actionType}`,v=a.get(x);if(v!==void 0&&s.has(v))return v;const W=p("flow_");return s.set(W,{key:x,createdAt:t(),started:!1,shown:!1,decided:!1}),a.set(x,W),W},permissionShow(M){if(Q(M.flowId,"shown")){f+=1;return}H("user_game_data_permission_show",{...I(M),entry:M.entry,reason:M.reason})},permissionResult(M){if(Q(M.flowId,"decided")){f+=1;return}H("user_game_data_permission_result",{...I(M),choice:M.choice,apply_result:M.applyResult})},permissionManage(M){H("user_game_data_permission_manage",{...I(M),operation:M.operation,apply_result:M.applyResult,...M.succeededCount===void 0?{}:{succeeded_count:M.succeededCount},...M.failedCount===void 0?{}:{failed_count:M.failedCount}})},action(M){if(M.stage==="start"&&Q(M.flowId,"start")){f+=1;return}if(M.stage==="finish"){if(M.flowId!==void 0&&c.has(M.flowId)){f+=1;return}M.flowId!==void 0&&N(M.flowId)}H("user_game_data_action",{...I(M),stage:M.stage,action_type:M.actionType,...M.outcome===void 0?{}:{outcome:M.outcome},...M.durationMs===void 0?{}:{duration_ms:Math.max(0,Math.round(M.durationMs))}})},access(M){if(i<=0){h+=1;return}if(i<1&&r()>=i){h+=1;return}H("user_game_data_access_result",{...I(M),api:M.api,trigger:M.trigger,status:M.status,duration_ms:Math.max(0,Math.round(M.durationMs)),sample_rate:i,...M.errorCode===void 0?{}:{error_code:M.errorCode},...M.failureStage===void 0?{}:{failure_stage:M.failureStage},...M.cacheHit===void 0?{}:{cache_hit:M.cacheHit},...M.overviewStatusCounts===void 0?{}:{overview_status_counts:M.overviewStatusCounts}})},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear())}}}function Hw(e){switch(e){case"public":case"production":return"production";case"preview":return"preview";case"development":case"dev":case"local":return"development";case"mock":return"mock";default:return"unknown"}}function Fw(e){return e===void 0||!Number.isFinite(e)?1:e<=0?0:e>=1?1:e}function rn(e){if(e!==void 0)try{const t=e();if(typeof t!="string")return;const r=t.trim();return r===""?void 0:r}catch{return}}function zw(e){try{return e.resolveEgressTier()==="upload"?"upload":"no_network"}catch{return"no_network"}}function jw(){const e=globalThis.crypto;if(typeof e?.randomUUID=="function")return e.randomUUID();const t=new Uint8Array(16);if(typeof globalThis.crypto?.getRandomValues=="function")globalThis.crypto.getRandomValues(t);else for(let r=0;r<t.length;r+=1)t[r]=Math.floor(Math.random()*256);return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function jt(e){const t=ft(e);return t.valid?t.permissions.network?.status==="enabled"||t.permissions.companion?.status==="enabled"?"upload":"no_network":"upload"}function Vw(e){let t=!1;const r=e.verifiedSdkVersion!==void 0&&(La(e.verifiedSdkVersion,"0.10.0-alpha.1")??-1)>=0,n=new Set;let i,s=0,a,c=!1;const u=new Map,d=new Map,l=new Set,h=new Map,f=e.now??Date.now,_=m=>H()[m]?.purpose??"",p=m=>{const S=kc(m);if(!S)throw T("REQUEST_UNSUPPORTED","未开放的资料资源");return S},y=m=>of(m,p(m).disclosureRevision,jt(e.runtimePermissions),_(m)),w=()=>Rw({storage:e.storage,resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,revisionOf:m=>p(m).disclosureRevision,purposeOf:_,...e.hash?{hash:e.hash}:{}});let N=w();const O=Bw({resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,resolveEgressTier:()=>jt(e.runtimePermissions),...e.telemetry??{}}),I=vw({network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,storage:e.storage,registry:e.fileRegistry,fileDownloads:e.fileDownloads,requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled,signal:e.operationContext.signal});function H(){const m=ft(e.runtimePermissions),S=m.valid?m.permissions.user_game_data:void 0;return S?.status==="enabled"?pi(S.config.resources):{}}function Q(m){if(t||e.operationContext.signal.aborted)throw T("RUNTIME_DESTROYED","小程序已关闭");if(m?.signal.aborted)throw T("REQUEST_CANCELLED","资料请求已取消")}function M(m){for(const[S,D]of u)D!==void 0&&(m===void 0||D===m)&&S.abort()}function x(m){for(const[S,D]of d)(m===void 0||S===m)&&(D.abort(),d.delete(S))}function v(){s++,x();for(const m of u.keys())m.abort();for(const m of l)e.fileRegistry.revokeFiles([m]);l.clear(),h.clear(),I.invalidate()}const W=Ci(e.account,m=>{if(c&&a===m)return;const S=a;c=!0,a=m,S!==void 0&&(v(),N.dispose(),N=w())}),q=()=>v();e.operationContext.signal.addEventListener("abort",q,{once:!0});async function te(m,S){Q(m);const D=new AbortController,P=()=>D.abort();u.set(D,void 0),m.signal.addEventListener("abort",P,{once:!0}),m.signal.aborted&&P();const X={...e.operationContext,...m,signal:D.signal};try{const ce=await S(X);return Q(X),ce}catch(ce){throw pe(ce)&&ce.name==="AbortError"?T("REQUEST_CANCELLED","资料操作已取消"):ce}finally{m.signal.removeEventListener("abort",P),u.delete(D)}}function F(m){const S=p(m);if(!_(S.key))throw T("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明这项游戏资料",{resource:S.key});return S}async function G(m){Q(m);const S=await e.account.getCurrentUserId(m);if(Q(m),!c)c=!0,a=S;else if(a!==S){const D=a;a=S,D!==void 0&&(v(),N.dispose(),N=w(),Q(m))}return S}function j(m,S){const D={login_required:"请先登录小黑盒",permission_required:"尚未允许读取这项资料",permission_denied:"已拒绝读取这项资料",source_not_linked:"请先在小黑盒关联对应游戏账号",source_login_required:"请先在小黑盒更新游戏来源登录"},P=S==="login_required"?{type:"user_login",label:"登录并授权"}:S==="permission_required"?{type:"permission",label:"允许读取"}:S==="permission_denied"&&e.presentation?.openDataPermissions?{type:"manage",label:"管理数据权限"}:void 0;return{status:"blocked",resource:m,reason:S,message:D[S],...P?{interaction:P}:{}}}async function z(m,S){F(m);const D=await G(S);if(!D)return j(m,"login_required");const P=await N.evaluate(D,{resource:m,egressTier:jt(e.runtimePermissions)},S);return Q(S),P.status==="allowed"?{userId:D}:j(m,P.status==="denied"?"permission_denied":"permission_required")}async function V(m,S,D,P,X){if(Q(X),s!==D||await G(X)!==S||y(m)!==P)throw T("AUTHORIZATION_CONTEXT_CHANGED","账号或资料范围已变化");return z(m,X)}function U(m,S){if(!pe(m)||typeof m.resource!="string")throw T("INVALID_PARAMS","资料请求无效");if(!dr(m.resource))throw T("REQUEST_UNSUPPORTED","当前宿主尚未开放该资料资源");const D=S==="query"?["resource","operation","schemaVersion","cursor","limit"]:["resource","saveId","fileId"];if(Object.keys(m).some(X=>!D.includes(X)))throw T("INVALID_PARAMS","资料请求包含未知参数");const P=F(m.resource);if(S==="query"){if(m.operation!=="get"&&m.operation!=="list")throw T("INVALID_PARAMS","资料查询操作无效");const X=P.queries[m.operation];if(!X)throw T("REQUEST_UNSUPPORTED","资源不支持该查询");if(m.schemaVersion!==X.version)throw T("REQUEST_UNSUPPORTED","SDK 与宿主正文合同版本不匹配");if(m.operation!=="list"&&(m.cursor!==void 0||m.limit!==void 0))throw T("INVALID_PARAMS","单份查询不能分页");if(m.cursor!==void 0&&(typeof m.cursor!="string"||!m.cursor||m.cursor.length>32768))throw T("INVALID_PARAMS","分页游标无效");if(!X.page&&(m.cursor!==void 0||m.limit!==void 0))throw T("INVALID_PARAMS","该列表不支持分页");if(m.limit!==void 0&&(typeof m.limit!="number"||!Number.isInteger(m.limit)||m.limit<1||m.limit>(X.page?.maxSize??100)))throw T("INVALID_PARAMS","分页数量无效")}else if(!P.operations.includes(S))throw T("REQUEST_UNSUPPORTED","资源不支持该操作");if(S==="file"&&(typeof m.saveId!="string"||!m.saveId||typeof m.fileId!="string"||!m.fileId))throw T("INVALID_PARAMS","资料文件标识无效");return S==="query"?{resource:m.resource,operation:m.operation,schemaVersion:m.schemaVersion,...m.cursor===void 0?{}:{cursor:m.cursor},...m.limit===void 0?{}:{limit:m.limit}}:{resource:m.resource,saveId:m.saveId,fileId:m.fileId}}async function k(m,S,D,P){const X=f(),ce=s,_e=y(S.resource);for(const ye of u.keys())ye.signal===D.signal&&u.set(ye,S.resource);try{const ye=await z(S.resource,D);if("status"in ye)return O.access({resource:S.resource,api:m,trigger:"initial",status:"blocked",durationMs:f()-X}),ye;let Ee;try{Ee=await P()}catch(De){const Fe=pe(De)?De.code:void 0;if(Fe==="USER_DATA_SOURCE_NOT_LINKED"||Fe==="USER_DATA_SOURCE_LOGIN_REQUIRED")return O.access({resource:S.resource,api:m,trigger:"initial",status:"blocked",durationMs:f()-X}),j(S.resource,Fe==="USER_DATA_SOURCE_NOT_LINKED"?"source_not_linked":"source_login_required");throw De}const Ce=await V(S.resource,ye.userId,ce,_e,D);return"status"in Ce?(O.access({resource:S.resource,api:m,trigger:"initial",status:"blocked",durationMs:f()-X}),Ce):(O.access({resource:S.resource,api:m,trigger:"initial",status:pe(Ee)&&Ee.status==="empty"?"empty":m===Qn?"succeeded":"ready",durationMs:f()-X}),Ee)}catch(ye){throw O.access({resource:S.resource,api:m,trigger:"initial",status:"error",durationMs:f()-X,errorCode:pe(ye)?String(ye.code):"REQUEST_FAILED"}),ye}}async function Y(m){const S=await G(m);if(!S)throw T("UNAUTHORIZED","请先登录小黑盒");const D=await N.read(S,m,{declared:Object.keys(H()),egressTier:jt(e.runtimePermissions)});return _(ar)?D:{...D,resources:D.resources.filter(({resource:P})=>P!==ar)}}async function R(m){const S=await m;return r?S:{...S,resources:S.resources.filter(({resource:D})=>D!==ar)}}async function K(m,S,D){const P=F(m),X=D!==void 0;if(X&&a!==D)return{status:"cancelled"};let ce=D??await G(S);if(!ce&&!X&&(await e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:S.signal}),ce=await G(S)),!ce)return{status:"cancelled"};let _e=await N.evaluate(ce,{resource:m,egressTier:jt(e.runtimePermissions)},S);if(_e.status==="allowed")return{status:"allowed"};if(_e.status==="denied"){if(X)return{status:"denied"};if(e.presentation?.openDataPermissions){const Ce=s,De=y(m),Fe=await e.presentation.openDataPermissions({resource:m,miniProgramName:e.miniProgramPresentation?.name,signal:S.signal});if(!("status"in await V(m,ce,Ce,De,S)))return{status:"allowed"};if(!Fe)return{status:"cancelled"}}return _e=await N.evaluate(ce,{resource:m,egressTier:jt(e.runtimePermissions)},S),{status:_e.status==="allowed"?"allowed":"denied"}}if(!e.presentation?.confirmDataPermission)throw T("REQUEST_UNSUPPORTED","当前宿主不支持资料许可弹窗");if(m!==ar)return ee(P,ce,S);const ye=i;if(ye?.userId===ce)return Se(()=>ye.result,S.signal);const Ee={userId:ce,result:ee(P,ce,S)};i=Ee;try{return await Ee.result}finally{i===Ee&&(i=void 0)}}async function Z(){if(!(!e.presentation?.confirmDataPermission||!_(ar)))try{const m=await G(e.operationContext);if(!m||n.has(m))return;await te(e.operationContext,S=>K(ar,S,m))}catch{}}async function ee(m,S,D){const P=m.key;x(P);const X=new AbortController;d.set(P,X);const ce=()=>X.abort();D.signal.addEventListener("abort",ce,{once:!0}),D.signal.aborted&&ce();const _e={...D,signal:X.signal},ye=s,Ee=y(P),Ce=N,De=O.beginFlow({resource:P,actionType:"permission"});let Fe="error";try{const He=(await Ce.read(S,_e,{egressTier:jt(e.runtimePermissions)})).resources.find(ct=>ct.resource===P);O.action({resource:P,flowId:De,stage:"start",actionType:"permission"}),O.permissionShow({resource:P,flowId:De,entry:"other",reason:He?.decision==="allow"?"scope_changed":"first"});const ze=await Se(()=>e.presentation.confirmDataPermission({miniProgramName:e.miniProgramPresentation?.name,resource:P,scopeText:`此黑盒账号关联的${m.name}${m.operations.includes("sync")?`。${eE}`:""}`,purposeText:_(P),egress:jt(e.runtimePermissions),canPersist:Ce.canPersist,...P===ar&&{onShown:()=>{!X.signal.aborted&&s===ye&&n.add(S)}},signal:X.signal}),X.signal);if(Q(_e),s!==ye||await G(_e)!==S||y(P)!==Ee)throw T("AUTHORIZATION_CONTEXT_CHANGED","资料许可范围已变化");return ze.decision==="cancelled"?(Fe="cancelled",O.permissionResult({resource:P,flowId:De,choice:"cancel",applyResult:"cancelled"}),{status:"cancelled"}):(await Ce.decide({userId:S,resource:P,decision:ze.decision==="deny"?"deny":"allow",scope:ze.decision==="session"?"session":"persistent",egressTier:jt(e.runtimePermissions),expectedRevision:He?.revision??0,expectedFingerprint:He?.scopeFingerprint},_e),ze.decision==="deny"&&M(P),Fe=ze.decision==="deny"?"unresolved":"resolved",O.permissionResult({resource:P,flowId:De,choice:ze.decision,applyResult:"applied"}),{status:ze.decision==="deny"?"denied":"allowed"})}catch($e){throw Fe=_e.signal.aborted?"cancelled":"error",O.permissionResult({resource:P,flowId:De,choice:"cancel",applyResult:_e.signal.aborted?"cancelled":"error"}),$e}finally{O.action({resource:P,flowId:De,stage:"finish",actionType:"permission",outcome:Fe}),D.signal.removeEventListener("abort",ce),d.get(P)===X&&d.delete(P)}}async function se(m,S,D,P,X,ce){S==="allow"?F(m):p(m);const _e=await G(P);if(!_e)throw T("UNAUTHORIZED","请先登录小黑盒");try{await N.decide({userId:_e,resource:m,decision:S,scope:D,expectedRevision:X,expectedFingerprint:ce,egressTier:jt(e.runtimePermissions)},P)}catch(ye){throw pe(ye)&&ye.code==="USER_DATA_PERMISSION_SAVE_FAILED"&&M(m),ye}return x(m),S!=="allow"&&M(m),Y(P)}async function fe(m,S,D){try{const P=await D();return O.permissionManage({operation:m,resource:S,applyResult:"applied"}),P}catch(P){throw O.permissionManage({operation:m,resource:S,applyResult:pe(P)&&P.code==="USER_DATA_PERMISSION_SAVE_FAILED"?"save_failed":"error"}),P}}async function we(m,S){x(m),M(m);const D=await G(S);if(!D)throw T("UNAUTHORIZED","请先登录小黑盒");return fe("revoke",m,async()=>(await N.revokeSession({userId:D,resource:m},S),Y(S)))}function Pe(){let m;const S=D=>te(e.operationContext,async P=>{const X=await G(P);if(!X)throw T("UNAUTHORIZED","请先登录小黑盒");if(m&&(m.userId!==X||m.generation!==s))throw T("AUTHORIZATION_CONTEXT_CHANGED","管理页面所属账号已变化,请重新打开");return m??={userId:X,generation:s},D(P)});return{getSnapshot:()=>S(Y),setDecision:D=>S(P=>fe("modify",D.resource,()=>se(D.resource,D.decision,D.scope,P,D.expectedRevision,D.expectedFingerprint))),revokeSession:D=>S(P=>we(D?.resource,P)),resetAll:()=>S(async D=>{x(),M();const P=await G(D);return fe("reset",void 0,async()=>(await N.reset({userId:P},D),Y(D)))})}}return{handlers:{[Oc]:async(m,S)=>te(S,async D=>{if(m!==void 0&&(!pe(m)||Object.keys(m).some(ce=>ce!=="game")||m.game!==void 0&&typeof m.game!="string"))throw T("INVALID_PARAMS","概览参数无效");if(pe(m)&&typeof m.game=="string"&&!Iu(m.game))throw T("REQUEST_UNSUPPORTED","当前宿主尚未开放该游戏");const P=Object.keys(H()),X=pe(m)?m.game:void 0;return sf.filter(ce=>X===void 0||ce===X).map(ce=>({game:ce,name:nf[ce],resources:Ji.filter(_e=>_e.game===ce&&P.includes(_e.key)).map(_e=>({resource:_e.key,name:_e.name,status:"not_checked",statusText:"尚未检查"}))})).filter(ce=>ce.resources.length>0)}),[Es]:async(m,S)=>te(S,D=>{const P=U(m,"query");return k(Es,P,D,()=>I.query(P,D))}),[Qn]:async(m,S)=>te(S,async D=>{if(!pe(m)||Object.keys(m).length!==1||typeof m.game!="string"||!Iu(m.game))throw T("INVALID_PARAMS","同步需要指定已开放的游戏");const P={game:m.game};if(!Ji.some(Ee=>Ee.game===P.game&&Ee.sync))throw T("REQUEST_UNSUPPORTED","该游戏不支持存档同步");const X=Ji.filter(Ee=>Ee.game===P.game&&Ee.sync&&_(Ee.key));if(X.length===0)throw T("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明可同步的资料");let ce,_e;for(const Ee of X){const Ce=await z(Ee.key,D);if(!("status"in Ce)){ce=Ee.key;break}(!_e||_e.reason==="permission_denied")&&(_e=Ce)}if(!ce)return _e;const ye={resource:ce};return k(Qn,ye,D,async()=>{const Ee=await G(D),Ce=`${Ee}\0${ye.resource}`;let De=h.get(Ce);if(!De){const Fe=new AbortController;u.set(Fe,ye.resource);const $e={controller:Fe,waiters:0,settled:!1,promise:Promise.resolve(void 0)};$e.promise=I.sync(ye,{...e.operationContext,signal:Fe.signal},{userId:Ee,miniProgramId:e.identity.get()?.miniProgramId??""}).finally(()=>{$e.settled=!0,u.delete(Fe),h.get(Ce)===$e&&h.delete(Ce)}),$e.promise.catch(()=>{}),h.set(Ce,$e),De=$e}De.waiters++;try{return await Se(()=>De.promise,D.signal)}finally{De.waiters--,De.waiters===0&&!De.settled&&De.controller.abort()}})}),[gs]:async(m,S)=>te(S,async D=>{const P=U(m,"file"),X=await G(D),ce=s,_e=y(P.resource),ye=async Ce=>{try{const De=await V(P.resource,X,ce,_e,Ce);if("status"in De)throw T("FILE_ACCESS_REVOKED","文件授权已撤销",{reason:De.reason})}catch(De){throw pe(De)&&["AUTHORIZATION_CONTEXT_CHANGED","USER_DATA_RESOURCE_NOT_DECLARED"].includes(String(De.code))?T("FILE_ACCESS_REVOKED","文件授权已失效",{causeCode:De.code}):De}};let Ee;try{const Ce=await k(gs,P,D,async()=>(Ee=await I.file(P,D,ye),{handle:Ee}));if(pe(Ce)&&Ce.status==="blocked"){const He=String(Ce.reason);throw T(He==="source_not_linked"?"USER_DATA_SOURCE_NOT_LINKED":He==="source_login_required"?"USER_DATA_SOURCE_LOGIN_REQUIRED":He==="login_required"?"UNAUTHORIZED":"PERMISSION_DENIED",String(Ce.message),{reason:He})}const De=Ce.handle,Fe={...De,read:async He=>{await ye(He);const ze=await De.read(He);try{return await ye(He),ze}catch(ct){throw ze.fill(0),ct}},stat:async He=>{await ye(He);const ze=await De.stat(He);return await ye(He),ze}},$e=e.fileRegistry.registerFile(Fe,"download","read");return"handleId"in $e.ref&&l.add($e.ref.handleId),$e}catch(Ce){throw Ee&&await I.releaseFile(Ee),Ce}}),[Mc]:async(m,S)=>{if(!S.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","许可操作需要点击");return te(S,D=>{if(!pe(m)||Object.keys(m).length!==1||typeof m.resource!="string"||!dr(m.resource))throw T("INVALID_PARAMS","许可资源无效");return K(m.resource,D)})},[Rc]:async(m,S)=>te(S,D=>R(Y(D))),[Cc]:async(m,S)=>{if(!S.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","修改许可需要点击");if(!pe(m)||typeof m.resource!="string"||!dr(m.resource)||m.decision!=="deny"||m.scope!=="persistent"||Object.keys(m).some(D=>!["resource","decision","scope"].includes(D)))throw T("INVALID_PARAMS","允许许可只能由可信弹窗确认");return te(S,D=>R(se(m.resource,m.decision,"persistent",D)))},[Lc]:async(m,S)=>{if(!S.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","管理资料许可需要点击");if(!e.presentation?.openDataPermissions)throw T("REQUEST_UNSUPPORTED","宿主未提供资料管理界面");if(m!==void 0&&(!pe(m)||Object.keys(m).some(D=>D!=="resource")||m.resource!==void 0&&(typeof m.resource!="string"||!dr(m.resource))))throw T("INVALID_PARAMS","管理资源无效");return te(S,async D=>(await e.presentation.openDataPermissions({resource:pe(m)?m.resource:void 0,miniProgramName:e.miniProgramPresentation?.name,signal:D.signal}),R(Y(D))))},[Pc]:async(m,S)=>{if(!S.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","撤销许可需要点击");if(m!==void 0&&(!pe(m)||Object.keys(m).some(D=>D!=="resource")||m.resource!==void 0&&(typeof m.resource!="string"||!dr(m.resource))))throw T("INVALID_PARAMS","撤销资源无效");return te(S,D=>R(we(pe(m)?m.resource:void 0,D)))}},promptPcHardwareOnEntry:Z,get permissionBridge(){return Pe()},diagnostics:{telemetry:O.diagnostics},dispose(){t||(t=!0,v(),W(),e.operationContext.signal.removeEventListener("abort",q),N.dispose(),O.dispose())}}}function hl(e){throw{code:"INVALID_PARAMS",message:e}}function Fn(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function mm(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Wi(e,t,r){return Math.min(mm(e,t),r)}async function Gw(e){try{return mm(await e.getNavigationBarHeight(),0)}catch{return 0}}function Yw(e,t,r,n){const i=Wi(e.safeArea?.left,0,t),s=Math.max(i,Wi(e.safeArea?.right,t,t)),a=Wi(e.safeArea?.top,n,r),c=Math.max(a,Wi(e.safeArea?.bottom,r,r));return{left:i,right:s,top:a,bottom:c,width:s-i,height:c-a}}async function ml(e){const t=e.getViewportMetrics(),r=Fn(t.windowWidth,0),n=Fn(t.windowHeight,0),i=await Gw(e);return{pixelRatio:Fn(t.pixelRatio,1),screenWidth:Fn(t.screenWidth,r),screenHeight:Fn(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:Yw(t,r,n,i),screenTop:i}}function qw(e){const t=new AbortController,r={...e,operationContext:{...e.operationContext,signal:t.signal}};let n=!1,i=0,s,a;const c=()=>{if(n||r.operationContext.signal.aborted||!r.onViewportChange)return;const h=++i;ml(r.presentation).then(f=>{if(n||r.operationContext.signal.aborted||h!==i)return;const _=JSON.stringify(f);_!==s&&(s=_,r.onViewportChange?.(f))}).catch(()=>{})},u=rN({...r,onApplied:c}),d=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),u.dispose(),a?.())};return e.operationContext.signal.aborted?d():(a=r.presentation.onViewportChange?.(c),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[Br]:async(h,f)=>u.apply(h,f?.signal),[Ms]:async()=>(ve(r.operationContext.signal),ml(r.presentation)),[Rs]:async h=>{if(ve(r.operationContext.signal),typeof h!="object"||h===null||Array.isArray(h))return hl("viewport.setNavigationBarStyle 参数必须是对象");const f=h.foregroundStyle;if(f!=="light"&&f!=="dark")return hl("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await Se(()=>r.presentation.setNavigationBarStyle(f,e.operationContext),r.operationContext.signal)}},runDisplayRequest:u.runDisplayRequest,applyOrientation:(h,f)=>u.apply({orientation:h.mode,fullscreen:h.hideCapsule},f),notifyChange:()=>{s=void 0,c()},dispose:d}}function Qw(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw ke("INVALID_PARAMS","工作区卡片刷新参数必须是对象");const t=e;if(Object.keys(t).some(i=>i!=="gameAppId"&&i!=="cardIds"))throw ke("INVALID_PARAMS","工作区卡片刷新包含未知参数");const{gameAppId:r,cardIds:n}=t;if(r!==void 0&&(typeof r!="string"||!/^[1-9][0-9]{0,9}$/.test(r)||Number(r)>2147483647))throw ke("INVALID_PARAMS","工作区卡片游戏编号无效");if(n!==void 0&&(!Array.isArray(n)||n.length>3||n.some(i=>typeof i!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(i))||new Set(n).size!==n.length))throw ke("INVALID_PARAMS","工作区卡片编号无效");return{...r===void 0?{}:{gameAppId:r},...n===void 0?{}:{cardIds:[...n]}}}function Ww(e,t){return{[ps]:async(r,n)=>{const i=Ue(t,n.signal,n.requestId);if(ve(i.signal),!e)throw ke("CAPABILITY_UNAVAILABLE","当前 Host 不支持工作区卡片");const s=Qw(r),a=await Se(()=>e.requestRefresh(s,i),i.signal);if(!a||typeof a!="object"||Array.isArray(a)||Object.keys(a).some(c=>c!=="scheduled")||!Number.isSafeInteger(a.scheduled)||a.scheduled<0)throw ke("HOST_INVALID_RESPONSE","工作区卡片刷新回执无效");return{scheduled:a.scheduled}}}}const $w=new Map(pr.map(e=>[e.method,e]));function ho(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function Kw(e){const t=Rf(e);return r=>t(r.requirement,r.method)}function Zw(e,t,r,n){let i;try{i=Promise.resolve(e(t,r))}catch(s){return n.aborted?Promise.resolve({status:"dropped"}):Promise.reject(s)}return n.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((s,a)=>{let c=!1;const u=l=>{c||(c=!0,n.removeEventListener("abort",d),l())},d=()=>u(()=>s({status:"dropped"}));n.addEventListener("abort",d,{once:!0}),i.then(l=>u(()=>s({status:"handled",value:l})),l=>u(()=>a(l)))})}function Xw(e){const t=Kw(e.runtimePermissions),r=ft(e.runtimePermissions);let n=0;return{async dispatch(i,s,a){const c=e.now??Jw,u=e.onTrace?c():0,d=e.onTrace?Date.now():0,l=e.onTrace?a.requestId??`runtime_${++n}`:"";e.onTrace&&mo(e.onTrace,{callId:l,method:i,startedAt:d,outcome:"started"},()=>u,u);try{if(e.terminalSignal.aborted)throw ho("RUNTIME_DESTROYED","小程序 Runtime 已终止");Nf(i,e.effectiveCapabilities);const h=$w.get(i);if(!h)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const f=t(h),_=!f.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,s)===!0,p=!f.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,s)===!0,y=!f.allowed&&r.valid&&r.permissions.user_game_data?.status==="enabled"&&e.allowsUserGameDataFileAccess?.(i,s)===!0;if(!f.allowed&&!_&&!p&&!y)throw ho(f.code,f.message,f.data);const w=e.handlers[i];if(!w)throw new Error(`Capability method ${i} 缺少 handler`);const N=async H=>{for(const Q of e.policies??[]){const M=await Q.evaluate({method:i,payload:s,capability:h});if(e.terminalSignal.aborted||H.aborted)throw gl();if(!M.allowed)throw ho(M.code,M.message,M.data)}if(e.terminalSignal.aborted||H.aborted)throw gl()},I=await Zw(async()=>{if(i===Br){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(s,a.signal,N)}return await N(e.terminalSignal),w(s,a)},void 0,a,e.terminalSignal);return e.onTrace&&mo(e.onTrace,El(l,i,s,d,I),c,u),I}catch(h){throw e.onTrace&&mo(e.onTrace,El(l,i,s,d,{status:"error",error:h}),c,u),h}}}}function Jw(){return typeof performance>"u"?Date.now():performance.now()}function mo(e,t,r,n){if(!e)return;const i=r()-n,s=Date.now();try{e({...t,phase:"host",timestamp:s,durationMs:Math.max(0,Number.isFinite(i)?i:0)})}catch{}}function El(e,t,r,n,i){const s=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:n,outcome:s,...i.status==="error"?{errorCode:eD(i.error)}:{},...tD(t,r,i)}}function eD(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function tD(e,t,r){if(e!=="network.request"||typeof t!="object"||t===null||!("url"in t)||typeof t.url!="string")return{};try{const n=new URL(t.url);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password)return{};const s=("method"in t&&typeof t.method=="string"?t.method:"GET").trim().toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(s))return{};const a=r.status==="handled"&&sc(r.value)&&typeof r.value.status=="number"?r.value.status:void 0;return{network:{method:s,origin:n.origin,pathname:n.pathname,...a===void 0?{}:{responseStatus:a}}}}catch{return{}}}function sc(e){return typeof e=="object"&&e!==null}function gl(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function rD(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=b_(e.requestPolicy);let n;if(e.files)try{n=f_(e.files,t)}catch{}const i=Ff({store:n}),s=e.onRequestPolicyReport??(r.debugReport?nD:void 0),a=r.enabled?__({...r.gateOptions,...s?{onReport:s}:{}}):void 0,c=new Vc(e.files,e.miniProgramDetail),u=uy({registry:c,picker:e.picker,operationContext:t}),d=Q_({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode,authorizationContext:e.authorizationContext,identityTtlMs:r.identityTtlMs,requestGate:a,requestPolicyEnabled:r.enabled});let l,h,f,_,p,y,w,N=()=>{},O=()=>{};try{l=qw({operationContext:t,presentation:e.hostPresentation,onDisplayChange:j=>e.eventSink.postEvent("display_change",j),onViewportChange:j=>e.eventSink.postEvent("viewport_change",j)}),f=_w({authPresentation:e.authPresentation,authorizationContext:e.authorizationContext,account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:d,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:a,requestPolicyEnabled:r.enabled}),N=d.onEvent((j,z)=>e.eventSink.postEvent(j,z)),O=e.hostCompanion?.onSessionEvent?.(j=>{const z=ny(j);!e.terminalSignal.aborted&&z&&e.eventSink.postEvent(z.type,z.payload)})??(()=>{}),_=LT({roomSocket:e.roomSocket,onRoomEvent:j=>e.eventSink.postEvent("cloud_rooms_event",j),authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:a,requestPolicyEnabled:r.enabled});const I=e.files&&e.transfer?qc({files:e.files,transfer:e.transfer,registry:c,signal:t.signal}):void 0,H=Vw({...e.verifiedSdkVersion===void 0?{}:{verifiedSdkVersion:e.verifiedSdkVersion},identity:e.identity,account:e.account,storage:e.storage,network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,fileDownloads:I,requestGate:a,requestPolicyEnabled:r.enabled,fileRegistry:c,...e.userDataPresentation===void 0?{}:{presentation:e.userDataPresentation},...e.miniProgramPresentation===void 0?{}:{miniProgramPresentation:e.miniProgramPresentation},runtimePermissions:e.runtimePermissions,environment:e.miniProgramDetail?.releaseChannel,operationContext:t,...e.onUserDataTelemetry===void 0?{}:{telemetry:{sink:{postEvent(j,z){e.onUserDataTelemetry?.({name:j,payload:z})}}}}});w=H,p=GT({identity:e.identity,storage:e.storage,account:e.account,presentation:e.hostPresentation,network:e.network,authorization:d,authorizationContext:e.authorizationContext,operationContext:t,files:e.files,transfer:e.transfer,fileRegistry:c,fileDownloads:I,requestGate:a,requestPolicyEnabled:r.enabled}),y=Gb({presentation:e.hostPresentation,account:e.account,network:e.network,authorization:d,authorizationContext:e.authorizationContext,operationContext:t,requestGate:a,requestPolicyEnabled:r.enabled,onBackgroundError:e.onBackgroundError,emit:j=>e.eventSink.postEvent("post_change",j)});const Q=WN({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});h=Ly({registry:c,media:e.media,operationContext:t});const M=[{name:"post",handlers:y.handlers},{name:"gameSaves",handlers:Object.fromEntries(Object.entries(p.handlers).map(([j,z])=>[j,async(V,U)=>{const k=e.verifiedSdkVersion,Y=k?La(k,"0.10.0-0"):void 0;if(Y===void 0||Y>=0)throw T("REQUEST_UNSUPPORTED","当前 SDK 不支持旧游戏存档入口,请使用 user.games.get(...).saves");return z(V,U)}]))},{name:"auth",handlers:tT({authorization:d})},{name:"user",handlers:{...Ow({user:f,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...s_({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:YN({prepareScreenshot:e.prepareScreenshot,prepareLongScreenshot:e.prepareLongScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:l.handlers},{name:"storage",handlers:Q.handlers},{name:"network",handlers:lN({network:e.network,transfer:e.transfer,fileRegistry:c,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins,allowDevelopmentHttp:e.allowDevelopmentHttp,networkPolicy:e.networkPolicy,firstParty:e.firstParty})},{name:"workspaceCards",handlers:Ww(e.workspaceCards,t)},{name:"files",handlers:u.files},{name:"file",handlers:u.file},{name:"directory",handlers:u.directory},{name:"media",handlers:h.handlers},{name:"ui",handlers:JN({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:oy({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:nN({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:j=>l.applyOrientation({mode:"portrait",hideCapsule:!1},j)}:{}})},{name:"cloud",handlers:_.handlers},{name:"userGameData",handlers:w.handlers},{name:"companion",handlers:Xb({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:c})}],x=iD(M);let v=!1;const W=()=>{v||(v=!0,e.terminalSignal.removeEventListener("abort",W),l?.dispose(),h?.dispose(),_?.dispose(),p?.dispose(),y?.dispose(),w?.dispose(),N(),O(),f?.dispose(),i.dispose(),d.dispose(),a?.dispose(),c.dispose())};e.terminalSignal.aborted?W():e.terminalSignal.addEventListener("abort",W,{once:!0});const q=new Set(["file.readText","file.readBytes","file.stat"]),te=(j,z)=>q.has(j)&&sc(z)&&c.isCompanionAttachmentRef(z.target),F=new Set(["file.readText","file.readBytes","file.stat","file.exists"]),G=(j,z)=>F.has(j)&&sc(z)&&c.isUserDataDownloadRef(z.target);return{get permissionBridge(){return H.permissionBridge},modules:M,setPostVisible:y.setVisible,dismissPostEditor:y.dismissEditor,handlers:x,runDisplayRequest:l.runDisplayRequest,allowsCompanionAttachmentAccess:te,allowsGameSaveAccess:p.allowsRead,allowsUserGameDataFileAccess:G,gameSaveDiagnostics:p.diagnostics,applyOrientation:l.applyOrientation,notifyViewportChange:l.notifyChange,promptPcHardwareOnEntry:H.promptPcHardwareOnEntry,...Q.diagnostics?{storageDiagnostics:Q.diagnostics}:{},...e.files?{sandboxDiagnostics:_y({registry:c,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},releaseRoomsForDocumentReload:()=>_?.releaseRoomsForDocumentReload(),dispose:W}}catch(I){throw l?.dispose(),h?.dispose(),_?.dispose(),p?.dispose(),y?.dispose(),w?.dispose(),N(),O(),f?.dispose(),i.dispose(),d.dispose(),a?.dispose(),c.dispose(),I}}function nD(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function iD(e){const t=new Map(pr.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[s,a]of Object.entries(i.handlers)){const c=s,u=t.get(c);if(!u)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${c}`);if(u!==i.name)throw new Error(`Capability method ${c} 应由 ${u} 拥有,不能注册到 ${i.name}`);if(r.has(c))throw new Error(`Capability method ${c} 存在重复 owner`);if(typeof a!="function")throw new Error(`Capability method ${c} 缺少 handler`);r.set(c,a)}const n=pr.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==pr.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const sD="heybox-mini-dev:";function pl(e){try{return aD(new URL(e))}catch{return!1}}function aD(e){return e.protocol===sD}function oD(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||cD(e)}function cD(e){const t=e.split(".");if(t.length!==4)return!1;const r=t.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);return r.some(n=>!Number.isInteger(n)||n<0||n>255)?!1:r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}const uD=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function dD(e,t){const r=[],n=lD(e.environmentInfo,r),i=us(n?.appVersion,"host.appVersion",r),s=hD(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:fD(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:us(t.miniProgramId),version:us(t.miniProgramVersion)}),operatingSystem:Object.freeze(s)}),invalidFields:Object.freeze(r)}}function lD(e,t){if(e!=null){if(Em(e))return e;t.push("environmentInfo")}}function fD(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function hD(e,t){if(e==null)return{name:"unknown",version:null};if(!Em(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=uD.has(e.name)?e.name:"unknown";return r==="unknown"&&e.name!==void 0&&e.name!==null&&e.name!=="unknown"&&t.push("operatingSystem.name"),{name:r,version:us(e.version,"operatingSystem.version",t)}}function us(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Em(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const mD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",ED="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",gD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",pD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function _D(e,t,r,n,i="dark"){ve(n);const s=e.defaultView;if(!s||!e.body)throw new Error("截图水印缺少可用的展示窗口");const a=e.createElement("div"),c=i==="light",u=c?"black":"white";a.dataset.miniProgramScreenshotWatermark="",a.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);a.style.cssText=`position:absolute;left:${r.left+s.scrollX}px;top:${r.top+s.scrollY+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const l=e.createElement("div");l.style.cssText=`display:flex;flex-direction:column;align-items:center;width:max-content;max-width:${r.width/d-24}px;transform:scale(${d});transform-origin:top left;font-family:"PingFang SC",sans-serif;`;const h=e.createElement("div");h.style.cssText="display:flex;align-items:center;max-width:100%;height:22px;flex-shrink:0;";const f=e.createElement("img");f.src=c?gD:mD,f.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const _=e.createElement("div");_.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${u};border-radius:11px;padding:0 7px 0 6px;`;const p=e.createElement("img");p.src=c?pD:ED,p.style.cssText="width:12px;height:12px;flex-shrink:0;";const y=e.createElement("span");y.textContent=t?.trim()||"小程序工坊",y.style.cssText=`color:${u};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const w=e.createElement("div");w.textContent="小黑盒工坊小程序",w.style.cssText=`margin-top:6px;color:${c?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,_.append(p,y),h.append(f,_),l.append(h,w),a.append(l),e.body.append(a);const N=()=>{a.remove(),n.removeEventListener("abort",N)};n.addEventListener("abort",N,{once:!0});try{await Se(()=>Promise.all([f.decode(),p.decode()]),n);const O=l.getBoundingClientRect();return a.style.left=`${r.left+s.scrollX+(r.width-O.width)/2}px`,a.style.width=`${O.width}px`,a.style.height=`${O.height}px`,l.style.width=`${O.width/d}px`,l.style.height=`${O.height/d}px`,l.style.maxWidth="none",await Se(()=>new Promise(I=>{let H=s.requestAnimationFrame(()=>{H=s.requestAnimationFrame(()=>{n.removeEventListener("abort",Q),I()})});const Q=()=>s.cancelAnimationFrame(H);n.addEventListener("abort",Q,{once:!0})}),n),N}catch(O){throw N(),O}}const TD=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"]),AD=new Set(["url","inline","eval","unknown"]),ID=/^\/(?:\:segment(?:\/\:segment)*)?$/,bD=/^[a-f0-9]{64}$/,yD=255,ND=160,wD=256;function DD(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!TD.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>wD||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!AD.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=SD(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>ND||!ID.test(i)))return;const s=r.sanitizedPathnameHash;if(!(s!==void 0&&(typeof s!="string"||!bD.test(s)||i===void 0)))return{effectiveDirective:r.effectiveDirective,violatedDirective:r.effectiveDirective,blockedResourceType:r.blockedResourceType,origin:n,sanitizedPathname:i,sanitizedPathnameHash:s,sdkVersion:r.sdkVersion,timestamp:r.timestamp}}function SD(e){if(e!==void 0&&!(typeof e!="string"||e.length>yD))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Va=["android","ios","ohos","windows","macos","linux"],OD="0.9.0",MD=Object.freeze(["android","ios","ohos","windows","macos"]),gm="该小程序暂不支持当前平台",RD="PLATFORM_UNSUPPORTED";function CD(e){return typeof e=="string"&&Va.includes(e)}function LD(e){if(typeof e!="string")return;const t=e.trim().toLowerCase().replace(/[\s_-]/g,"");if(t==="android")return"android";if(t==="ios")return"ios";if(t==="ohos"||t==="harmony"||t==="harmonyos")return"ohos";if(t==="windows"||t==="win32"||t==="win64")return"windows";if(t==="mac"||t==="macos"||t==="darwin")return"macos";if(t==="linux")return"linux"}function PD(e){const t=e.manifest;if(!BD(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Tl(e.sdkVersion)??Tl(t.sdkVersion);return xD(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:kD()}const r=pm(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function vD(e){const t=LD(e.operatingSystemName);if(!t)return sn("host_operating_system_unknown");const r=e.platformAccess;if(!r)return sn("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Va,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const a=PD({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return a.status==="invalid"?sn("platform_declaration_invalid",{invalidReason:a.reason,platform:t}):_l(t,a)}if(r.effectivePlatforms===void 0)return sn("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=pm(r.effectivePlatforms);if("reason"in n)return sn("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,s=UD(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return _l(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:s})}function _l(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:sn("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function sn(e,t={}){return{status:"denied",reason:e,message:gm,...t}}function kD(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:MD,platformsDeclared:!1,policy:"legacy_mobile_default"}}function pm(e){if(!Array.isArray(e))return{reason:"platforms_not_array"};if(e.length===0)return{reason:"platforms_empty"};const t=new Set;for(const r of e){if(!CD(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Va.filter(r=>t.has(r)))}}function xD(e){if(typeof e!="string"||!e.trim())return!1;const t=La(e.trim(),OD);return t!==void 0&&t>=0}function Tl(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function UD(e){return e==="explicit"||e==="legacy_mobile_default"}function BD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function HD(e,t,r){const n=Date.now();try{const i=new URL(t);return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r,origin:i.origin,sanitizedPathname:FD(i.pathname),sanitizedPathnameHash:Bc(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function FD(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}const zD=1e4,jD=3e4,VD=1e4,Eo=2e3,GD=2,YD="open-with-native-credential-policy",_m="安全提示",Tm="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class qD{nonce=Uu();runtimeId=Uu();terminalController=new AbortController;options;handshakeTimeout;identity;identityRef;iframe;iframeErrorListener;iframeLoadListener;bridgeServer=null;miniProgramSrc="";launchUrl="";startPromise=null;readyContext=null;resolveReady;rejectReady;terminalError;status="idle";stateValue="idle";handshakeTimeoutTimer;lifecycleDisposer;workspaceCardsDisposer;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;failureTransitionInProgress=!1;destroyRequestedDuringFailure=!1;sdkVersionDecision;platformGateDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;awaitingDevelopmentDocumentLoad=!1;unexpectedDocumentLoadTimer;devDocumentDisposer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;firstParty=!1;networkPolicy;networkPolicyDisposer;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;allowDevelopmentHttp=!1;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe,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??zD,this.iframeErrorListener=r=>{this.onIframeError(r)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.awaitingDevelopmentDocumentLoad&&(this.awaitingDevelopmentDocumentLoad=!1,this.stateValue==="starting"&&this.armHandshakeTimeout()),this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.capabilityGraph?.releaseRoomsForDocumentReload(),this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?(this.capabilityGraph?.releaseRoomsForDocumentReload(),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}getDataPermissionBridge(){return this.capabilityGraph?.permissionBridge}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics,r=this.capabilityGraph?.sandboxDiagnostics,n=this.capabilityGraph?.gameSaveDiagnostics;return{...t?{storage:t}:{},...r?{sandbox:r}:{},...n?{gameSaves:n}:{}}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??ke("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??ke("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(i1(),this.startPromise=this.createReadyPromise(),this.setState("starting"),this.setStatus("starting"),this.launch().catch(t=>{this.failRuntime(t)}),this.startPromise)}destroy(){if(this.failureTransitionInProgress){this.destroyRequestedDuringFailure=!0;return}if(this.stateValue==="destroyed")return;const t=this.terminalError??ke("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.capabilityGraph?.setPostVisible(!0),this.emitLifecycleEvent("show"),this.capabilityGraph?.notifyViewportChange(),!t&&this.stateValue==="ready"&&this.capabilityGraph?.promptPcHardwareOnEntry(),!t&&this.stateValue==="ready"&&this.sdkVersionDecision?.heartbeatEnabled&&(this.documentRevalidationPending?this.preparedHistoryTraversalGeneration!==void 0?this.armDocumentRevalidationTimer(this.documentRevalidationGeneration,{waitingForDocument:!0}):this.resendDocumentRevalidationProbe():this.sendLocationProbe())}hide(){this.hostVisible=!1,this.capabilityGraph?.setPostVisible(!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.isInactive()||t!==this.documentRevalidationGeneration?()=>{}:(this.preparedHistoryTraversalGeneration=t,()=>{this.preparedHistoryTraversalGeneration===t&&this.cancelPreparedHistoryTraversal()})}createReadyPromise(){return new Promise((t,r)=>{this.resolveReady=t,this.rejectReady=r})}async launch(){const t=await this.resolveRuntimeLaunchConfiguration();if(this.isInactive())return;if(this.runtimePermissions=Ep(t.runtimePermissions),this.firstParty=t.firstParty===!0,this.networkPolicy=this.firstParty?void 0:Df(t.networkPolicy),this.networkPolicy?.enforcement==="restricted"){const d=t.canonicalIdentity?.miniProgramId?.trim();if(!d||!this.options.networkPolicyEnforcement)throw{code:"NETWORK_POLICY_UNSUPPORTED",message:"当前 Host 尚未具备严格网络策略执行能力,请更新 Host 后重新打开"};const l=await Zg(this.options.networkPolicyEnforcement,{policy:this.networkPolicy,miniProgramId:d,launchUrl:t.launchUrl,onInvalidated:()=>this.failRuntime({code:"NETWORK_POLICY_CHANGED",message:"网络权限已变更,请重新打开小程序"})},{signal:this.terminalController.signal});if(this.isInactive()){l();return}this.networkPolicyDisposer=l}this.runtimeFeatures=t.runtimeFeatures?Object.freeze({...t.runtimeFeatures}):void 0,this.miniProgramPresentation=t.miniProgramPresentation,this.locationBasePath=t.locationBasePath,this.anonymousStorageScope=t.anonymousStorageScope??this.options.anonymousStorageScope;const r=t.allowedHttpOrigins??this.options.allowedHttpOrigins;this.allowedHttpOrigins=r?Object.freeze([...r]):void 0,this.bindCanonicalIdentity(t.canonicalIdentity),this.sdkVersionDecision=n_(t.sdkVersionPolicy),this.allowDevelopmentHttp=t.sdkVersionPolicy?.releaseChannel==="development";const n=dD(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.platformGateDecision=vD({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw o1(this.platformGateDecision);this.miniProgramDetail=c1(t);const{ports:i,primitiveAvailability:s,effectiveCapabilities:a}=wf({...this.options.ports,roomSocket:this.options.authorizationContext?this.options.ports.roomSocket:void 0},{callerCapabilities:this.options.capabilities,hostCapabilities:this.options.hostCapabilities,miniProgramDetail:this.miniProgramDetail,hasUserDataPresentation:this.options.userDataPresentation!==void 0,hasUserDataSettings:this.options.userDataPresentation?.openDataPermissions!==void 0});if(console.info("[hb-sdk-runtime] host capability",Object.freeze({filesAccessPrimitive:s["files.access"],callerFileCreate:this.options.capabilities?.["file.create"]??"default",hostFileCreate:this.options.hostCapabilities?.["file.create"]??"default",canonicalMiniProgramDetail:!!this.miniProgramDetail?.miniProgramId.trim(),effectiveFileCreate:a["file.create"]===!0})),this.compatibilityWithoutSdk=!!(t.sdkVersionPolicy&&t.sdkVersionPolicy.releaseChannel!==void 0&&!this.sdkVersionDecision.sdkVersion&&!this.sdkVersionDecision.heartbeatEnabled),JD(this.options.onLaunchConfigurationResolved,t,this.sdkVersionDecision),this.isInactive())return;this.applyIframeDefaults(),this.startBridgeServer(i,a),this.installSubscriptions();const c=await this.normalizeLaunchUrl(t.launchUrl);if(this.isInactive())return;const u=await this.confirmDevMiniProgramLaunch(c);if(!this.isInactive()){if(!u){await this.closeAfterDevLaunchCancellation(i.presentation);return}if(this.bridgeServer?.setTargetOrigin(t1(c)),this.launchUrl=c,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const d=Sf(new URL(c),this.locationBasePath);this.devDocumentDisposer=mp({iframe:this.iframe,launchUrl:c,nonce:this.nonce,locationBasePath:d,onLeaving:()=>{this.prepareForHistoryTraversal()},onResume:()=>{!this.isInactive()&&this.documentRevalidationPending&&this.beginDocumentRevalidation()},onReload:l=>{this.isInactive()||Pt(h=>this.options.onDevDocumentReload?.(h,d),l)}})}if(this.miniProgramSrc=ap(c,this.nonce),this.traceSecurityPolicy(c),this.setStatus("src_resolved"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"src_resolved"}),s["presentation.applyOrientation"]){try{await this.capabilityGraph?.applyOrientation({mode:"portrait",hideCapsule:!1})}catch(d){if(this.isInactive())return;const l=Js(d);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:Br,errorCode:l.code,message:`默认展示设置失败,沿用宿主当前布局:${l.message}`})}if(this.isInactive())return}this.awaitingDevelopmentDocumentLoad=t.sdkVersionPolicy?.releaseChannel==="development",this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,Pt(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout(this.awaitingDevelopmentDocumentLoad)}}startBridgeServer(t,r){const n=t.workspaceCards,i={postEvent:(a,c)=>{this.stateValue==="ready"&&(a!=="viewport_change"||r["viewport.getWindowInfo"])&&(a!=="display_change"||r[Br])&&this.bridgeServer?.postEvent(a,c)}};this.capabilityGraph=rD({verifiedSdkVersion:this.sdkVersionDecision?.sdkVersion,diagnosticCapabilities:r,account:t.account,network:t.network,files:t.files,picker:t.picker,media:t.media,transfer:t.transfer,storage:t.storage,scopedStorage:t.scopedStorage,storageDiagnostics:t.storageDiagnostics,hostPresentation:t.presentation,hostCompanion:t.companion,roomSocket:t.roomSocket,hostProtocol:t.protocol,...this.options.userDataPresentation===void 0?{}:{userDataPresentation:this.options.userDataPresentation},...this.options.onUserDataTelemetry===void 0?{}:{onUserDataTelemetry:this.options.onUserDataTelemetry},workspaceCards:t.workspaceCards,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,networkPolicy:this.networkPolicy,firstParty:this.firstParty,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:i,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,prepareLongScreenshot:(a,c)=>Kg(this.iframe,a,c),prepareScreenshot:(a,c,u)=>{const d=this.sdkVersionDecision?.sdkVersion;return!d||(La(d,"0.9.1")??-1)<0?Promise.resolve(()=>{}):_D(this.iframe.ownerDocument,this.miniProgramPresentation?.name,a,c,u)},miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins,allowDevelopmentHttp:this.allowDevelopmentHttp,requestPolicy:this.options.requestPolicy,onBackgroundError:(a,c)=>{const u=Js(c);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",errorCode:u.code,message:`后台任务 ${a} 失败:${u.message}`})},...this.options.onRequestPolicyReport?{onRequestPolicyReport:this.options.onRequestPolicyReport}:{}}),this.capabilityGraph.setPostVisible(this.hostVisible);const s=Xw({handlers:this.capabilityGraph.handlers,runDisplayRequest:this.capabilityGraph.runDisplayRequest,effectiveCapabilities:r,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,allowsGameSaveAccess:this.capabilityGraph.allowsGameSaveAccess,allowsUserGameDataFileAccess:this.capabilityGraph.allowsUserGameDataFileAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:a,method:c,startedAt:u,timestamp:d,durationMs:l,outcome:h,errorCode:f,network:_})=>{const p={type:"capability",phase:"host",runtimeId:this.runtimeId,callId:a,method:c,startedAt:u,timestamp:d,durationMs:l,outcome:h,...f?{errorCode:f}:{},...this.identity,..._?{network:_}:{}};Pt(this.options.onCapabilityTrace,p)}}:{}});this.bridgeServer=new Ap({iframe:this.iframe,nonce:this.nonce,dispatcher:s,environmentInfo:this.environmentInfo,...this.options.onDevUploadSession?{onDevUploadSession:a=>{this.isInactive()||Pt(this.options.onDevUploadSession,a)}}:{},...n?{getWorkspaceCardLaunchContext:()=>n.getLaunchContext()}:{},onHandshake:a=>this.handleBridgeHandshake(a),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:a=>{this.handleInternalBridgeEvent(a)},onResponsePosted:({method:a,outcome:c,errorCode:u})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:a,outcome:c,...u?{errorCode:u}:{}})}}),this.bridgeServer.start(),this.workspaceCardsDisposer=n?.onLaunchContextChange(()=>{this.stateValue==="ready"&&this.bridgeServer?.postEvent("workspace_cards_launch_context_change",n.getLaunchContext())}),this.setStatus("bridge_started"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge_started"})}onIframeError(t=new Error("小程序 iframe 加载失败")){if(this.isInactive())return;const r=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(ke("IFRAME_LOAD_ERROR",r,t))}emitLifecycleEvent(t){if(this.stateValue!=="ready"){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle_ignored",event:t,reason:this.isInactive()?"inactive":"not_ready"});return}this.bridgeServer?.postEvent(t,{timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle",method:t})}async resolveRuntimeLaunchConfiguration(){try{return await this.options.resolveLaunchConfiguration()}catch(t){throw XD(t)?t:Am(ke("STARTUP_ERROR",t instanceof Error?t.message:"获取小程序启动配置失败"),t)}}bindCanonicalIdentity(t){const r=t?.miniProgramId?.trim();r&&(this.identity.miniProgramId=r);const n=t?.miniProgramVersion?.trim();n&&(this.identity.miniProgramVersion=n)}async normalizeLaunchUrl(t){try{const r=this.options.environment.getCurrentHref();return sp(t,r,{allowPrivateNetwork:pl(r)||Al(r)||await this.isDevRuntime()})}catch(r){throw ke("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??n1)({message:Tm,title:_m,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Hu(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!pl(r)&&!Al(r)}async closeAfterDevLaunchCancellation(t){const r=ke("LAUNCH_CANCELLED","小程序启动已取消");this.terminalError=r,this.destroyBridgeServer();const n=new AbortController;let i;try{i=Promise.resolve(t.close({signal:n.signal}))}catch{Il(),i=Promise.resolve()}this.terminalController.abort(r),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"launch_cancelled"}),this.rejectReady?.(r),await i.catch(()=>Il())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",tp),this.iframe.setAttribute("referrerpolicy",rp),this.iframe.setAttribute("sandbox",Of)}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.workspaceCardsDisposer];this.lifecycleDisposer=null,this.workspaceCardsDisposer=null;for(const r of t)try{r?.()}catch{}}handleBridgeReady(){if(this.isInactive())return;if(this.readyContext){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"});return}this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge",method:"ready"}),this.setState("ready"),this.sdkVersionDecision?.heartbeatEnabled&&this.hostVisible&&this.sendLocationProbe(),this.hostVisible&&this.capabilityGraph?.promptPcHardwareOnEntry(),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),Pt(this.options.onReady,t)}completeCompatibilityLaunch(){if(this.stateValue!=="starting"||this.isInactive()||this.readyContext)return;this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:"bridge_ready"}),this.setState("ready"),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),Pt(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{i_(r,t?.sdkVersion)}catch(n){return this.failRuntime(n),!1}return!0}armHandshakeTimeout(t=!1){this.clearHandshakeTimeout(),!(this.handshakeTimeout<=0)&&(this.handshakeTimeoutTimer=setTimeout(()=>{if(!(this.stateValue==="ready"||this.isInactive())){if(t){this.onIframeError(new Error("开发页面加载超时,请检查 Vite 服务、入口脚本和网络连接"));return}this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"handshake_timeout"}),this.failRuntime(ke("SDK_HANDSHAKE_TIMEOUT","小程序 SDK 握手超时"))}},t?jD: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>=GD)){this.failRuntime(ke("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(ki,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},Eo),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:ki})}clearHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0),this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0}beginDocumentRevalidation(t={}){this.clearUnexpectedDocumentLoadFailure(),this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.preparedHistoryTraversalGeneration=void 0,this.documentRevalidationPending=!0;const r=++this.documentRevalidationGeneration;return this.iframeHiddenForRevalidation||(this.iframeVisibilityBeforeRevalidation=this.iframe.style.visibility,this.iframe.style.visibility="hidden",this.iframeHiddenForRevalidation=!0),t.deferProbe?this.armDocumentRevalidationTimer(r,{waitingForDocument:!0}):this.sendDocumentRevalidationProbe(),this.traceDocumentValidation(),r}sendDocumentRevalidationProbe(){if(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)return;const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.armDocumentRevalidationTimer(this.documentRevalidationGeneration),this.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled||this.preparedHistoryTraversalGeneration!==void 0)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(ki,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:ki})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&this.failRuntime(ke("DOCUMENT_REVALIDATION_TIMEOUT",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时"))},r.waitingForDocument?VD:Eo))}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()},Eo)),this.traceDocumentValidation()}traceDocumentValidation(){this.isInactive()||this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"document_validation",documentVerifying:this.documentRevalidationPending,message:this.documentRevalidationPending?"当前文档正在验证":"当前文档验证等待已结束"})}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(),this.traceDocumentValidation()}handleDuplicateBridgeHandshake(){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"}),this.documentRevalidationPending&&this.resendDocumentRevalidationProbe()}handleInternalBridgeEvent(t){if(t.method==="sdk.post.editor.dismiss"){const i=t.payload;typeof i?.requestId=="string"&&this.capabilityGraph?.dismissPostEditor(i.requestId);return}if(t.method===x0){this.handleCspViolation(t.payload);return}if(t.method!==k0)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(ke("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Mf(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(ke("URL_OUT_OF_SCOPE","小程序页面地址超出允许范围"));return}n.probeId!==void 0?(this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.documentRevalidationPending&&this.completeDocumentRevalidation()):this.documentRevalidationPending&&!this.pendingProbeId&&(this.preparedHistoryTraversalGeneration=void 0,this.sendDocumentRevalidationProbe())}}handleCspViolation(t){const r=DD(t,this.sdkVersionDecision?.sdkVersion);r&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:r.timestamp,sdkVersion:r.sdkVersion,origin:r.origin,sanitizedPathname:r.sanitizedPathname,sanitizedPathnameHash:r.sanitizedPathnameHash,effectiveDirective:r.effectiveDirective,violatedDirective:r.violatedDirective,blockedResourceType:r.blockedResourceType})}emitSecurityViolation(t){Pt(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=HD(t,r,this.sdkVersionDecision?.sdkVersion);this.emitSecurityViolation(n)}scheduleUnexpectedDocumentLoadFailure(){this.clearUnexpectedDocumentLoadFailure(),this.unexpectedDocumentLoadTimer=setTimeout(()=>{this.unexpectedDocumentLoadTimer=void 0,this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(ke("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 发生未授权文档加载"))},50)}clearUnexpectedDocumentLoadFailure(){this.unexpectedDocumentLoadTimer&&(clearTimeout(this.unexpectedDocumentLoadTimer),this.unexpectedDocumentLoadTimer=void 0)}traceSecurityPolicy(t){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"security",sandboxPolicyVersion:ep,launchUrlType:Hu(t),networkPolicy:YD})}failRuntime(t){const r=QD(t);if(this.isInactive())return r;this.terminalError=r,this.stateValue="failed",this.failureTransitionInProgress=!0;try{this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),Pt(this.options.onError,WD(r)),Pt(this.options.onStateChange,"failed"),this.terminalController.abort(r),this.postBridgeError(r);try{this.disposeRuntimeResources()}finally{this.teardownIframe(r)}}finally{this.rejectReady?.(r),this.failureTransitionInProgress=!1,this.destroyRequestedDuringFailure&&(this.destroyRequestedDuringFailure=!1,this.destroy())}return r}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(this.devDocumentDisposer?.(),this.devDocumentDisposer=void 0,!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0;try{this.networkPolicyDisposer?.()}catch{}this.networkPolicyDisposer=void 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,Pt(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){Pt(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 QD(e){const t=Js(e);return fa(e)&&"cause"in e&&Am(t,e.cause),t}function Am(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function WD(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{},...e.cause!==void 0?{cause:ZD(e.cause)}:{}}}const go=(()=>{const e=Object.getOwnPropertyDescriptor(new Error,"stack")?.get,t=Object.getOwnPropertyDescriptor(new Error,"stack")?.get;return typeof e=="function"&&e===t?e:void 0})(),$D=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function KD(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return;if("value"in r)return r.value;if(t!=="stack"||!go||r.get!==go)return;const n=Object.getPrototypeOf(e);if($D.has(n)){for(const i of["name","message"]){const s=Object.getOwnPropertyDescriptor(e,i),a=Object.getOwnPropertyDescriptor(n,i)??Object.getOwnPropertyDescriptor(Error.prototype,i);if(s&&!("value"in s)||a&&!("value"in a))return}return go.call(e)}}function ZD(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=KD(e,r);typeof n=="string"&&(t[r]=n.slice(0,r==="stack"?8192:2048).replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@").replace(/([?&][^=\s]+)=([^&#\s]*)/g,"$1=[redacted]").replace(/(authorization|cookie|password|secret|token|pkey|api[_-]?key)([\"'\s:=]+)([^\s,}]+)/gi,"$1$2[redacted]"))}return Object.keys(t).length?t:void 0}catch{return}}function XD(e){return fa(e)&&typeof e.code=="string"&&typeof e.message=="string"}function fa(e){return!!e&&typeof e=="object"}function Pt(e,t){try{e?.(t)}catch{}}function JD(e,t,r){try{e?.(t,r)}catch{}}function Al(e){try{const t=new URL(e);return t.protocol==="http:"&&oD(t.hostname)}catch{return!1}}function e1(e){try{return new URL(e).origin}catch{return}}function t1(e){return np()?"*":e1(e)}function r1(e){return`${_m}
9
-
10
- ${Tm}
11
-
12
- URL: ${e}`}function n1(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(r1(e.url))}function Il(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function i1(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,r=typeof window>"u"?void 0:window,n=Object.freeze({protocolVersion:Wl,knownMethodCount:pr.length,supportsFileCreate:pr.some(i=>i.method===di),system:s1(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:nn(e?.hardwareConcurrency),maxTouchPoints:nn(e?.maxTouchPoints),screen:{width:nn(t?.width),height:nn(t?.height)},viewport:{width:nn(r?.innerWidth),height:nn(r?.innerHeight),devicePixelRatio:a1(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function s1(e="",t=""){const r=`${t} ${e}`.toLowerCase();return/iphone|ipad|ipod/.test(r)?"ios":r.includes("android")?"android":/win32|win64|windows/.test(r)?"windows":/darwin|macintosh|macintel|mac os/.test(r)?"macos":/linux|x11/.test(r)?"linux":"unknown"}function nn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function a1(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function o1(e){return ke(RD,gm,{reason:e.reason,...e.platform===void 0?{}:{platform:e.platform},...e.invalidReason===void 0?{}:{invalidReason:e.invalidReason},...e.effectivePlatforms===void 0?{}:{effectivePlatforms:e.effectivePlatforms}})}function c1(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(!t)return;const r=e.canonicalIdentity?.miniProgramVersion?.trim(),n=e.miniProgramPresentation?.name?.trim(),i=e.miniProgramPresentation?.avatarUrl?.trim(),s=e.miniProgramPresentation?.author?.trim();return Object.freeze({miniProgramId:t,...r?{version:r}:{},...n?{name:n}:{},...i?{iconUrl:i}:{},...s?{author:s}:{},...e.sdkVersionPolicy.releaseChannel===void 0?{}:{releaseChannel:e.sdkVersionPolicy.releaseChannel}})}function u1(e){if(!fa(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!fa(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 qD(e)}function d1(e={}){return async(t,r,n)=>{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");const i=e.indexedDB??globalThis.indexedDB,s=e.crypto??globalThis.crypto;if(!i||!s?.getRandomValues)throw new Error("Host 缺少持久化账号标识能力");const a=await new Promise((c,u)=>{const d=i.open("heybox-mini-program-private-account-v1",1);let l=!1;const h=()=>n.signal.removeEventListener("abort",_),f=p=>{l||(l=!0,h(),u(p))},_=()=>f(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{l?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>f(d.error),d.onblocked=()=>f(new Error("账号存储被阻塞")),d.onsuccess=()=>{l?d.result.close():(l=!0,h(),c(d.result))},n.signal.addEventListener("abort",_,{once:!0}),n.signal.aborted&&_()});try{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");return await new Promise((c,u)=>{const d=a.transaction("accounts","readwrite"),l=d.objectStore("accounts"),h=JSON.stringify([t,r]);let f;const _=()=>{try{d.abort()}catch{}p(),u(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",_,{once:!0});const p=()=>n.signal.removeEventListener("abort",_);d.oncomplete=()=>{p(),c(f)},d.onabort=d.onerror=()=>{p(),u(d.error??new Error("账号存储事务失败"))};const y=l.get(h);y.onsuccess=()=>{try{if(typeof y.result=="string"&&/^ak_[0-9a-f]{64}$/.test(y.result))f=y.result;else{const w=s.getRandomValues(new Uint8Array(32));f=`ak_${Array.from(w,N=>N.toString(16).padStart(2,"0")).join("")}`,l.put(f,h)}}catch{d.abort()}}})}finally{a.close()}}}const l1=/^(?: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,f1=new Set(["origin","referer","user-agent"]);function h1(e,t){return Dg({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const s={...n,signal:i},a=m1(r),c=await e.authenticatedRequest(a,s);return p1(c)})}).network}function m1(e){const t=E1(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function E1(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!g1(t)))}function g1(e){const t=e.trim().toLowerCase();return f1.has(t)}function p1(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:_1(e.headers)??{}}}function _1(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!T1(t)))}function T1(e){const t=e.trim().toLowerCase();return l1.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function A1(e,t,r){const n=w1(e.presentation,t);return{account:y1(e,t,r),network:h1(e,t),...e.roomSocket&&e.authorizationContext?{roomSocket:{connect:(i,s)=>e.roomSocket.connect(i,Ue(s,t.signal))}}:{},...e.storage===void 0?{}:{storage:N1(e,t)},...e.storage===void 0?{}:I1(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function I1(e,t){const r=e.storage;return typeof r.storage.key!="function"||typeof r.storage.length!="number"?{}:{storageDiagnostics:{listRaw:n=>t.run(n.signal,()=>{const i=[];for(let s=0;s<r.storage.length;s+=1){const a=r.storage.key(s);if(a===null)continue;const c=r.storage.getItem(a);c!==null&&i.push({area:r.area,key:a,value:c})}return i})}}}function b1(e,t){return{getCurrentHref:()=>(t.assertActive(),e.environment.getCurrentHref()),isDevRuntime:()=>t.run(void 0,()=>e.environment.isDevRuntime()),...e.environment.setDocumentTitle===void 0?{}:{setDocumentTitle:r=>{t.assertActive(),e.environment.setDocumentTitle?.(r)}}}}function y1(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??d1();return{getAccountKey:(i,s,a)=>t.run(a.signal,c=>n(i,s,{...a,signal:c})),getCurrentUserId:i=>t.run(i.signal,s=>e.account.getCurrentUserId({signal:s})),ensureAuthenticated:i=>t.run(i.signal,s=>e.account.ensureAuthenticated({trustedUserGesture:i.trustedUserGesture,reason:i.reason,signal:s})),onChange:i=>{t.assertActive();const s=e.account.onChange(a=>{t.signal.aborted||i(a)});return r(s)}}}function N1(e,t){const r=e.storage.storage;return{getRaw:(n,i)=>t.run(i.signal,()=>{const s=r.getItem(n);return s===null?void 0:s}),setRaw:(n,i,s)=>t.run(s.signal,()=>{r.setItem(n,i)})}}function w1(e,t){if(!e)return;const r={};return e.close&&(r.close=n=>t.run(n.signal,i=>e.close({...n,signal:i}))),e.reload&&(r.reload=n=>t.run(n.signal,i=>e.reload({...n,signal:i}))),e.openAppPage&&(r.openAppPage=(n,i)=>t.run(i.signal,s=>e.openAppPage(n,{...i,signal:s}))),e.openWindow&&(r.openWindow=(n,i)=>t.run(i.signal,s=>e.openWindow(n,{...i,signal:s}))),e.applyOrientation&&(r.applyOrientation=(n,i)=>t.run(i.signal,s=>e.applyOrientation(n,{...i,signal:s}))),e.onViewportChange&&(r.onViewportChange=n=>{t.assertActive();const i=e.onViewportChange(()=>{t.signal.aborted||n()});let s=!1;const a=()=>{s||(s=!0,t.signal.removeEventListener("abort",a),i())};return t.signal.addEventListener("abort",a,{once:!0}),a}),e.getViewportMetrics&&(r.getViewportMetrics=()=>(t.assertActive(),e.getViewportMetrics())),e.getNavigationBarHeight&&(r.getNavigationBarHeight=()=>(t.assertActive(),e.getNavigationBarHeight())),e.setNavigationBarStyle&&(r.setNavigationBarStyle=(n,i)=>t.run(i.signal,s=>e.setNavigationBarStyle(n,{...i,signal:s}))),e.showShareMenu&&(r.showShareMenu=(n,i)=>t.run(i.signal,s=>e.showShareMenu(n,{...i,signal:s}))),e.setScreenshotChromeHidden&&(r.setScreenshotChromeHidden=(n,i)=>Hg(i)?e.setScreenshotChromeHidden(n,i):t.run(i.signal,s=>e.setScreenshotChromeHidden(n,{...i,signal:s}))),e.captureAndShare&&(r.captureAndShare=(n,i)=>t.run(i.signal,s=>e.captureAndShare(n,{...i,signal:s}))),e.showToast&&(r.showToast=(n,i)=>t.run(i.signal,s=>e.showToast(n,{...i,signal:s}))),e.showLoading&&(r.showLoading=(n,i)=>t.run(i.signal,s=>e.showLoading(n,{...i,signal:s}))),e.hideLoading&&(r.hideLoading=n=>t.run(n.signal,i=>e.hideLoading({...n,signal:i}))),e.vibrate&&(r.vibrate=(n,i)=>t.run(i.signal,s=>e.vibrate(n,{...i,signal:s}))),e.setClipboard&&(r.setClipboard=(n,i)=>t.run(i.signal,s=>e.setClipboard(n,{...i,signal:s}))),Object.keys(r).length===0?void 0:r}function D1(){const e=new AbortController;return{signal:e.signal,abort:t=>{e.signal.aborted||e.abort(t)},assertActive:t=>{const r=[e.signal,t].find(n=>n?.aborted);if(r)throw $i(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(l=>l.aborted);if(i)throw $i(i.reason);const s=new AbortController;let a;const c=new Promise((l,h)=>{a=h}),u=n.map(l=>{const h=()=>{s.signal.aborted||s.abort(l.reason),a($i(l.reason))};return l.addEventListener("abort",h,{once:!0}),{listener:h,source:l}});let d;try{d=Promise.resolve(r(s.signal))}catch(l){d=Promise.reject(l)}try{const l=await Promise.race([d,c]),h=n.find(f=>f.aborted);if(h)throw $i(h.reason);return l}finally{for(const{listener:l,source:h}of u)h.removeEventListener("abort",l)}}}}function $i(e){return new DOMException("Web Host operation aborted","AbortError")}async function S1(e){const t=D1(),r=new Set;let n=!1;const i=f=>{if(n||t.signal.aborted)return po(f),()=>{};let _=!0;const p=()=>{_&&(_=!1,r.delete(p),po(f))};return r.add(p),p},s=()=>a(e.signal.reason),a=f=>{if(!n){n=!0,e.signal.removeEventListener("abort",s),t.abort(f);for(const _ of[...r])_();e.onDispose&&po(e.onDispose)}};e.signal.addEventListener("abort",s,{once:!0}),e.signal.aborted&&a(e.signal.reason);const c=A1(e,t,i);c.storage?.getRaw&&c.storage.setRaw&&(c.scopedStorage=im({storage:c.storage,diagnostics:c.storageDiagnostics,coordinationKey:e.storage.storage,lock:sm,resolveScope:async()=>nm((await h()).configuration)}));const u=wf(c,{hostCapabilities:e.hostCapabilities,hasUserDataPresentation:e.userDataPresentation!==void 0,hasUserDataSettings:e.userDataPresentation?.openDataPermissions!==void 0}),d=b1(e,t);let l;const h=()=>l??=t.run(void 0,f=>e.resolveLaunch(f));return{platform:"web",ports:c,environment:d,resolveLaunch:h,...e.authorizationContext?{authorizationContext:e.authorizationContext}:{},...e.authPresentation===void 0?{}:{authPresentation:O1(e.authPresentation,t)},...e.userDataPresentation===void 0?{}:{userDataPresentation:M1(e.userDataPresentation,t)},hostCapabilities:u.effectiveCapabilities,dispose:a}}function po(e){try{e()}catch{}}function O1(e,t){return{...e.confirmFollowAuthor?{confirmFollowAuthor:r=>t.run(r.signal,n=>e.confirmFollowAuthor({...r,signal:n}))}:{},confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}function M1(e,t){return{...e.openDataPermissions?{openDataPermissions:r=>t.run(r.signal,n=>e.openDataPermissions({...r,signal:n}))}:{},confirmDataPermission:r=>t.run(r.signal,n=>e.confirmDataPermission({...r,signal:n}))}}function R1(e){const t=`hb-game-saves-${crypto.randomUUID()}`,r=u=>`hb-sdk:game-save-cache:${u}`;let n,i;const s=new Promise((u,d)=>{n=u,i=d});let a;const c=new Promise(u=>{a=u});return e.signal.addEventListener("abort",a,{once:!0}),e.signal.aborted&&a(),e.locks.request(r(t),async()=>{let u;try{u=await e.getRoot();const d=await e.locks.request("hb-sdk:game-save-cache:gc",async()=>{e.signal.throwIfAborted();for await(const[l,h]of u)h.kind!=="directory"||!/^hb-game-saves-[a-f0-9-]{36}$/.test(l)||await e.locks.request(r(l),{ifAvailable:!0},async f=>{f&&await bl(u,l)});return e.signal.throwIfAborted(),u.getDirectoryHandle(t,{create:!0})});e.signal.throwIfAborted(),n(d),await c}catch(d){i(d)}finally{e.signal.removeEventListener("abort",a),u&&await bl(u,t).catch(()=>{})}}).catch(i),s.catch(()=>{}),s}async function bl(e,t){for(let r=0;;r++)try{await e.removeEntry(t,{recursive:!0});return}catch(n){if(n instanceof DOMException&&n.name==="NotFoundError")return;if(!(n instanceof DOMException)||n.name!=="NoModificationAllowedError"||r>=4)throw n;await new Promise(i=>setTimeout(i,25*(r+1)))}}const _o=8*1024*1024,C1=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),L1="/__hb_sdk__/game-save-download",dt=(e,t)=>({code:e,message:t});function P1(e){const t=e.getRoot??(navigator.storage?.getDirectory?()=>navigator.storage.getDirectory():void 0),r=e.locks??navigator.locks,n=e.supportsWritable??(typeof FileSystemFileHandle<"u"&&typeof FileSystemFileHandle.prototype.createWritable=="function");if(!t||!r||!n)return;const i=R1({getRoot:t,locks:r,signal:e.signal}),s=new WeakMap,a=new WeakSet,c=p=>{p.signal.throwIfAborted(),p.lifecycle!=="cleanup"&&e.signal.throwIfAborted()},u=()=>i;function d(p){if(!/^\.hb-game-saves\/[a-zA-Z0-9_-]+\.zip$/.test(p))throw dt("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存");return p.slice(15)}async function l(p,y){c(y);const w=d(p);try{return await(await u()).getFileHandle(w)}catch(N){throw N instanceof DOMException&&N.name==="NotFoundError"?dt("FILE_NOT_FOUND","存档缓存不存在"):N}}function h(p){const y={kind:"file",mode:"readwrite",name:p.split("/").at(-1),async create(w,N){c(N);const O=d(p),I=await u();if(w.exclusive)try{throw await I.getFileHandle(O),dt("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(H){if(!(H instanceof DOMException&&H.name==="NotFoundError"))throw H}c(N),await I.getFileHandle(O,{create:!0}),c(N)},async remove(w){c(w);const N=d(p);if(i)try{await(await i).removeEntry(N)}catch(O){if(!(O instanceof DOMException&&O.name==="NotFoundError"))throw O}},async read(w){const N=await(await l(p,w)).getFile();if(N.size>_o)throw dt("FILE_TOO_LARGE","存档文件超过 8 MiB");const O=new Uint8Array(await N.arrayBuffer());try{return c(w),O}catch(I){throw O.fill(0),I}},async write(){throw dt("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(w){const N=await(await l(p,w)).getFile();return c(w),{kind:"file",size:N.size,modifiedAt:N.lastModified}}};return s.set(y,p),y}const f=async()=>{throw dt("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},_={kind:"directory",mode:"readwrite",name:"",file:h,directory(p){return{..._,name:p,async create(y,w){if(c(w),p!==".hb-game-saves")return f();await u(),c(w)}}},create:f,stat:f,list:f};return{files:{sandbox:_},transfer:{network:{async open(p,y){if(c(y),!If(p))throw dt("METHOD_FORBIDDEN","仅支持受控存档下载");const w=await(e.fetch??fetch)(L1,{method:"POST",credentials:"same-origin",redirect:"error",headers:{"content-type":"application/json","x-hb-sdk-csrf":e.csrfToken()},body:JSON.stringify(p),signal:AbortSignal.any([y.signal,e.signal,AbortSignal.timeout(6e4)])});if(!w.ok){const N=await w.json().catch(()=>({}));throw dt(N.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return a.add(w),{status:w.status,headers:Object.fromEntries(Array.from(w.headers).filter(([N])=>C1.has(N)).map(([N,O])=>[N,[O]])),body:w}},async release(p){a.delete(p),await p.body?.cancel()}},files:{async writeResource(p,y,w,N){let O,I;try{c(N);const H=s.get(p);if(!H||!a.delete(y))throw dt("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(w.mode!=="replace-existing")throw dt("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(O=await(await l(H,N)).createWritable(),!y.body)throw dt("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");I=y.body.getReader();let M=0;for(;;){c(N);const x=await I.read().catch(v=>{throw c(N),dt(v instanceof DOMException&&v.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(c(N),x.done)break;if(M+=x.value.byteLength,M>Math.min(w.maxBytes??_o,_o))throw dt("FILE_TOO_LARGE","存档文件超过 8 MiB");await O.write(new Uint8Array(x.value)),N.onProgress(M)}if(w.expectedBytes!==void 0&&M!==w.expectedBytes)throw dt("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return c(N),await O.close(),O=void 0,{committedBytes:M}}catch(H){throw H instanceof DOMException&&H.name==="QuotaExceededError"?dt("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):H}finally{await I?.cancel().catch(()=>{}),I||await y.body?.cancel().catch(()=>{}),await O?.abort().catch(()=>{}),a.delete(y)}}}}}}function Vt(e,t){throw{code:e,message:t}}function zn(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.keys(r).sort().map(n=>[n,r[n]])):r)}function v1(e){return{declaredPermissions:e.declaredPermissions??{},platforms:[...e.platforms??[]].sort(),runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy}}function k1(e){const t=e.now??Date.now;let r;const n=new Map,i=()=>{r=void 0};e.signal.addEventListener("abort",i,{once:!0});function s(){if(e.signal.aborted)throw new DOMException("调试会话已结束","AbortError");const u=e.readState();u.userId||(i(),Vt("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:d,browser:l}=u,h=ZE(d.developmentSnapshot);(d.source!=="remote"||!d.miniProgramId||!d.localDevLaunchToken||!d.expiresAt||d.expiresAt<=t()||!h||!d.developmentSnapshotDigest||!/^[a-f0-9]{64}$/.test(d.developmentSnapshotDigest))&&(i(),Vt("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态"));let f;try{f=Tf({...h,declared_permissions:l.declaredPermissions??{},platforms:l.platforms??[]})}catch{}(l.source!=="remote"||l.miniProgramId!==d.miniProgramId||l.devSessionId!==h.session_id||d.devSessionId!==h.session_id||d.contextRevision!==h.revision||f!==d.developmentSnapshot||zn(l.runtimePermissions)!==zn(d.runtimePermissions)||zn(l.networkPolicy)!==zn(d.networkPolicy))&&(i(),Vt("AUTHORIZATION_CONTEXT_CHANGED","开发快照正在更新,请稍后重试"));const _={mini_program_id:d.miniProgramId,launch_kind:"remote-dev",version_identity:`dev:${h.session_id}:${h.revision}`,sdk_version:h.sdk_version,local_dev_launch_token:d.localDevLaunchToken,dev_snapshot_digest:d.developmentSnapshotDigest,dev_network_enabled:u.networkEnabled};return{body:_,key:zn([u.userId,u.accountRevision,_,l.contextRevision,v1(l)]),expiresAt:d.expiresAt}}async function a(u,d){const l=d.signal;let h;try{h=await e.request({source:"runtime-private",credentials:"heybox-session",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:"heybox.user_miniprogram.runtime.auth.context.post",path:"/user_miniprogram/runtime/auth/context",channel:"api"},method:"POST",bodyEncoding:"form",data:u.body,timeout:1e4},d)}catch(w){l.throwIfAborted();const N=w&&typeof w=="object"&&"code"in w?String(w.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(N)&&Vt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(N)||w instanceof DOMException&&["AbortError","TimeoutError"].includes(w.name))throw w;Vt("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}l.throwIfAborted(),await e.refreshAccount(l),l.throwIfAborted(),s().key!==u.key&&Vt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const f=h.data;(h.status===401||f?.status==="login"||f?.status==="relogin")&&Vt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(h.status!==200||f?.status!=="ok")&&Vt("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const _=f.result,p=Number(_?.expires_at)*1e3;(typeof _?.token!="string"||!_.token.trim()||!Number.isSafeInteger(_?.expires_at)||!Number.isSafeInteger(p)||p<=t()||!["legacy","local","server"].includes(String(_.user_data_mode)))&&Vt("INVALID_RESPONSE","开发运行授权响应无效");const y={token:_.token,expiresAt:Math.min(p,u.expiresAt),steamAccount:_.steam_account===!0,userDataMode:_.user_data_mode};return r={key:u.key,value:y},y}const c={async get(u){const d=AbortSignal.any([u.signal,e.signal]);d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted();const l=s();if(r?.key===l.key&&r.value.expiresAt>t()+3e4)return r.value;i();let h=n.get(l.key);if(!h||h.controller.signal.aborted){const _=new AbortController,p=a(l,{...u,signal:AbortSignal.any([_.signal,e.signal])});h={promise:p,controller:_,users:0},n.set(l.key,h);const y=h;p.finally(()=>{n.get(l.key)===y&&n.delete(l.key)}).catch(()=>{})}h.users++;let f;try{const _=await Promise.race([h.promise,new Promise((p,y)=>{f=()=>y(d.reason),d.addEventListener("abort",f,{once:!0}),d.aborted&&f()})]);return d.throwIfAborted(),s().key!==l.key&&Vt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),_}finally{d.removeEventListener("abort",f),--h.users===0&&h.controller.abort()}}};return{...c,async resolveLaunchConfiguration(u,d){const l=AbortSignal.any([d.signal,e.signal]);l.throwIfAborted(),await e.refreshAccount(l),l.throwIfAborted();const h=e.readState();if(!u.canonicalIdentity?.miniProgramId||!h.userId||!h.signed.localDevLaunchToken)return u;const f=await c.get({...d,signal:l});return{...u,runtimeFeatures:{steamAccount:f.steamAccount,userDataMode:f.userDataMode}}}}}function yl(e,t){return Ii(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId:void 0,developmentSnapshot:typeof e.developmentSnapshot=="string"?e.developmentSnapshot:void 0,developmentSnapshotDigest:typeof e.developmentSnapshotDigest=="string"?e.developmentSnapshotDigest:void 0,localDevLaunchToken:typeof e.localDevLaunchToken=="string"?e.localDevLaunchToken:void 0,runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,...e.source==="remote"&&e.firstParty===!0?{firstParty:!0}:{},publishedRuntimePermissions:e.publishedRuntimePermissions,warning:typeof e.warning=="string"?e.warning:void 0,declaredPermissions:Ii(e.declaredPermissions)?e.declaredPermissions:void 0,platforms:Array.isArray(e.platforms)?e.platforms.filter(r=>["android","ios","ohos","windows","macos","linux"].includes(String(r))):void 0,localDevGrant:e.localDevGrant,contextRevision:typeof e.contextRevision=="number"?e.contextRevision:void 0,devSessionId:typeof e.devSessionId=="string"?e.devSessionId:void 0,expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0,companionManifestSha256:typeof e.companionManifestSha256=="string"?e.companionManifestSha256:void 0}:{source:"anonymous",runtimePermissions:t}}function ti(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=cf(e.localDevGrant);return!r.valid||!e.devSessionId?.trim()||!Number.isSafeInteger(e.contextRevision)||e.contextRevision!==r.grant.revision||!e.expiresAt||!Number.isFinite(e.expiresAt)||e.source!=="remote"&&e.expiresAt<=t?{...e,localDevGrant:void 0,warning:"本地临时授权无效或已过期,已降权"}:{...e,...e.expiresAt<=t?{source:"anonymous",localDevLaunchToken:void 0,expiresAt:t+3e4}:{},localDevGrant:oE({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,revision:r.grant.revision,eligiblePermissionKeys:e.platforms?.some(n=>["windows","macos","linux"].includes(n))?["network","companion","appProtocol"]:["network","appProtocol"]})}}function x1(e){if(!Ii(e)||!Nl(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!Ii(t)||!Nl(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const U1={networkRequest:{status:"disabled",useOfficialDomain:!1}};function iu(e){const t=ft(e.localDevGrant?Uc({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}).runtimePermissions:e.runtimePermissions),r=t.permissions.network;return t.valid&&r?{networkRequest:{status:r.status,useOfficialDomain:r.config.useOfficialDomain===!0}}:B1()}function Im(e,t,r){return r?.localDevGrant?Uc({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:H1(e,t,t.networkRequest.useOfficialDomain)}function B1(){return{networkRequest:{...U1.networkRequest}}}function H1(e,t,r){const n=ft(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const a of zr){const c=n.permissions[a];c&&i.push(a==="network"?{key:a,status:t.networkRequest.status,config:{useOfficialDomain:r}}:a==="user_game_data"||a==="post"?{key:a,status:c.status,config:{...c.config}}:{key:a,status:c.status,config:{}})}const s=Ii(e)&&typeof e.revision=="number"&&Number.isInteger(e.revision)&&e.revision>=0?e.revision:void 0;return{schema_version:1,...s===void 0?{}:{revision:s},entries:i}}function Ii(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Nl(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function F1(e){let t,r=!1,n=!1,i;return{invalidate(c){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(c,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=s().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function s(){let c={ok:!0};for(;r&&!n;){r=!1;const u=new AbortController;t=u;let d;try{d=await e.fetch(u.signal)}catch(h){c={ok:!1},!n&&!u.signal.aborted&&a(h);continue}finally{t===u&&(t=void 0)}if(n)return{ok:!1};let l;try{l=e.apply(d)}catch(h){c={ok:!1},n||a(h);continue}if(n)return{ok:!1};if(c={ok:!0},!!e.hasChanged(l))try{await e.onChanged(l)}catch(h){c={ok:!1},n||a(h)}}return n?{ok:!1}:c}function a(c){try{e.onError(c)}catch{}}}function z1(e){return F1({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 j1(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,s;return{schedule:a,reset(){n=t,c()},dispose(){i||(i=!0,c())}};function a(){i||e.isDisposed()||(c(),s=e.timers.setTimeout(async()=>{s=void 0;let u;try{u=await e.invalidate()}catch{u={ok:!1}}if(!(i||e.isDisposed())){if(u.ok){n=t,e.connectEvents();return}n=Math.min(n*2,r),a()}},n))}function c(){s!==void 0&&e.timers.clearTimeout(s),s=void 0}}const To=new WeakMap;function su(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}const{root:n,signal:i}=e;To.set(n,document.activeElement);const s=[...n.querySelectorAll("button[data-action]")];n.dataset.hostDialog="true",n.style.zIndex="40";const a=()=>[...document.querySelectorAll("[data-host-dialog]")].at(-1);n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-label",e.title);let c;const u=()=>{i?.removeEventListener("abort",l),document.removeEventListener("keydown",f);const p=a()===n;if(n.remove(),p){const y=a();y&&(y.inert=!1,y.removeAttribute("aria-hidden"));let w=To.get(n)??null;for(;w instanceof HTMLElement&&!w.isConnected;){const N=w.closest("[data-host-dialog]");w=N?To.get(N)??null:null}w instanceof HTMLElement&&(!y||y.contains(w))?w.focus():y?.querySelector("button")?.focus()}},d=e0({kind:"dialog",mode:e.mode??"simulated",title:e.title,method:e.method,...e.callId?{callId:e.callId}:{},actions:s.map(p=>p.textContent?.trim()??"")},p=>{u(),c!==void 0?t(c):r(i?.reason??new DOMException(`宿主弹窗已${p}`,"AbortError"))});function l(){d.finish("cancelled")}function h(p){c=p,d.finish(p===e.cancelAction?"cancelled":"confirmed")}function f(p){if(a()!==n||(p.key==="Escape"&&e.cancelAction&&(p.preventDefault(),h(e.cancelAction)),p.key!=="Tab"||s.length===0))return;const y=s[0],w=s.at(-1);p.shiftKey&&document.activeElement===y?(p.preventDefault(),w.focus()):!p.shiftKey&&document.activeElement===w&&(p.preventDefault(),y.focus())}if(!d.active)return;if(i?.aborted){l();return}for(const p of s)p.addEventListener("click",()=>h(p.dataset.action));n.addEventListener("click",p=>{p.target===n&&e.cancelAction&&h(e.cancelAction)}),n.dataset.interactionId=d.interactionId;const _=a();_&&(_.inert=!0,_.setAttribute("aria-hidden","true")),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n),i?.addEventListener("abort",l,{once:!0}),document.addEventListener("keydown",f),s[0]?.focus(),i?.aborted?l():e.onShown?.()})}function Nt(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}const wl="hb-sdk-action-dialog-style";async function Ga(e){await bm(e)}async function V1(e){return await bm({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function bm(e){W1();const t=document.createElement("div");return t.className="hb-sdk-action-dialog",t.innerHTML=`
13
- <div class="hb-sdk-action-dialog__panel">
14
- <h2>${Nt(e.title)}</h2>
15
- <pre class="hb-sdk-action-dialog__detail">${Nt(e.detail)}</pre>
16
- <div class="hb-sdk-action-dialog__actions">
17
- ${e.confirmation?'<button type="button" data-action="cancel">取消</button>':""}
18
- <button type="button" class="primary" data-action="confirm">${e.confirmation?"关注":"确定"}</button>
19
- </div>
20
- </div>`,await su({root:t,title:e.title,method:e.method??"host.action",signal:e.signal,callId:e.callId,mode:e.mode,...e.confirmation?{cancelAction:"cancel"}:{}})==="confirm"}async function G1(e,t){await Ga({method:"navigation.openAppPage",title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+An(e.params)].join(`
21
- `),signal:t.signal,callId:t.requestId})}async function Y1(e,t){await Ga({method:"navigation.openAppPage",title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+An(e.extra)].join(`
22
- `),signal:t.signal,callId:t.requestId})}async function q1(e,t){await Ga({method:"share.showShareMenu",title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+An(e.channel),"post: "+An(e.post)].join(`
23
- `),signal:t.signal,callId:t.requestId})}async function Q1(e,t){await Ga({method:"share.screenshot",title:"截图分享",detail:["rect: "+An(e.rect),"post: "+An(e.post)].join(`
24
- `),signal:t.signal,callId:t.requestId})}function An(e){return JSON.stringify(e,null,2)}function W1(){if(document.getElementById(wl))return;const e=document.createElement("style");e.id=wl,e.textContent=`
25
- .hb-sdk-action-dialog {
26
- position: absolute;
27
- inset: 0;
28
- display: grid;
29
- place-items: center;
30
- padding: 24px;
31
- background: rgba(15, 23, 42, 0.45);
32
- }
33
-
34
- .hb-sdk-action-dialog__panel {
35
- width: min(420px, 100%);
36
- border-radius: 12px;
37
- padding: 20px;
38
- background: #fff;
39
- box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
40
- }
41
-
42
- .hb-sdk-action-dialog__panel h2 {
43
- margin: 0 0 8px;
44
- font-size: 18px;
45
- }
46
-
47
- .hb-sdk-action-dialog__detail {
48
- margin: 0 0 16px;
49
- max-height: 40vh;
50
- overflow: auto;
51
- color: #1f2933;
52
- font-family: inherit;
53
- font-size: 12px;
54
- line-height: 1.6;
55
- white-space: pre-wrap;
56
- overflow-wrap: anywhere;
57
- word-break: break-word;
58
- }
59
-
60
- .hb-sdk-action-dialog__actions {
61
- display: flex;
62
- justify-content: flex-end;
63
- gap: 8px;
64
- }
65
-
66
- .hb-sdk-action-dialog__actions button {
67
- min-height: 36px;
68
- border: 1px solid #cad5e2;
69
- border-radius: 6px;
70
- padding: 0 12px;
71
- background: #fff;
72
- cursor: pointer;
73
- }
74
-
75
- .hb-sdk-action-dialog__actions .primary {
76
- border-color: #2563eb;
77
- color: #fff;
78
- background: #2563eb;
79
- }
80
- `,document.head.appendChild(e)}const $1={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};async function K1(e){const t=document.createElement("div");return t.className="hb-sdk-auth-dialog",t.innerHTML=`
81
- <div class="hb-sdk-auth-dialog__panel">
82
- <h2>授权请求</h2>
83
- <p class="hb-sdk-auth-dialog__app">${Nt(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
84
- <ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(n=>`<li>${Nt($1[n]||n)}</li>`).join("")}</ul>
85
- ${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${Nt(e.userProfile.nickname)}</p>`:""}
86
- <div class="hb-sdk-auth-dialog__actions">
87
- <button type="button" data-action="deny">拒绝</button>
88
- <button type="button" class="primary" data-action="allow">允许</button>
89
- </div>
90
- </div>
91
- `,await su({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function Z1(e){const t=e.miniProgramName?.trim();return{launchUrl:e.launchUrl,...e.locationBasePath!==void 0?{locationBasePath:e.locationBasePath}:{},...t?{miniProgramPresentation:{name:t}}:{},sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:hu,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,firstParty:e.firstParty===!0,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:Va},sdkVersion:hu},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const Dl="hb-sdk-user-data-dialog-style",X1=new Map(Ma.map(e=>[e.key,e.name]));function J1(e){return(dr(e)?X1.get(e):void 0)??"游戏资料"}function eS(e){return e==="upload"?"可上传":"无网络权限"}async function tS(e){nS();const t=e.miniProgramName?.trim()||"当前小程序",r=J1(e.resource),n=`“${t}”想读取你的${r}`,i=eS(e.egress),s=pg[e.egress],a=e.egress==="upload"?"↑":"⊘",c=document.createElement("div");c.className="hb-sdk-user-data-dialog",c.innerHTML=`
92
- <div class="hb-sdk-user-data-dialog__panel">
93
- <h2>${Nt(n)}</h2>
94
- <dl class="hb-sdk-user-data-dialog__meta">
95
- <dt>范围</dt><dd>${Nt(e.scopeText)}</dd>
96
- <dt>用途</dt><dd>${Nt(e.purposeText)}</dd>
97
- </dl>
98
- <p class="hb-sdk-user-data-dialog__egress" data-egress="${Nt(e.egress)}">
99
- <span class="hb-sdk-user-data-dialog__egress-label" aria-hidden="true">${Nt(a)}</span>
100
- <span class="hb-sdk-user-data-dialog__egress-tag">${Nt(i)}</span>
101
- <span>${Nt(s)}</span>
102
- </p>
103
- <p class="hb-sdk-user-data-dialog__browser-note">读取当前登录黑盒账号的真实资料。许可仅适用于本浏览器,不会同步到手机或其他客户端;来源登录需另行完成。</p>
104
- <div class="hb-sdk-user-data-dialog__actions">
105
- <button type="button" data-action="deny">拒绝</button>
106
- <button type="button" data-action="session">本次使用允许</button>
107
- ${e.canPersist===!1?"":'<button type="button" class="primary" data-action="persistent">在此浏览器上始终允许</button>'}
108
- </div>
109
- </div>
110
- `;const u=await su({root:c,title:n,method:"user.dataPermission.confirm",mode:"browser",signal:e.signal,...e.onShown?{onShown:e.onShown}:{},cancelAction:"cancelled"});return{decision:rS(u)}}function rS(e){return e==="deny"||e==="session"||e==="persistent"?e:"cancelled"}function nS(){if(document.getElementById(Dl))return;const e=document.createElement("style");e.id=Dl,e.textContent=`
111
- .hb-sdk-user-data-dialog {
112
- position: absolute;
113
- inset: 0;
114
- display: grid;
115
- place-items: center;
116
- padding: 24px;
117
- background: rgba(15, 23, 42, 0.45);
118
- }
119
-
120
- .hb-sdk-user-data-dialog__panel {
121
- width: min(440px, 100%);
122
- border-radius: 12px;
123
- padding: 20px;
124
- background: #fff;
125
- box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
126
- }
127
-
128
- .hb-sdk-user-data-dialog__panel h2 {
129
- margin: 0 0 12px;
130
- font-size: 17px;
131
- line-height: 1.45;
132
- color: #1f2933;
133
- overflow-wrap: anywhere;
134
- }
135
-
136
- .hb-sdk-user-data-dialog__meta {
137
- display: grid;
138
- grid-template-columns: auto 1fr;
139
- gap: 4px 10px;
140
- margin: 0 0 12px;
141
- font-size: 12px;
142
- line-height: 1.6;
143
- }
144
-
145
- .hb-sdk-user-data-dialog__meta dt {
146
- color: #7b8794;
147
- white-space: nowrap;
148
- }
149
-
150
- .hb-sdk-user-data-dialog__meta dd {
151
- white-space: pre-wrap;
152
- margin: 0;
153
- color: #1f2933;
154
- overflow-wrap: anywhere;
155
- }
156
-
157
- .hb-sdk-user-data-dialog__egress {
158
- display: flex;
159
- flex-wrap: wrap;
160
- align-items: baseline;
161
- gap: 6px;
162
- margin: 0 0 10px;
163
- padding: 10px 12px;
164
- border: 1px solid #cad5e2;
165
- border-radius: 8px;
166
- font-size: 12px;
167
- line-height: 1.6;
168
- color: #1f2933;
169
- }
170
-
171
- .hb-sdk-user-data-dialog__egress[data-egress="upload"] {
172
- border-color: #e0b34d;
173
- background: #fff8e6;
174
- }
175
-
176
- .hb-sdk-user-data-dialog__egress[data-egress="no_network"] {
177
- border-color: #9fb3c8;
178
- background: #f2f6fa;
179
- }
180
-
181
- .hb-sdk-user-data-dialog__egress-label {
182
- font-weight: 700;
183
- }
184
-
185
- .hb-sdk-user-data-dialog__egress-tag {
186
- font-weight: 700;
187
- white-space: nowrap;
188
- }
189
-
190
- .hb-sdk-user-data-dialog__browser-note {
191
- margin: 0 0 16px;
192
- font-size: 11px;
193
- line-height: 1.6;
194
- color: #7b8794;
195
- }
196
-
197
- .hb-sdk-user-data-dialog__actions {
198
- display: flex;
199
- flex-wrap: wrap;
200
- justify-content: flex-end;
201
- gap: 8px;
202
- }
203
-
204
- .hb-sdk-user-data-dialog__actions button {
205
- min-height: 36px;
206
- border: 1px solid #cad5e2;
207
- border-radius: 6px;
208
- padding: 0 12px;
209
- background: #fff;
210
- color: #1f2933;
211
- cursor: pointer;
212
- }
213
-
214
- .hb-sdk-user-data-dialog__actions .primary {
215
- border-color: #2563eb;
216
- color: #fff;
217
- background: #2563eb;
218
- }
219
- `,document.head.appendChild(e)}function iS(e){let t,r,n,i,s,a=0,c=0,u=0,d=!1,l=Promise.resolve();const h=new Set,f=()=>{const N=e.resolveScope();return N?JSON.stringify(N):void 0},_=()=>{if(!d)for(const N of h)N()},p=async()=>{if(d||u)return;const N=t,O=f(),I=++a;if(!N||!O){r=void 0,i=void 0,_();return}try{const H=await N.getSnapshot();if(d||I!==a||t!==N||O!==f())return;r=H,n=O,i=void 0}catch(H){if(d||I!==a||t!==N||O!==f())return;r=void 0,s=O,i=H instanceof Error?H.message:"许可状态不可用"}_()},y=N=>{const O=t,I=f(),H=c;if(d||!O||!I)return Promise.resolve();const Q=++a;u++;const M=l.then(async()=>{if(!(d||c!==H||I!==f()))try{const x=await N(O);if(d||Q!==a||c!==H||I!==f())return;r=x,n=I,i=void 0}catch(x){if(d||Q!==a||c!==H||I!==f())return;r=void 0,s=I,i=x instanceof Error?x.message:"许可设置失败"}}).finally(()=>{c===H&&u--,_()});return l=M,M},w=()=>{c++,a++,u=0,l=Promise.resolve(),t=void 0,r=void 0,i=void 0};return{snapshot(){const N=f(),O=N&&N===n?r:void 0,I=e.declared?.();return{scenario:"unknown",dataScenario:"unknown",egressTier:e.egressTier(),declaredSource:I?.source??"manifest",permissionStateReady:O!==void 0,stateError:N&&N===s?i:void 0,simulatedSession:[],resources:Ma.map(H=>{const Q=O?.resources.find(x=>x.resource===H.key),M=Q?.allowed===!0;return{resource:H.key,name:H.name,declared:I?.resources.includes(H.key)??!1,decision:Q?.decision??"ask",revision:Q?.revision??0,sessionAllowed:Q?.sessionAllowed??!1,sessionSimulated:!1,licensed:M,...M?{sourceStatus:"unknown"}:{}}})}},subscribe(N){return d||h.add(N),()=>h.delete(N)},bind(N){d||(w(),t=N,p())},refresh:p,revokeSession:()=>y(N=>N.revokeSession()),resetAll:()=>y(N=>N.resetAll()),clearSession(){w(),_()},dispose(){d=!0,w(),h.clear()}}}function sS(e){const t="hb_user_game_data_consent_",r="hb_browser_real_user_game_data_consent_",n=i=>i.startsWith(t)?`${r}${i.slice(t.length)}`:i;return{getItem(i){return e.getItem(n(i))},setItem(i,s){e.setItem(n(i),s)},get length(){return e.length},key(i){const s=e.key(i);return s?.startsWith(t)?null:s?.startsWith(r)?`${t}${s.slice(r.length)}`:s}}}function aS(e){const t=ft(e.runtimePermissions);let r={};return t.valid&&t.permissions.user_game_data?.status==="enabled"?r=pi(t.permissions.user_game_data.config.resources):e.runtimePermissions===void 0&&e.declaredPermissions?.user_game_data?.enabled&&(r=pi(e.declaredPermissions.user_game_data.resources)),{resources:iE(r),source:"manifest"}}const oS=Object.freeze({user_game_data_permission_show:["entry","reason"],user_game_data_permission_result:["choice","apply_result"],user_game_data_permission_manage:["operation","apply_result","succeeded_count","failed_count"],user_game_data_action:["stage","action_type","outcome","duration_ms"],user_game_data_access_result:["api","trigger","status","error_code","failure_stage","duration_ms","cache_hit"]}),cS="host.userDataTelemetry",Sl=80;function uS(e){return{method:cS,detail:{...e.payload,eventName:e.name,message:dS(e)}}}function dS(e){const t=oS[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}: ${ym(i)}`)}return[e.name,...r].join(" · ")}function ym(e){let t;if(typeof e=="string")t=e;else if(typeof e=="number"||typeof e=="boolean")t=String(e);else if(Array.isArray(e))t=e.map(r=>ym(r)).join(",");else try{t=JSON.stringify(e)??""}catch{t="[无法序列化]"}return t.length>Sl?`${t.slice(0,Sl)}…`:t}const lS=44;function fS(e){const t=()=>e.isCapsuleHidden?.()?0:lS,r=()=>{const n=e.getDeviceMetrics?.();return n?{windowWidth:n.screenWidth,windowHeight:n.screenHeight,screenWidth:n.screenWidth,screenHeight:n.screenHeight,pixelRatio:n.pixelRatio,safeArea:{top:n.safeAreaInsets.top+t(),right:n.screenWidth-n.safeAreaInsets.right,bottom:n.screenHeight-n.safeAreaInsets.bottom,left:n.safeAreaInsets.left}}:{windowWidth:window.innerWidth,windowHeight:window.innerHeight,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}};return{...e.applyDisplay?{applyOrientation:async(n,i)=>(await e.applyDisplay(n,i.signal),{supported:!0})}:{},...e.onViewportChange?{onViewportChange:e.onViewportChange}:{},close:async()=>{await e.close()},reload:async()=>{await e.reload()},getViewportMetrics:()=>e.getViewportMetrics?.()??r(),getNavigationBarHeight:()=>{if(e.getNavigationBarHeight)return e.getNavigationBarHeight();const n=e.getDeviceMetrics?.().statusBarHeight;return n===void 0?0:n+t()},setNavigationBarStyle:n=>{document.documentElement.dataset.navigationBarStyle=n,e.onNavigationBarStyleChange?.(n)},setClipboard:async({text:n})=>{await navigator.clipboard.writeText(n)},showToast:s0,showLoading:i0,hideLoading:n0,vibrate:r0,openAppPage:G1,openWindow:Y1,showShareMenu:q1,captureAndShare:Q1,setScreenshotChromeHidden:t0}}const Ol=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],Ki=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Ml={"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 hS{port;presentation;now;schedule;clearSchedule;onDiagnostic;preparations=new Map;sessions=new Map;eventSink;sessionEventListeners=new Set;nextSessionId=0;constructor(t={}){this.now=t.now??Date.now,this.schedule=t.schedule??((r,n)=>setTimeout(r,n)),this.clearSchedule=t.clearSchedule??(r=>clearTimeout(r)),this.onDiagnostic=t.onDiagnostic??(()=>{}),this.port={getInfo:async r=>this.getInfo(r),getPreparationStatus:async r=>this.getPreparationStatus(r),prepare:(r,n)=>this.prepare(r,n),cancelPreparation:async r=>this.cancelPreparation(r),getActiveSession:async r=>this.getActiveSession(r),launch:async r=>this.launch(r),write:async r=>this.write(r),closeStdin:async r=>this.closeStdin(r),terminate:async r=>this.terminate(r),ackOutput:async r=>this.ackOutput(r),openAttachment:async r=>this.openAttachment(r),showNotification:async r=>this.showNotification(r),onSessionEvent:r=>(this.sessionEventListeners.add(r),()=>this.sessionEventListeners.delete(r))},this.presentation={confirmCompanionOperation:async({action:r,companion:n})=>{const i=n.alias===`${r}-cancel`;return this.diagnostic(`authorization.${i?"cancelled":"granted"}`,n.alias,{action:r}),i?{status:"cancelled"}:{status:"granted"}}}}bindEventSink(t){this.eventSink=t,this.diagnostic(t?"runtime.connected":"runtime.disconnected")}reset(t){const r=t?[t]:[...Ol];for(const n of r){const i=this.preparations.get(n);for(const s of i?.operation?.timers??[])this.clearSchedule(s);i?.operation?.reject(it("COMPANION_PREPARATION_CANCELLED","固定 Fake 已重置")),this.preparations.delete(n),this.sessions.delete(n)}this.diagnostic("reset",t)}getInfo(t){const r=this.readAlias(t);return{alias:r,displayName:`Browser Fake: ${r}`,target:r==="os-blocked"?"macos-arm64":"windows-x64",capabilities:Ml[r],archiveBytes:12,signatureStatus:"unsigned"}}getPreparationStatus(t){const r=this.readAlias(t);return this.preparations.get(r)?.status??{state:"not-prepared"}}prepare(t,r){const n=this.readAlias(t),i=this.preparations.get(n);if(i?.status.state==="ready")return Promise.resolve(this.getInfo(n));if(i?.operation)return i.operation.listeners.add(r.onProgress),this.diagnostic("prepare.joined",n),r.onProgress(i.status.state==="preparing"?i.status.progress:Ki[0]),i.operation.promise;let s,a;const c=new Promise((d,l)=>{s=d,a=l}),u={cancelled:!1,listeners:new Set([r.onProgress]),promise:c,reject:a,resolve:s,timers:new Set};{const d={status:{state:"preparing",progress:Ki[0]},operation:u};this.preparations.set(n,d),this.diagnostic("prepare.started",n),Ki.forEach((l,h)=>{const f=this.schedule(()=>{if(u.timers.delete(f),!u.cancelled){d.status={state:"preparing",progress:l};try{u.listeners.forEach(_=>_(l))}catch(_){u.cancelled=!0;for(const p of u.timers)this.clearSchedule(p);d.operation=void 0,d.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",n,{message:_ instanceof Error?_.message:String(_)}),u.reject(_);return}if(this.diagnostic("prepare.progress",n,{phase:l.phase}),h===Ki.length-1){if(d.operation=void 0,n==="prepare-fail"){d.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},u.reject(it("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",n,{code:"COMPANION_INTEGRITY_FAILED"});return}d.status={state:"ready",preparedAt:this.now()},u.resolve(this.getInfo(n)),this.diagnostic("prepare.ready",n)}}},h+1);u.timers.add(f)})}return c}cancelPreparation(t){const r=this.readAlias(t),n=this.preparations.get(r);if(n?.operation){n.operation.cancelled=!0;for(const i of n.operation.timers)this.clearSchedule(i);n.operation.reject(it("COMPANION_PREPARATION_CANCELLED","准备已取消")),n.operation=void 0,n.status={state:"not-prepared"},this.diagnostic("prepare.cancelled",r)}}getActiveSession(t){const r=this.readAlias(t),n=this.sessions.get(r);if(!n||n.exited)return;const i=n.snapshot.controllerGeneration;return n.snapshot={...n.snapshot,controllerGeneration:i+1},this.emit(H0,{sessionId:n.snapshot.id,controllerGeneration:i}),n.waitingOutput&&(n.queuedOutput.unshift(n.waitingOutput),n.waitingOutput=void 0,this.flushOutput(n)),this.diagnostic("session.controller-transferred",r,{controllerGeneration:n.snapshot.controllerGeneration}),{...n.snapshot,capabilities:[...n.snapshot.capabilities]}}launch(t){const r=this.readAlias(t);if(this.getPreparationStatus(r).state!=="ready")throw it("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw it("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw it("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:Ml[r],state:"running",controllerGeneration:1},s={snapshot:i,stdinClosed:!1,exited:!1,queuedOutput:[]};return this.sessions.set(r,s),this.diagnostic("session.launched",r,{capabilities:[...i.capabilities],sessionId:i.id}),i.capabilities.includes("stdio")&&this.schedule(()=>{this.queueOutput(s,"stdout",1,`fake:ready
220
- `),this.queueOutput(s,"stderr",1,`fake:diagnostic
221
- `)},20),r==="normal-exit"&&this.schedule(()=>this.requestExit(s,{reason:"exited",exitCode:0}),40),r==="crash"&&this.schedule(()=>this.requestExit(s,{reason:"crashed",exitCode:1}),40),r==="output-limit"&&this.schedule(()=>this.requestExit(s,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("stdio"))throw it("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw it("COMPANION_PIPE_CLOSED","stdin 已关闭");const n=Math.max(1,...r.queuedOutput.map(i=>i.sequence),r.waitingOutput?.sequence??0)+1;this.queueOutput(r,"stdout",n,new Uint8Array(t.data)),this.diagnostic("stdio.write",r.snapshot.alias,{bytes:t.data.byteLength})}closeStdin(t){const r=this.readController(t);r.stdinClosed=!0,this.diagnostic("stdio.closed",r.snapshot.alias)}terminate(t){const r=this.readController(t);this.exit(r,{reason:"terminated"})}ackOutput(t){const r=this.readController(t),n=r.waitingOutput;!n||n.stream!==t.stream||n.sequence!==t.sequence||(r.waitingOutput=void 0,this.diagnostic("stdio.ack",r.snapshot.alias,{sequence:t.sequence,stream:t.stream}),this.flushOutput(r))}openAttachment(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("attachments"))throw it("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw it("COMPANION_ATTACHMENT_NOT_FOUND","固定 Fake Attachment 不存在");this.diagnostic("attachment.opened",r.snapshot.alias,{id:t.id});const n=new TextEncoder().encode(`Browser Fake Companion report
222
- `);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw it("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw it("FILE_ACCESS_DENIED","Attachment 只读")},stat:async()=>({kind:"file",size:n.byteLength})}}showNotification(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("notifications"))throw it("COMPANION_NOTIFICATION_UNAVAILABLE","notifications 未启用");this.diagnostic("notification.shown",r.snapshot.alias,{category:t.category})}queueOutput(t,r,n,i){t.queuedOutput.push({stream:r,sequence:n,data:typeof i=="string"?new TextEncoder().encode(i):i}),this.flushOutput(t)}flushOutput(t){if(t.exited||t.waitingOutput||!this.eventSink&&this.sessionEventListeners.size===0)return;const r=t.queuedOutput.shift();if(!r){t.pendingExit&&this.exit(t,t.pendingExit);return}t.waitingOutput=r,this.emit(U0,{sessionId:t.snapshot.id,controllerGeneration:t.snapshot.controllerGeneration,...r}),this.diagnostic("stdio.chunk",t.snapshot.alias,{bytes:r.data.byteLength,sequence:r.sequence,stream:r.stream})}requestExit(t,r){t.pendingExit=r,!t.waitingOutput&&t.queuedOutput.length===0&&this.exit(t,r)}exit(t,r){t.exited||(t.exited=!0,t.pendingExit=void 0,t.waitingOutput=void 0,t.queuedOutput.length=0,this.emit(B0,{sessionId:t.snapshot.id,exit:r}),this.diagnostic("session.exit",t.snapshot.alias,{...r}))}readController(t){const r=[...this.sessions.values()].find(n=>n.snapshot.id===t.sessionId);if(!r||r.exited)throw it("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw it("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!Ol.includes(t))throw it("COMPANION_NOT_DECLARED","未知固定 Companion Fake 场景");return t}emit(t,r){this.eventSink?.(t,r),this.sessionEventListeners.forEach(n=>n({type:t,payload:r}))}diagnostic(t,r,n){this.onDiagnostic({action:t,...r?{alias:r}:{},...n?{detail:n}:{}})}}const mS=Object.freeze({[pa]:!0,[_a]:!0,[Ta]:!0,[Aa]:!0,[Ia]:!0,[ba]:!0,[ya]:!0,[Na]:!0,[wa]:!0,[Da]:!0,[Sa]:!0,[Oa]:!0,[hi]:!0,[fi]:!0,[mi]:!0});function ES(e){return new hS(e)}function it(e,t){return Object.assign(new Error(t),{code:e})}function gS(e={}){const t=e.source??bS(e.document??document),r=e.readMetadata??yS,n=e.createPreviewUrl??(d=>URL.createObjectURL(d)),i=e.revokePreviewUrl??(d=>URL.revokeObjectURL(d)),s=new WeakMap,a=new Set,c=d=>{if(!(!d||!a.has(d))){a.delete(d);try{i(d)}catch{}}},u=()=>{for(const d of[...a])c(d)};return e.signal?.addEventListener("abort",u,{once:!0}),{async pick(d,l){switch(qn(l.signal),e.getMode?.()??"normal"){case"cancel":throw qe("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");case"system-permission-denied":throw qe("MEDIA_SYSTEM_PERMISSION_DENIED","系统未授予相机或相册权限");case"prepare-failure":throw qe("MEDIA_PREPARE_FAILED","媒体准备失败,未保留部分结果");case"preview-unavailable":throw qe("MEDIA_PREVIEW_UNAVAILABLE","当前 Host 无法提供受控媒体预览")}const h=d.source==="camera"?[await t.capture({mediaType:d.mediaType})]:await pS(t,d);if(qn(l.signal),d.source==="camera"&&h.length!==1)throw qe("MEDIA_PREPARE_FAILED","相机模拟必须恰好返回 1 项");const f=[];try{for(const _ of h)qn(l.signal),f.push(await TS(_,d,l.signal,r,n,s,a));qn(l.signal)}catch(_){for(const p of f)c(s.get(p.file));throw _}return f},release(d){for(const l of d)c(s.get(l.file))}}}async function pS(e,t){const r=await e.pickAlbum({accept:_S(t.mediaType),maxCount:t.maxCount,multiple:t.maxCount>1});if(!r||r.length===0)throw qe("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");if(r.length>t.maxCount)throw qe("MEDIA_PREPARE_FAILED",`本次选择 ${r.length} 项,超过 maxCount ${t.maxCount}`);return r}function _S(e){switch(e){case"image":return"image/*";case"video":return"video/*";default:return"image/*,video/*"}}async function TS(e,t,r,n,i,s,a){const c=AS(e.type);if(!c)throw qe("MEDIA_PREPARE_FAILED",`浏览器未提供可识别的媒体类型: ${e.name}`);if(t.mediaType!=="all"&&t.mediaType!==c)throw qe("MEDIA_PREPARE_FAILED",`所选媒体 ${e.name} 与 mediaType 不匹配`);const u=await n(e);qn(r);const d=Rl(u.width),l=Rl(u.height);if(d===void 0||l===void 0)throw qe("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的显示尺寸`);if(c==="video"){if(Cl(u.durationMs)===void 0)throw qe("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的视频时长`)}else if(u.durationMs!==void 0)throw qe("MEDIA_PREPARE_FAILED",`图片 ${e.name} 不应携带视频时长`);const h=i(e);if(!h)throw qe("MEDIA_PREVIEW_UNAVAILABLE","无法提供受控媒体预览");const f=IS(e);s.set(f,h),a.add(h);const _={type:c,mimeType:e.type,size:e.size,width:d,height:l,previewUrl:h,file:f};return c==="video"?{..._,durationMs:Cl(u.durationMs)}:_}function AS(e){if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video"}function IS(e){const t=()=>Promise.reject(Object.assign(new Error("Browser Dev Host 媒体句柄只读"),{code:"FILE_ACCESS_DENIED"}));return{kind:"file",name:e.name,mode:"read",create:t,read:async()=>new Uint8Array(await e.arrayBuffer()),write:t,stat:async()=>({kind:"file",size:e.size,...e.lastModified?{modifiedAt:e.lastModified}:{}})}}function bS(e=document){return{pickAlbum(t){return new Promise(r=>{const n=e.createElement("input");n.type="file",n.accept=t.accept,n.multiple=t.multiple,n.style.display="none";let i=!1;const s=()=>{n.removeEventListener("change",c),n.removeEventListener("cancel",u),n.remove()},a=d=>{i||(i=!0,s(),r(d))},c=()=>a(n.files?Array.from(n.files):[]),u=()=>a(void 0);n.addEventListener("change",c),n.addEventListener("cancel",u),e.body.append(n),n.click()})},capture(t){return t.mediaType==="video"?OS():SS()}}}async function yS(e){return e.type.startsWith("video/")?wS(e):NS(e)}async function NS(e){if(typeof globalThis.createImageBitmap=="function"){const r=await globalThis.createImageBitmap(e),n={width:r.width,height:r.height};return r.close?.(),n}const t=URL.createObjectURL(e);try{const r=new Image;return await new Promise((n,i)=>{r.onload=()=>n(),r.onerror=()=>i(qe("MEDIA_PREPARE_FAILED","无法解码所选图片")),r.src=t}),{width:r.naturalWidth,height:r.naturalHeight}}finally{URL.revokeObjectURL(t)}}async function wS(e){const t=URL.createObjectURL(e),r=document.createElement("video");r.preload="metadata";try{await new Promise((i,s)=>{r.onloadedmetadata=()=>i(),r.onerror=()=>s(qe("MEDIA_PREPARE_FAILED","无法读取所选视频元数据")),r.src=t});let n=r.duration;return Number.isFinite(n)||(n=await DS(r)),{width:r.videoWidth,height:r.videoHeight,durationMs:Number.isFinite(n)?Math.max(0,Math.round(n*1e3)):0}}finally{r.removeAttribute("src"),URL.revokeObjectURL(t)}}function DS(e){return new Promise(t=>{const r=()=>{e.removeEventListener("durationchange",r),e.removeEventListener("timeupdate",r),t(e.duration)};e.addEventListener("durationchange",r),e.addEventListener("timeupdate",r),e.currentTime=1e101})}async function SS(){const e=document.createElement("canvas");e.width=640,e.height=480;const t=e.getContext("2d");if(!t)throw qe("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=t.createLinearGradient(0,0,e.width,e.height);r.addColorStop(0,"#2b2b3a"),r.addColorStop(1,"#0f7b6c"),t.fillStyle=r,t.fillRect(0,0,e.width,e.height),t.fillStyle="#ffffff",t.font="28px sans-serif",t.fillText("Browser Dev Host 模拟拍摄",40,e.height/2);const n=await new Promise(i=>e.toBlob(i,"image/png"));if(!n)throw qe("MEDIA_PREPARE_FAILED","无法生成测试图片");return new File([n],"browser-dev-camera.png",{type:"image/png"})}async function OS(){const e=document.createElement("canvas");e.width=320,e.height=240;const t=e.getContext("2d");if(!t)throw qe("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=e.captureStream?.bind(e),n=globalThis.MediaRecorder;if(!r||!n)throw qe("MEDIA_PREPARE_FAILED","当前浏览器不支持 MediaRecorder 视频模拟");const i=r.call(e,12),s=new n(i,{mimeType:MS(n)}),a=[],c=new Promise((l,h)=>{s.ondataavailable=f=>{f.data.size>0&&a.push(f.data)},s.onstop=()=>l(),s.onerror=()=>h(qe("MEDIA_PREPARE_FAILED","模拟拍摄录制失败"))});s.start();const u=Date.now();await RS(t,e,()=>Date.now()-u<900),s.stop(),await c;for(const l of i.getTracks())l.stop();const d=new Blob(a,{type:s.mimeType||"video/webm"});if(d.size===0)throw qe("MEDIA_PREPARE_FAILED","模拟拍摄未生成视频数据");return new File([d],"browser-dev-camera.webm",{type:d.type})}function MS(e){for(const t of["video/webm;codecs=vp8","video/webm","video/mp4"])if(e.isTypeSupported?.(t))return t;return"video/webm"}async function RS(e,t,r){for(;r();){const n=Math.min(1,Date.now()%900/900);e.fillStyle="#101820",e.fillRect(0,0,t.width,t.height),e.fillStyle=`rgb(${Math.round(40+n*180)}, 120, ${Math.round(200-n*120)})`,e.fillRect(0,t.height*(1-n),t.width,8),e.fillStyle="#ffffff",e.font="18px sans-serif",e.fillText("模拟拍摄中",24,t.height/2),await new Promise(i=>setTimeout(i,60))}}function qn(e){if(e.aborted){const t=new Error("Browser Dev Host 媒体选择已取消");throw t.name="AbortError",t}}function qe(e,t){const r=new Error(t);return r.name="BrowserDevMediaError",r.code=e,r}function Rl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:void 0}function Cl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function CS(e){const t=ft(e.runtimePermissions),r=Uc({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=ft(e.publishedRuntimePermissions),s=ft(r.runtimePermissions);for(const a of xc){const c=a.key,u={network:"Network",companion:"Companion",appProtocol:"AppProtocol"}[c]??a.name;if(!e.declaredPermissions?.[c]?.enabled)continue;const d=t.valid&&t.permissions[c]?.status==="enabled",l=r.temporaryPermissionKeys.some(h=>h===c);n.push({key:c,label:u,state:a.access==="declaration"?"declared":d?"approved":l?"temporary":"unavailable",facts:{platformApproval:a.access==="declaration"?null:d,temporary:l,effective:s.permissions[c]?.status==="enabled",online:i.valid?i.permissions[c]?.status??"missing":"unknown"},...l?{releaseDifference:"本次使用临时授权,发布后仍需平台批准。"}:i.valid&&!i.permissions[c]?{releaseDifference:"线上快照尚未包含该权限,需发布包含声明的新版本。"}:{},...c==="appProtocol"?{highestRisk:!0}:{},...a.access!=="declaration"&&!d&&!l?{reason:c==="appProtocol"?"最高危险权限:可执行任意协议并绕过其他 SDK 能力权限;当前没有有效临时授权,线上未批准":"没有有效的本地临时授权,线上未批准"}:{}})}if(e.declaredPermissions?.network?.useOfficialDomain){const a=t.valid&&t.permissions.network?.status==="enabled"&&t.permissions.network.config.useOfficialDomain===!0;n.push({key:"network.useOfficialDomain",label:"官方域名",state:a?"approved":"unavailable",...a?{}:{reason:"不支持本地临时授权,获得线上批准后才能使用"}})}return n}function Lr(e){return JSON.stringify({source:e.source,miniProgramId:e.miniProgramId,devSessionId:e.devSessionId,contextRevision:e.contextRevision,declaredPermissions:e.declaredPermissions,runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant,companionManifestSha256:e.companionManifestSha256})}const Ll="__hb_sdk_mini_dev_console_installed__",LS=["log","debug","info","warn","error"];function PS(e,t=console){if(t[Ll])return;let r=!1;for(const n of LS){const i=t[n];if(typeof i!="function")continue;const s=function(...a){try{e(n,a)}catch{}return i.apply(this,a)};try{t[n]=s,r=!0}catch{break}}r&&(t[Ll]=!0)}const ac=1,Pl=64*1024,vS=64,kS=/^[A-Za-z0-9_-]{22}$/;class It extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function xS(e,t=!1){const r=BS(e,t);switch(oc(r,"Server message"),HS(r),r.type){case"grant":return ri(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),ni(r.connectionEpoch,"connectionEpoch"),Pr(r.nextClientSequence,"nextClientSequence"),Pr(r.nextServerSequence,"nextServerSequence"),vl(r.snapshot),r;case"event":return ri(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),ni(r.connectionEpoch,"connectionEpoch"),Pr(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&Ar("event must be account.changed or status.changed"),vl(r.snapshot),r;case"heartbeat":return ri(r,["version","type","connectionEpoch","sequence"],"heartbeat"),ni(r.connectionEpoch,"connectionEpoch"),Pr(r.sequence,"sequence"),r;default:return Ar("Unknown server message type")}}function US(e){const t=e.connectionEpoch;ni(t,"connectionEpoch"),Pr(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(ni(n.connectionEpoch,"connectionEpoch"),Pr(n.sequence,"sequence"),n.connectionEpoch!==t)throw new It("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new It("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new It("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function BS(e,t){if(t)throw new It("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new It("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Pl)throw new It("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Pl)throw new It("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return FS(e),JSON.parse(e)}catch(r){throw r instanceof It?r:new It("INVALID_JSON","Channel frame must contain strict JSON")}}function vl(e){oc(e,"snapshot"),ri(e,["account","permissions"],"snapshot"),oc(e.account,"snapshot.account"),ri(e.account,["revision"],"snapshot.account"),Pr(e.account.revision,"snapshot.account.revision"),x1(e.permissions)||Ar("snapshot.permissions is invalid")}function HS(e){e.version!==ac&&Ar("version must be 1")}function oc(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Ar(`${t} must be a plain JSON object`)}function ri(e,t,r,n=[]){const i=Object.keys(e);(t.some(s=>!Object.hasOwn(e,s))||i.some(s=>!t.includes(s)&&!n.includes(s)))&&Ar(`${r} fields are invalid`)}function Pr(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Ar(`${t} must be a non-negative safe integer`)}function ni(e,t){(typeof e!="string"||!kS.test(e))&&Ar(`${t} must be a 22-character base64url value`)}function Ar(e){throw new It("INVALID_MESSAGE",e)}function FS(e){new zS(e).scan()}class zS{constructor(t){this.source=t}position=0;scan(){if(this.skipWhitespace(),this.scanValue(),this.skipWhitespace(),this.position!==this.source.length)throw new SyntaxError("Unexpected trailing JSON data")}scanValue(t=0){const r=this.source[this.position];if(r==="{"||r==="["){if(t>=vS)throw new It("INVALID_JSON","Channel JSON exceeds maximum nesting depth");return r==="{"?this.scanObject(t):this.scanArray(t)}if(r==='"'){this.scanString();return}this.scanPrimitive()}scanObject(t){this.position+=1,this.skipWhitespace();const r=new Set;if(!this.consume("}"))for(;;){if(this.source[this.position]!=='"')throw new SyntaxError("JSON object key must be a string");const n=this.scanString(),i=JSON.parse(n);if(typeof i!="string")throw new SyntaxError("JSON object key must be a string");if(r.has(i))throw new It("INVALID_JSON","Channel JSON contains a duplicate key");if(r.add(i),this.skipWhitespace(),!this.consume(":"))throw new SyntaxError("Missing JSON object colon");if(this.skipWhitespace(),this.scanValue(t+1),this.skipWhitespace(),this.consume("}"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON object comma");this.skipWhitespace()}}scanArray(t){if(this.position+=1,this.skipWhitespace(),!this.consume("]"))for(;;){if(this.scanValue(t+1),this.skipWhitespace(),this.consume("]"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON array comma");this.skipWhitespace()}}scanString(){const t=this.position;for(this.position+=1;this.position<this.source.length;){const r=this.source[this.position];if(r==='"')return this.position+=1,this.source.slice(t,this.position);r==="\\"?this.position+=2:this.position+=1}throw new SyntaxError("Unterminated JSON string")}scanPrimitive(){const t=this.position;for(;this.position<this.source.length&&!/[\s,\]}]/.test(this.source[this.position]??"");)this.position+=1;if(t===this.position)throw new SyntaxError("Missing JSON value")}skipWhitespace(){for(;/[\t\n\r ]/.test(this.source[this.position]??"");)this.position+=1}consume(t){return this.source[this.position]!==t?!1:(this.position+=1,!0)}}const kl=[1e3,2e3,4e3,8e3,15e3];function jS(e){const t=new Set,r=e.webSocketFactory??(q=>new WebSocket(q)),n=e.randomValues??(q=>crypto.getRandomValues(q)),i=e.timers??{clearTimeout:q=>window.clearTimeout(q),setTimeout:(q,te)=>window.setTimeout(q,te)},s=e.onlineTarget??(typeof window>"u"?void 0:window),a=e.visibilityTarget??(typeof document>"u"?void 0:document),c=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let u,d,l,h=!1,f=0,_,p=!1,y=!1;const w=new Set,N=(q,te)=>{if(!(!e.onDiagnostic||w.has(q))){w.add(q);try{e.onDiagnostic({phase:q,...te?{code:te}:{}})}catch{}}},O=(q,te,F=!1)=>{if(l&&q.account.revision<l.account.revision)return;const G=l&&JSON.stringify(q)===JSON.stringify(l);if(l=q,!(G&&!F))for(const j of t)j(q,te)},I=()=>{if(h||_!==void 0||u)return;const q=kl[Math.min(f,kl.length-1)];f+=1,_=i.setTimeout(()=>{_=void 0,W()},q)},H=()=>{h||!p||u||(_!==void 0&&(i.clearTimeout(_),_=void 0),W())},Q=()=>{c()&&H()},M=()=>{a&&!a.hidden&&H()},x=()=>{y||(y=!0,s?.addEventListener("online",Q),a?.addEventListener("visibilitychange",M))},v=()=>{y&&(y=!1,s?.removeEventListener("online",Q),a?.removeEventListener("visibilitychange",M))},W=()=>{if(h||u)return;p=!0,x(),_!==void 0&&(i.clearTimeout(_),_=void 0);let q,te;try{q=r(e.url)}catch{N("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),I();return}try{te=GS(n)}catch{N("entropy","NONCE_GENERATION_FAILED");try{q?.close(1011,"channel initialization failed")}catch{}I();return}u=q;let F,G,j;const z=()=>{q.removeEventListener("open",U),q.removeEventListener("message",k),q.removeEventListener("close",Y),q.removeEventListener("error",R),d===z&&(d=void 0)},V=()=>{if(u===q){u=void 0,z();try{q.close(1008,"invalid channel state")}catch{}I()}},U=()=>{if(!(h||u!==q))try{q.send(JSON.stringify({version:ac,type:"hello",csrfToken:e.csrfToken,clientNonce:te}))}catch{N("send","HELLO_SEND_FAILED"),V()}},k=K=>{if(h||u!==q)return;if(typeof K.data!="string"){N("parse","TEXT_FRAME_REQUIRED"),V();return}let Z;try{Z=xS(K.data)}catch(ee){N("parse",ee instanceof It?ee.code:"INVALID_MESSAGE"),V();return}if(Z.type==="grant"){if(j){N("sequence","DUPLICATE_GRANT"),V();return}F=Z.connectionEpoch,G=Z.nextClientSequence,j=US({connectionEpoch:F,nextSequence:Z.nextServerSequence}),f=0,w.clear(),O(Z.snapshot,{type:"grant"});return}if(!j||!F||G===void 0){N("sequence","MESSAGE_BEFORE_GRANT"),V();return}try{j.accept(Z)}catch{N("sequence","INVALID_SEQUENCE"),V();return}if(Z.type==="heartbeat"){try{q.send(JSON.stringify({version:ac,type:"heartbeat.ack",connectionEpoch:F,sequence:G}))}catch{N("send","HEARTBEAT_ACK_SEND_FAILED"),V()}G=G===Number.MAX_SAFE_INTEGER?void 0:G+1;return}O(Z.snapshot,{type:"event",event:Z.event},!0)},Y=()=>{u===q&&(N("close","SOCKET_CLOSED"),u=void 0,z(),I())},R=()=>{N("open","SOCKET_ERROR"),V()};q.addEventListener("open",U),q.addEventListener("message",k),q.addEventListener("close",Y),q.addEventListener("error",R),d=z};return{connect:W,subscribeUpdates(q){return t.add(q),()=>t.delete(q)},dispose(){if(h)return;h=!0,p=!1,v(),_!==void 0&&i.clearTimeout(_),_=void 0;const q=u;u=void 0,d?.(),q?.close(1e3,"client disposed"),t.clear()}}}function VS(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,s=e[n+1],a=e[n+2];r+=t[i>>2],r+=t[(i&3)<<4|(s??0)>>4],s!==void 0&&(r+=t[(s&15)<<2|(a??0)>>6]),a!==void 0&&(r+=t[a&63])}return r}function GS(e){const t=e(new Uint8Array(16));if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("Channel nonce source must fill 16 bytes");const r=VS(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let Ge=!1,Nm=!1,rt;const wm=new AbortController;try{PS((e,t)=>{vr(`console.${e}`,{source:"host",message:t.map(r=>oO(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const YS="/__hb_sdk_bootstrap__",qS="/__hb_sdk__/network",QS="/session/status",WS="/session/request",$S="/session/events",KS=1e3,ZS=1e3,XS=15e3,xl="dark",JS=["windows","macos","linux","unknown"],Dm=new URL(location.href).searchParams,Sm=Dm.get("mini_url"),ht=Dm.get("ui_preview")==="1",eO={get device(){return vO("#device")}};if(!Sm&&!ht)throw eO.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Om=Sm??"about:blank",je=await Vm(),au=ht?void 0:await kt.configure({csrfToken:je.csrfToken??"",diagnosticsToken:je.diagnosticsToken??"",signal:wm.signal,query:SO,onDropped:e=>{ie.diagnosticsDropped=e},onOwnershipLost:xm});ie.diagnosticTargetId=au?.targetId??"";ie.diagnosticOwnerId=au?.ownerId??"";ie.diagnosticTargetName=au?.metadata.displayName??"";ie.openPlatformBaseUrl=je.openPlatformBaseUrl;ie.devReadiness=je.devReadiness;ie.miniProgramSupportsDesktop=je.miniProgramSupportsDesktop;ie.miniProgramPlatforms=je.devContext.platforms??[];ie.desktopLaunch.workspaceCardsEnabled=je.workspaceCardsEnabled;Fl(je.hostPlatform);zl(je.windowForm);je.lanAddresses;je.defaultLanAddressId;je.mobileLaunchRedirect;let Mm=je.nativeAppLaunchUnavailableReason,ii=je.devSessionId,cc=je.miniProgramManifestAccessToken,ds=je.workspaceCardsEnabled,Rm=du(je),Dt=je.devContext,dn=je.browserDevContext,tt=ti(dn);Ea();let In=iu(tt),Ya=0;const jr=new AbortController;let ou=0,$t,uc=0,dc,lc,Ao=!1;const bn=A0({apply:I0,waitForLayout:async e=>{await ms(),await Yl(e),await ql(e)}});let cu=!1;function Io(e){if(e.throwIfAborted(),Ge)throw new Mr("SESSION_CLOSED","调试台已关闭");if(ie.diagnosticOwnershipLost)throw new Mr("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!cu)throw new Mr("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(cn)throw new Mr("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const fc=_0({observe:()=>{const e=yi()?{width:hs.value.width,height:hs.value.height}:{width:Mo.value.screenWidth,height:Mo.value.screenHeight};return{preset:ie.deviceSelectionId,orientation:yi()?e.width>=e.height?"landscape":"portrait":ie.display.orientation,runtimeStatus:ie.runtimeStatus,viewport:e,instanceId:rt?.mounted?rt.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:y0()}},async selectPreset(e,t){Io(t),ie.deviceSelectOpen=!1;const r=ie.previewMode,n=rt;b0(e),await ms(),t.throwIfAborted(),ie.previewMode!==r&&await Ul(n,t)},async applyOrientation(e,t){Io(t),ie.deviceSelectOpen=!1,await bn.applyDisplay({mode:e,hideCapsule:ie.display.capsuleHidden},t)},async reload(e){Io(e),ie.deviceSelectOpen=!1;const t=rt;Tr("runtime.restart",{boundary:ou+1}),Gr("manual restart").catch(()=>{}),await Ul(t,e)},async waitForLayout(e){await ms(),e.throwIfAborted(),await Yl(e),await ql(e)}}),ls=M0(),Cm={...fc.bridge,prepareCapture:ls.prepare,restoreCapture:ls.restore,cancel(e){fc.bridge.cancel(e),ls.cancel(e)}};window.__HB_SDK_PREVIEW__=Cm;async function Ul(e,t){for(;;){if(t.throwIfAborted(),Ge)throw new Mr("SESSION_CLOSED","调试台已关闭");if(rt!==e&&$t===void 0){const r=ie.runtimeStatus;if(r==="ready"||ht&&r==="idle")return;if(r==="error")throw new Mr("RUNTIME_START_FAILED","小程序 Runtime 启动失败,请查看调试日志");if(r==="closed")throw new Mr("RUNTIME_CLOSED","预览窗口已关闭或最小化,请先恢复窗口")}await new Promise((r,n)=>{const i=()=>{clearTimeout(s),n(t.reason)},s=setTimeout(()=>{t.removeEventListener("abort",i),r()},20);t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}}let hc,mc,Ec,gc,pc,_c,Bl=Date.now(),cn=!1,ln=-1,bi=!1,rr,Tc,Ac,fs,Or;const ha=new Set,Hl="hb-sdk:browser-dev-host:user-data-device";function tO(){try{const e=localStorage.getItem(Hl)?.trim();if(e)return e;const t=typeof crypto.randomUUID=="function"?crypto.randomUUID():`mock-${Date.now().toString(36)}`;return localStorage.setItem(Hl,t),t}catch{return"browser-mock-device"}}const rO=tO();function nO(){return{miniProgramId:Dt.miniProgramId?.trim().toLowerCase()||"anonymous-mini-program",userId:rr?.trim()||"anonymous-user",deviceId:rO,environment:"development"}}function Lm(){return Im(tt.runtimePermissions,In,tt)}function iO(){const e=ft(Lm());return e.valid&&e.permissions.network?.status==="enabled"?"upload":"no_network"}function sO(){return aS({declaredPermissions:tt.declaredPermissions,runtimePermissions:Lm()})}const Kt=iS({resolveScope:nO,egressTier:iO,declared:sO});function yn(){Nm&&T0({...Kt.snapshot(),targetId:ie.diagnosticTargetId,instanceId:rt?.instanceId})}Kt.subscribe(yn);Nm=!0;yn();function bo(){const e=Kt.snapshot().stateError;if(e)throw new Error(e)}a0({async refresh(){await Kt.refresh(),bo()},async revokeSession(){await Kt.revokeSession(),bo()},async resetAll(){await Kt.resetAll(),bo()}});const Ic=ES({onDiagnostic:({action:e,alias:t,detail:r})=>Tr(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Nn=z1({applyStatus:e=>zm(e,!0),fetchStatus:e=>Fm(lu(jr.signal,e)),getCanonicalRevision:()=>ln,onError:MO,reconcile:()=>EO(Ya)}),bc=j1({connectEvents:jm,invalidate:()=>Nn.invalidate(),isDisposed:()=>Ge,maxDelayMs:XS,minDelayMs:ZS,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let yo=0,Zi="",No=!1,yc,Nc;function Pm(){ht||Ge||ie.diagnosticOwnershipLost||kt.poll().finally(()=>{!Ge&&!ie.diagnosticOwnershipLost&&(Nc=window.setTimeout(Pm,1e3))})}Pm();await ma(!1);Gm();qm(Ym(je));ht&&cO();Ni();ht||await km();aO();vm();IO();await Gr("initial");ht||(jm(),hO());cu=!0;function vm(){!ht&&!Ge&&(yc=window.setTimeout(()=>{km().finally(vm)},1e3))}async function km(){if(!(No||Ge)){No=!0;try{const e=await fetch(`${mu}?after=${yo}&limit=500`,{headers:{"x-hb-sdk-csrf":je.csrfToken??""},signal:AbortSignal.any([jr.signal,AbortSignal.timeout(5e3)])});if(!e.ok){ie.diagnosticsStale=!0;return}const t=await e.json();if(Ge)return;if(Zi&&t.epoch!==Zi){yo=0,Zi=t.epoch,o0();return}Zi=t.epoch,ie.uploadSessions=t.uploadSessions;const r=await fetch(`${mu}?mode=inspect`,{headers:{"x-hb-sdk-csrf":je.csrfToken??""},signal:AbortSignal.any([jr.signal,AbortSignal.timeout(5e3)])});if(r.ok){const s=await r.json();ie.diagnosticInstances=s.instances,ie.diagnosticTargets=s.targets,ie.diagnosticPrimaryTargetId=s.primaryTargetId;const a=s.targets.find(c=>c.targetId===ie.diagnosticTargetId);a&&(ie.diagnosticTargetName=a.metadata.displayName),a&&(a.state==="closed"||a.ownerId!==ie.diagnosticOwnerId)&&xm()}ie.diagnosticsStale=!r.ok,ie.diagnosticsGap=ie.diagnosticsGap||t.gap===!0;const n=new Map(ie.diagnosticTargets.map(s=>[s.targetId,s.metadata.displayName])),i=new Map(ie.diagnosticInstances.map(s=>[s.instanceId,n.get(s.targetId)]));for(const s of t.items){const a=c0(s);a&&(a.targetName=n.get(s.targetId)??i.get(s.instanceId),a.uploadSessionId=s.uploadSessionId,a.uploadSessionName=t.uploadSessions.find(c=>c.id===s.uploadSessionId)?.name,a.dedupeKey=void 0,u0(a,s.cursor))}yo=t.nextCursor}catch{ie.diagnosticsStale=!0}finally{No=!1}}}function aO(){window.addEventListener("beforeunload",RO),window.addEventListener("hb-sdk:refresh-storage",Ni),hc=d0(()=>document.querySelector("#host-fullscreen-exit-mount")),mc=Rn(()=>[si.value,Do.value,Xi.value?.state,Xi.value?.stale,Xi.value?.capabilities.storage].join("|"),()=>{ie.storage=[],ie.storageError="",Ni()}),Ec=Rn(()=>ie.devicePresetId,()=>bn.notifyViewportChange(),{flush:"post"}),gc=Rn(()=>ie.previewMode,()=>{nr("preview mode changed"),jl(!1),l0(!1),wn("preview mode changed")},{flush:"sync"}),pc=Rn(()=>hs.value,()=>bn.notifyViewportChange(),{flush:"post"}),_c=Rn(()=>ie.desktopWindow.closed,(e,t)=>{if(yi()){if(e){nr("desktop window closed"),ie.runtimeStatus="closed";return}t&&ie.runtimeStatus==="closed"&&wn("desktop window reopened")}},{flush:"sync"})}function oO(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
223
- `).slice(0,4).join(`
224
- `):"")||`${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 wn(e){Ge||$t!==void 0||(Tr("runtime.restart",{boundary:ou+1}),$t=window.setTimeout(()=>{$t=void 0,Ge||Gr(e)},0))}async function Gr(e,t=Om,r){if(Ge||cn||ie.diagnosticOwnershipLost)return;if($t!==void 0&&window.clearTimeout($t),$t=void 0,nr(e),yi()&&ie.desktopWindow.closed){ie.runtimeStatus="closed";return}const n=document.createElement("iframe");n.dataset.testid="device-iframe",n.title="小程序预览",n.allow="clipboard-read; clipboard-write",n.name="__hb_sdk_mini_dev__";const i=crypto.randomUUID(),s=f0(i,u=>{ht||kt.event(i,u)}),a={instanceId:i,launchUrl:t,locationBasePath:r,interactions:s,sequence:++ou,state:"starting",iframe:n,terminal:new AbortController,permissions:$m(In),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(a.iframe.dataset.hbSdkInstanceId=a.instanceId,rt=a,ie.runtimeStatus="loading",Bm(),ht||kt.send({operation:"register",instanceId:a.instanceId}),await ms(),!st(a))return;const c=Zm("#device");if(!c){wo(a,new Error("预览容器尚未挂载"));return}if(ht){c.innerHTML='<div class="browser-mock-preview"><span class="browser-mock-preview__icon">UI</span><strong>Browser Mock</strong><small>mp_preview</small></div>',ie.runtimeStatus="idle";return}c.replaceChildren(a.iframe),a.mounted=!0,kt.send({operation:"activate",instanceId:a.instanceId});try{const u=await S1(uO(a));if(!st(a)){u.dispose();return}a.assembly=u,u.ports.companion=Ic.port,u.ports.media=gS({getMode:()=>ie.mediaSimulation,signal:a.terminal.signal});const d=P1({signal:a.terminal.signal,csrfToken:()=>je.csrfToken??""}),l=k1({signal:a.terminal.signal,refreshAccount:f=>ma(!0,f),request:Hm,readState:()=>({signed:Dt,browser:tt,userId:rr,accountRevision:ln,networkEnabled:a.permissions.networkRequest.status==="enabled"})}),h=u1({iframe:a.iframe,authorizationContext:l,ports:{...u.ports,...d},environment:u.environment,hostCapabilities:{...u.hostCapabilities,"media.pick":!0,...d?{"gameSaves.getFile":!0,"user.data.file":!0,"file.readBytes":!0,"file.readText":!0,"file.stat":!0,"file.exists":!0}:{},...mS},authPresentation:u.authPresentation,userDataPresentation:u.userDataPresentation,companionPresentation:Ic.presentation,resolveLaunchConfiguration:async()=>l.resolveLaunchConfiguration((await u.resolveLaunch()).configuration,{signal:a.terminal.signal}),dispose:()=>wc(a),onDevDocumentReload:(f,_)=>{st(a)&&Gr("development document reloaded",f,_)},onDevUploadSession:f=>{st(a)&&(a.uploadSessionId=f,Dn(a,{uploadSessionId:f}))},onReady:()=>{st(a)&&(a.state="ready",a.hadReady=!0,Sc.value=d?h.diagnostics.gameSaves:void 0,ie.runtimeStatus="ready",Dn(a),vr("runtime.ready",{generation:a.sequence},Date.now(),void 0,a.instanceId))},onUserDataTelemetry:f=>{Kt.refresh();const _=uS(f);vr(_.method,_.detail,Date.now(),"info",a.instanceId)},onTrace:f=>fO(a,f),onError:f=>{st(a)&&wo(a,f)},onCapabilityTrace:f=>{vr(f.method,{...f,source:"host"},f.timestamp,void 0,a.instanceId),st(a)&&f.method==="storage.setStorage"&&f.outcome==="success"&&Ni()}});a.runtime=h,await h.start(),st(a)&&Kt.bind(h.getDataPermissionBridge())}catch(u){if(!st(a))return;wo(a,u),vr("runtime.start.failed",Qm(u,a),Date.now(),"error",a.instanceId),a.terminal.abort(u),a.runtime?.destroy(),a.iframe.remove(),wc(a)}}function xm(){Ge||ie.diagnosticOwnershipLost||(ie.diagnosticOwnershipLost=!0,nr("预览页面授权已失效"),ie.runtimeStatus="closed",cu=!1)}function st(e){return rt===e&&!Ge&&!e.terminal.signal.aborted&&e.state!=="closed"&&e.state!=="failed"}function Dn(e,t={}){kt.send({operation:"update",instanceId:e.instanceId,state:e.state,...t})}function Um(e,t){e.mounted&&(e.mounted=!1,kt.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function wc(e){rt===e&&(Sc.value=void 0),e.interactions.dispose();const t=e.assembly;e.assembly=void 0,t?.dispose()}function wo(e,t){e.state==="failed"||e.state==="closed"||(e.state="failed",e.interactions.dispose(),Dn(e,{error:Qm(t,e),...e.uploadSessionId?{uploadSessionId:e.uploadSessionId}:{}}),Um(e,"Runtime failed"),rt===e&&(ie.runtimeStatus="error"))}function nr(e){const t=rt;t&&(rt=void 0,Sc.value=void 0,Kt.clearSession(),t.state!=="failed"&&(t.state="closed",Dn(t,{reason:e})),Um(t,e),(!si.value||si.value===ie.diagnosticTargetId)&&(uc+=1,dc?.abort()),h0(),Ic.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),wc(t),bn.reset())}function cO(){const e=w0();ie.diagnosticTargetId=e.targetId,ie.diagnosticOwnerId=e.ownerId,ie.diagnosticPrimaryTargetId=e.targetId,ie.diagnosticTargetName=e.metadata.displayName,ie.diagnosticTargets=[e],ie.diagnosticInstances=[{instanceId:e.currentInstanceId,targetId:e.targetId,ownerId:e.ownerId,adapterId:e.adapterId,kind:"browser",capabilities:e.capabilities,state:"ready",startedAt:Date.now(),updatedAt:Date.now(),startCursor:0,lastCursor:0,stale:!1}];const t={...e,targetId:"ui-preview-phone",ownerId:"ui-preview-phone-owner",kind:"mobile",currentInstanceId:"ui-preview-phone-instance",metadata:{displayName:"小黑盒",deviceModel:"iPhone 16 Pro",os:"iOS"}};ie.diagnosticTargets.push(t),ie.diagnosticInstances.push({...ie.diagnosticInstances[0],instanceId:t.currentInstanceId,targetId:t.targetId,ownerId:t.ownerId,kind:"mobile"}),So({...Oo("console.error",{source:"app",message:"真机示例:请求超时"},Date.now(),"error"),targetId:t.targetId,instanceId:t.currentInstanceId}),Tr("runtime.ready",{generation:1}),So(Oo("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info")),Tr("user.getInfo",{durationMs:34,outcome:"success"}),Tr("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function uO(e){const t=e.terminal.signal,r=tt,n=ii,i=Im(r.runtimePermissions,e.permissions,r),s=yi();return{signal:t,account:{async getCurrentUserId(){return(await ma(!1,t)).user_id},async ensureAuthenticated({signal:a}){await ma(!1,a)},onChange(a){return ha.add(a),()=>ha.delete(a)}},authenticatedRequest:Hm,storage:{area:"local",storage:sS(localStorage)},presentation:fS({close:async()=>{st(e)&&(nr("mini program closed"),Bm(),ie.runtimeStatus="closed",s&&jl(!0))},reload:()=>{st(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:a=>{st(e)&&Vl(a)},...s?{getViewportMetrics:()=>{const a=hs.value;return{windowWidth:a.width,windowHeight:a.height,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio,safeArea:{left:0,right:a.width,top:0,bottom:a.height}}},getNavigationBarHeight:()=>N0}:{getDeviceMetrics:()=>Mo.value,applyDisplay:(a,c)=>bn.applyDisplay(a,c),isCapsuleHidden:()=>ie.display.capsuleHidden},onViewportChange:a=>bn.onViewportChange(a)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:a=>{document.title=a}},resolveLaunch:async()=>({configuration:Z1({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,firstParty:r.source==="remote"&&r.firstParty===!0,...ie.miniProgram.bound&&ie.miniProgram.name.trim()?{miniProgramName:ie.miniProgram.name}:{},...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:s?ie.hostPlatform:m0.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:a=>K1(a),confirmFollowAuthor:a=>V1(a)},userDataPresentation:{confirmDataPermission:tS},protocol:dO(e)}}function yi(){return ie.previewMode==="desktop"}function dO(e){return{async invoke(t){vr("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:lO(t)},Date.now(),void 0,e.instanceId)}}}function lO(e){if(typeof e!="string")return typeof e.protocol_type=="string"?e.protocol_type:void 0;const t=/^heybox:\/\/(.+)$/i.exec(e.trim());if(t)try{const r=JSON.parse(decodeURIComponent(t[1]));return St(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function Bm(){document.documentElement.dataset.navigationBarStyle=xl,Vl(xl)}function fO(e,t){st(e)&&t.type==="document_validation"&&typeof t.documentVerifying=="boolean"&&Dn(e,{documentVerifying:t.documentVerifying}),Ge||kt.event(e.instanceId,{source:"runtime",level:t.type==="error"||t.type==="security_violation"?"error":"info",timestamp:t.timestamp,phase:t.type,method:t.method??`runtime.${t.type}`,message:JSON.stringify(E0({...t,generation:e.sequence})),...t.errorCode?{errorCode:t.errorCode}:{}}),e.runtimeId!==t.runtimeId&&(e.runtimeId=t.runtimeId,Dn(e,{runtimeId:t.runtimeId})),st(e)&&e.pendingNavigationReload&&t.type==="bridge_response"&&t.method==="navigation.reload"&&t.outcome==="success"&&(e.pendingNavigationReload=!1,wn("navigation.reload"))}async function Hm(e,t){if(e.redirectPolicy!=="error")throw new Error("Browser Dev Host network 只允许 no-follow redirect policy");const n=e.target.kind==="absolute-url"&&e.source==="public-sdk"&&e.target.kind==="absolute-url"?{url:e.target.url,method:e.method,params:e.params,data:e.data,bodyEncoding:e.bodyEncoding,headers:e.headers,timeout:e.timeout}:void 0;if(!n&&e.source!=="runtime-private")throw new Error("Browser Dev Host 的公开请求只支持 absolute URL");const i=await AO(n?qS:WS,{method:"POST",body:JSON.stringify(n??{target:e.target,method:e.method,params:e.params,data:e.data,headers:e.headers,credentials:e.source==="runtime-private"?e.credentials:void 0,security:e.source==="runtime-private"?e.security:void 0,bodyEncoding:e.bodyEncoding,timeout:e.timeout}),signal:t.signal});!n&&i.status===401&&Nn.invalidate();const s=await i.json();if(!i.ok)throw s;return s}async function ma(e,t){const r=Ya,n=await Fm(lu(jr.signal,t));return Wm(r)?zm(n,e).status:Dc()}async function Fm(e){return await(await fetch(QS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function zm(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<ln)return{changed:!1,status:Dc()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?Qe(e.nickname):void 0,i=e.authenticated?Qe(e.avatar):void 0,s=e.revision!==ln||e.authenticated!==bi||r!==rr||n!==Tc||i!==Ac;return ln=e.revision,bi=e.authenticated,rr=r,Tc=n,Ac=i,Gm(),yn(),t&&s&&ha.forEach(a=>a(rr)),{changed:s,status:Dc()}}function Dc(){return{authenticated:bi,revision:ln,...bi&&rr?{user_id:rr}:{}}}function hO(){if(!(!je.csrfToken||Ge))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Or=jS({csrfToken:je.csrfToken,onDiagnostic:t=>Tr("channel.diagnostic",t),url:e.toString()}),Or.subscribeUpdates((t,r)=>mO(t,r)),Or.connect()}catch{Or?.dispose(),Or=void 0}}function mO(e,t){Nn.invalidate(e.account.revision),PO(In,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Gr("status changed"):(In=$m(e.permissions),gO())}function jm(){if(fs?.close(),fs=void 0,!rr||Ge)return;const e=new EventSource($S);fs=e,e.addEventListener("account-invalidated",()=>{Nn.invalidate()}),e.addEventListener("account-revision",()=>{Nn.invalidate()}),e.onopen=()=>{bc.reset()},e.onerror=()=>{e.close(),bc.schedule()}}async function EO(e){Wm(e)&&await Gr("account revision changed")}async function gO(){Ge||await Gr("permission changed")}async function Vm(e){const t=await fetch(YS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:lu(AbortSignal.timeout(5e3),e)});if(!t.ok)throw new Error("Browser Dev Host bootstrap request failed");const r=await t.json();if(!St(r))throw new Error("Browser Dev Host bootstrap is invalid");const n=LO(r.mobileLaunchRedirect);if(Object.hasOwn(r,"mobileLaunchRedirect")&&r.mobileLaunchRedirect!==void 0&&!n)throw new yO;return{openPlatformBaseUrl:typeof r.openPlatformBaseUrl=="string"?r.openPlatformBaseUrl:void 0,devReadiness:TO(r.devReadiness),csrfToken:typeof r.csrfToken=="string"?r.csrfToken:void 0,diagnosticsToken:typeof r.diagnosticsToken=="string"?r.diagnosticsToken:void 0,defaultLanAddressId:typeof r.defaultLanAddressId=="string"?r.defaultLanAddressId:void 0,devSessionId:typeof r.devSessionId=="string"&&/^[a-f0-9]{32}$/.test(r.devSessionId)?r.devSessionId:void 0,devContext:yl(r.devContext,r.runtimePermissions),browserDevContext:yl(r.browserDevContext??r.devContext,r.runtimePermissions),lanAddresses:Array.isArray(r.lanAddresses)?r.lanAddresses.filter(CO):[],loginAvailable:r.loginAvailable===!0,miniProgram:wO(r.miniProgram),miniProgramSupportsDesktop:r.miniProgramSupportsDesktop===!0,workspaceCardsEnabled:r.workspaceCardsEnabled===!0,mobileLaunchRedirect:n,nativeAppLaunchUnavailableReason:typeof r.nativeAppLaunchUnavailableReason=="string"?r.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof r.miniProgramManifestAccessToken=="string"?r.miniProgramManifestAccessToken:void 0,windowForm:_O(r.windowForm),hostPlatform:pO(r.hostPlatform)}}function pO(e){return JS.includes(e)?e:"unknown"}function _O(e){if(!St(e))return;const t=a=>typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0,r=t(e.defaultWidth),n=t(e.defaultHeight),i=t(e.minWidth),s=t(e.minHeight);return{...r===void 0?{}:{defaultWidth:r},...n===void 0?{}:{defaultHeight:n},...i===void 0?{}:{minWidth:i},...s===void 0?{}:{minHeight:s},...typeof e.resizable=="boolean"?{resizable:e.resizable}:{}}}function TO(e){if(!St(e))return;const t=a=>{if(!(!St(a)||!["ready","pending","blocked","not-configured"].includes(String(a.state))))return{state:a.state,...typeof a.reason=="string"?{reason:a.reason.slice(0,240)}:{}}},r=t(e.browser),n=t(e.mobile),i=t(e.companion);if(!r||!n||!i||!St(e.companion))return;const s=e.companion;return{browser:r,mobile:n,companion:{...i,...typeof s.digest=="string"&&/^[a-f0-9]{64}$/.test(s.digest)?{digest:s.digest}:{},artifacts:Array.isArray(s.artifacts)?s.artifacts.filter(a=>St(a)&&typeof a.alias=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(a.alias)&&["windows-x64","macos-arm64"].includes(String(a.target))).map(({alias:a,target:c})=>({alias:a,target:c})):[]}}}async function AO(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),je.csrfToken&&r.set("x-hb-sdk-csrf",je.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function IO(){uu(),ht||(lc=window.setInterval(()=>{NO()},KS))}function bO(e){const t=Lr(tt),r=!!Dt.localDevLaunchToken,n=Dt.developmentSnapshotDigest;ie.devReadiness=e.devReadiness,ie.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,ie.miniProgramPlatforms=e.devContext.platforms??[],Fl(e.hostPlatform),zl(e.windowForm),ds=e.workspaceCardsEnabled,Rm=du(e),Dt=e.devContext,dn=e.browserDevContext,tt=ti(dn),In=iu(tt),Ea(),e.lanAddresses,e.defaultLanAddressId,e.mobileLaunchRedirect,Mm=e.nativeAppLaunchUnavailableReason,ii=e.devSessionId,cc=e.miniProgramManifestAccessToken,qm(Ym(e)),uu(),(t!==Lr(tt)||r!==!!Dt.localDevLaunchToken||n!==Dt.developmentSnapshotDigest&&(rt?.state==="starting"||rt?.state==="failed"))&&(nr("local permission context changed"),wn("local permission context changed"))}function Ea(){if(ht){ie.localPermissions=D0(),ie.devContextWarning="";return}ie.localPermissions=CS(tt),ie.devContextWarning=tt.source==="anonymous"?"未连接线上上下文":tt.warning?"本地上下文受限,请检查 CLI 状态":"",yn()}function uu(){let e;try{e=g0(Om)}catch{}const t=Dt.miniProgramId?.trim().toLowerCase();let r=Mm?.trim()??"";!r&&(Dt.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!Dt.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&ds&&!ii&&(r="本地调试会话尚未就绪"),!r&&Dt.expiresAt!==void 0&&Dt.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),Gl({...e?{address:e}:{},...t?{miniProgramId:t}:{},...ds&&ii?{devSessionId:ii}:{},...cc?{miniProgramManifestToken:cc}:{},workspaceCardsEnabled:ds,ready:r==="",...r?{unavailableReason:r}:{}})}class yO extends Error{}async function NO(){if(!(Ao||Ge)){Ao=!0;try{const e=await Vm();Bl=Date.now();const t=cn;cn=!1;const r=du(e);if(!t&&r===Rm&&Lr(ti(e.browserDevContext))===Lr(tt)){dn=e.browserDevContext,tt=ti(dn),Ea();return}bO(e),t&&wn("CLI dev session reconnected")}catch{const t=ti(dn);Lr(t)!==Lr(tt)&&(tt=t,In=iu(tt),Ea(),nr("local permission context expired"),wn("local permission context expired"),uu()),Date.now()-Bl>=3e4&&!cn&&(cn=!0,nr("CLI dev session disconnected"),Zm("#device")?.replaceChildren(),ie.runtimeStatus="closed",ie.localPermissions=[],ie.devContextWarning="调试会话已断开",Gl({ready:!1,unavailableReason:"调试会话已断开"}),ie.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}})}finally{Ao=!1}}}function du(e){return JSON.stringify({devReadiness:e.devReadiness,devSessionId:e.devSessionId,defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,devContext:{platforms:e.devContext.platforms,permissionContext:Lr(e.devContext),expiresAt:e.devContext.expiresAt,localDevLaunchToken:e.devContext.localDevLaunchToken,miniProgramId:e.devContext.miniProgramId,source:e.devContext.source},nativeAppLaunchUnavailableReason:e.nativeAppLaunchUnavailableReason,miniProgramManifestAccessToken:e.miniProgramManifestAccessToken,miniProgramSupportsDesktop:e.miniProgramSupportsDesktop,workspaceCardsEnabled:e.workspaceCardsEnabled,hostPlatform:e.hostPlatform,windowForm:e.windowForm})}function Gm(){if(!bi){ie.account={authenticated:!1,avatar:"",nickname:"未登录"};return}ie.account={authenticated:!0,avatar:Ac??"",nickname:Tc||rr||"已登录"}}function Ym(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function qm(e){if(!!!e?.miniProgramId||!e){ie.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试",description:"",version:""},yn();return}ie.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · "),description:e.description??"",version:e.version??""},yn()}function wO(e){if(e===null)return null;if(!St(e))return;const t=Qe(e.miniProgramId)??Qe(e.mini_program_id);if(t)return{miniProgramId:t,...Qe(e.description)?{description:Qe(e.description)}:{},...Qe(e.name)?{name:Qe(e.name)}:{},...Qe(e.iconUrl)??Qe(e.icon_url)?{iconUrl:Qe(e.iconUrl)??Qe(e.icon_url)}:{},...Qe(e.status)?{status:Qe(e.status)}:{},...Qe(e.version)?{version:Qe(e.version)}:{},...Qe(e.developerName)??Qe(e.developer_name)?{developerName:Qe(e.developerName)??Qe(e.developer_name)}:{}}}function Qe(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function Ni(){const e=++uc;dc?.abort();const t=new AbortController;dc=t;const r=si.value,n=!r||r===ie.diagnosticTargetId,i=Xi.value,s=Do.value||(n?rt?.instanceId:void 0),a=()=>!Ge&&e===uc&&r===si.value&&s===(Do.value||(n?rt?.instanceId:void 0));if(!n&&(!i||!s||i.stale||i.state!=="attached"||!i.capabilities.storage)){ie.storage=[],ie.storageError=!i||!i.capabilities.storage?"当前设备不支持存储诊断":"当前设备未连接或没有运行实例";return}if(ht){ie.storage=[{area:"local",key:"preferences",serializedValue:'{"theme":"light","language":"zh-CN"}',bytes:36},{area:"local",key:n?"lastOpenedProject":"deviceModel",serializedValue:n?'"demo-project"':'"iPhone 16 Pro"',bytes:n?14:15}],ie.storageError="";return}if(!s){ie.storage=[],ie.storageError="";return}try{const c=await p0({instanceId:s,resource:"storage"},{csrfToken:je.csrfToken,signal:AbortSignal.any([t.signal,jr.signal])});if(!a())return;if(c.code)throw new Error(c.error??"Storage 诊断查询失败");ie.storage=c.value,ie.storageError=""}catch(c){if(!a())return;ie.storage=[],ie.storageError=Km(c)}}function Qm(e,t=rt){const r=(u,d)=>{if(!(!u||typeof u!="object"))try{return Object.getOwnPropertyDescriptor(u,d)?.value}catch{return}},n=(u,d)=>{const l=r(u,d);return typeof l=="string"?l.slice(0,8192):void 0},i=r(e,"cause"),s=n(e,"stack")??n(i,"stack"),a=n(e,"name")??n(i,"name"),c=typeof i=="string"?i:[n(i,"name"),n(i,"message")].filter(Boolean).join(": ");return{code:n(e,"code")??"RUNTIME_START_FAILED",message:n(e,"message")??(typeof e=="string"?e:"Runtime 启动失败"),phase:t?.hadReady?"running":"starting",...a?{name:a}:{},...s?{stack:s}:{},...c?{cause:c}:{}}}function vr(e,t,r=Date.now(),n,i){DO(Oo(e,t,r,n==="debug"?"log":n),i)}function DO(e,t){if(Ge)return;if(ht){So({...e,targetId:ie.diagnosticTargetId});return}const r=St(e.detail)?e.detail:{};kt.event(t,{source:t&&e.source==="runtime"?"runtime":"host",level:e.level,timestamp:e.timestamp,message:e.summary,method:e.method,...typeof r.phase=="string"?{phase:r.phase}:{},...e.callId?{callId:e.callId}:{},...e.outcome?{outcome:e.outcome}:typeof r.outcome=="string"?{outcome:r.outcome}:{},...e.durationMs===void 0?{}:{durationMs:e.durationMs},...typeof r.startedAt=="number"?{startedAt:r.startedAt}:{},...e.errorCode?{errorCode:e.errorCode}:{},...St(r.network)?{network:r.network}:{}})}async function SO(e){const t=rt;if(!t||e.instanceId!==t.instanceId||!st(t)||!t.runtime)return{code:"closed",error:"该实例已结束"};if(Date.now()>=e.deadline)return{code:"timeout",error:"查询已超过期限"};if(e.resource==="presentation")return{value:t.interactions.snapshot()};if(e.resource==="sandbox")return{code:"unsupported",error:"Browser Dev Host 不提供文件系统能力"};const r=t.runtime,n=r.diagnostics.storage;if(!n)return{code:"unsupported",error:"当前 Host 不支持 Storage 诊断"};const i=AbortSignal.any([jr.signal,t.terminal.signal,AbortSignal.timeout(Math.max(1,e.deadline-Date.now()))]);let s,a;try{a=await Promise.race([n.getSnapshot(),new Promise((c,u)=>{s=()=>u(i.reason),i.addEventListener("abort",s,{once:!0}),i.aborted&&s()})])}catch{return{code:Date.now()>=e.deadline?"timeout":"closed",error:"实例查询已结束或超过期限"}}finally{s&&i.removeEventListener("abort",s)}return!st(t)||r!==t.runtime||e.instanceId!==t.instanceId?{code:"closed",error:"查询期间实例已结束"}:{value:a}}function OO(e,t){Tr("host.message",{message:e,status:t})}function MO(e){Ge||OO(Km(e),"error")}function Tr(e,t){vr(e,t)}function RO(){kt.close(),yc!==void 0&&window.clearTimeout(yc),Nc!==void 0&&window.clearTimeout(Nc),!Ge&&(Ge=!0,ls.dispose(),fc.dispose(),window.__HB_SDK_PREVIEW__===Cm&&delete window.__HB_SDK_PREVIEW__,window.removeEventListener("hb-sdk:refresh-storage",Ni),Ya+=1,jr.abort(new DOMException("Browser Dev Host disposed","AbortError")),Nn.dispose(),nr("Browser Dev Host disposed"),Kt.dispose(),kt.send({operation:"close-target",reason:"Browser Dev Host disposed"}),window.setTimeout(()=>wm.abort(),2e3),fs?.close(),Or?.dispose(),Or=void 0,bc.dispose(),$t!==void 0&&window.clearTimeout($t),$t=void 0,lc!==void 0&&window.clearInterval(lc),ha.clear(),hc?.(),hc=void 0,mc?.(),mc=void 0,Ec?.(),Ec=void 0,gc?.(),gc=void 0,pc?.(),pc=void 0,_c?.(),_c=void 0)}function lu(e,t){return t?AbortSignal.any([e,t]):e}function Wm(e){return!Ge&&e===Ya}function CO(e){return St(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 LO(e){if(!(!St(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 $m(e){return{networkRequest:{...e.networkRequest}}}function PO(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function Km(e){return e instanceof Error&&e.message?e.message:"操作失败"}function St(e){return Object.prototype.toString.call(e)==="[object Object]"}function vO(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function Zm(e){return document.querySelector(e)??void 0}