@heybox/hb-sdk 0.10.0-alpha.2 → 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 (38) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +13 -0
  3. package/dist/cli-chunks/{build-Be8QI9ma.cjs → build-wguxGJim.cjs} +8 -6
  4. package/dist/cli-chunks/{create-CaAGgJXF.cjs → create-mJhWyXDG.cjs} +2 -2
  5. package/dist/cli-chunks/{dev-BS8uwRH2.cjs → dev-CyfaFkKn.cjs} +19 -11
  6. package/dist/cli-chunks/{doctor-CgdrOrS5.cjs → doctor-De8pnp13.cjs} +1 -1
  7. package/dist/cli-chunks/{game-binding-guide-DX8uXx0V.cjs → game-binding-guide-C9ICs9zj.cjs} +3 -3
  8. package/dist/cli-chunks/{game-bindings-CjI0oA1t.cjs → game-bindings-Bg2xoKZY.cjs} +4 -4
  9. package/dist/cli-chunks/{games-C8A0PCo-.cjs → games-CAhkA4nh.cjs} +1 -1
  10. package/dist/cli-chunks/{index-BTOX41Vr.cjs → index-B8rzkV1n.cjs} +1 -1
  11. package/dist/cli-chunks/{index-CMbVUUpA.cjs → index-pGP_FOkj.cjs} +24 -22
  12. package/dist/cli-chunks/{index.esm-D7A_j5MA.cjs → index.esm-B8H9EwB1.cjs} +67 -0
  13. package/dist/cli-chunks/{index.esm-CIBT3Na1.cjs → index.esm-BqyU_JCg.cjs} +9 -9
  14. package/dist/cli-chunks/{login-BWuLgJWT.cjs → login-BYLNpsQ1.cjs} +1 -1
  15. package/dist/cli-chunks/{project-vite-FWtHl3XL.cjs → project-vite-BRUA9Vng.cjs} +1 -1
  16. package/dist/cli-chunks/{remote-R1jgvh-Z.cjs → remote-BAf86E8n.cjs} +13 -9
  17. package/dist/cli-chunks/{runtime-permission-env-BuXOApO4.cjs → runtime-permission-env-XMA-YAuB.cjs} +392 -113
  18. package/dist/cli-chunks/{skill-EM-Uv3Rj.cjs → skill-D6kR1-g0.cjs} +2 -2
  19. package/dist/cli-chunks/{version-BXh-cltM.cjs → version-SUKtha-_.cjs} +1 -1
  20. package/dist/cli.cjs +1 -1
  21. package/dist/devtools/browser-dev-host/assets/browser-dev-host-C2-qtvqp.js +224 -0
  22. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-BXVw6d6N.js → desktop-app-launch-DVnZ7dFB.js} +1 -1
  23. package/dist/devtools/browser-dev-host/assets/{index-CABlopeJ.js → index-DCPdAyuJ.js} +3 -3
  24. package/dist/devtools/browser-dev-host/index.html +2 -2
  25. package/dist/index.cjs.js +284 -1
  26. package/dist/index.esm.js +284 -1
  27. package/dist/miniapp-publish.cjs.js +215 -116
  28. package/dist/miniapp-publish.esm.js +214 -117
  29. package/dist/protocol.cjs.js +57 -0
  30. package/dist/protocol.esm.js +57 -0
  31. package/dist/vite.cjs.js +238 -96
  32. package/dist/vite.esm.js +238 -96
  33. package/package.json +6 -6
  34. package/skill/skill.json +4 -4
  35. package/types/index.d.ts +81 -6
  36. package/types/miniapp-publish/index.d.ts +30 -15
  37. package/types/vite/index.d.ts +7 -0
  38. package/dist/devtools/browser-dev-host/assets/browser-dev-host-CpphzCg4.js +0 -224
@@ -0,0 +1,224 @@
1
+ import{m as Jm,H as Eu,a_ as e0,bA as t0,a3 as r0,bh as n0,bi as i0,n as kt,bK as se,ba as zl,l as jl,aM as s0,e as gu,aR as a0,aD as o0,k as c0,aN as u0,bE as Rn,aY as si,aX as Do,aZ as Xi,b2 as Vl,b4 as d0,f as hs,v as l0,ap as ms,Z as Oc,aQ as f0,j as So,at as Oo,h as h0,be as Gl,aI as m0,G as E0,b0 as Yl,U as g0,z as p0,aF as _0,y as T0,bb as A0,bC as ql,bB as Ql,b6 as I0,g as Mo,aH as b0,b as Mr,c as y0}from"./desktop-app-launch-DVnZ7dFB.js";function N0(){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 w0(){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"]'},pu=15e3,D0=32*1024*1024,_u="data-hb-preview-capture-device",qa="data-hb-preview-capture-ancestor",Tu="data-hb-preview-capture-surface",Au=64,S0=1024;function O0(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??pu;if(!Number.isFinite(n)||n<=0||n>pu)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:p,name:_,previous:y}of l.attributes)p.getAttribute(_)===d&&(y===null?p.removeAttribute(_):p.setAttribute(_,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 p=h.getBoundingClientRect();return["left","top","width","height"].every(_=>Math.abs(p[_]-f[_])<.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>D0)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],p=d.scope==="device"?f:t.querySelector(vi[d.scope]);if(!p||p!==f&&!f.contains(p))throw ut("CAPTURE_TARGET_UNAVAILABLE","截图内容尚未创建");const _=f.getBoundingClientRect();if(!(_.width>0&&_.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",Y=>Y.preventDefault(),{passive:!1}),y.addEventListener("touchmove",Y=>Y.preventDefault(),{passive:!1});const D=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:D};i=N,N.timer=setTimeout(()=>a(N.token),Math.max(0,D-Date.now()));const v=()=>a(N.token);l?.addEventListener("abort",v,{once:!0}),N.removeAbort=()=>l?.removeEventListener("abort",v);const I=()=>{const{viewport:Y}=N;(r.innerWidth!==Y.width||r.innerHeight!==Y.height||r.devicePixelRatio!==Y.devicePixelRatio)&&a(N.token)};r.addEventListener("resize",I),N.removeResize=()=>r.removeEventListener("resize",I);const H=()=>{if(l?.throwIfAborted(),i!==N||Date.now()>=D)throw ut("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{y.src=d.previewImage,await y.decode(),H();const Y=N.token,R=`[${_u}="${Y}"]`,x=r.getComputedStyle(f),U=new r.DOMMatrixReadOnly(x.transform==="none"?void 0:x.transform),G=Math.atan2(U.b,U.a),V=f.querySelector(".desktop-window__surface"),te=V?V.offsetWidth:Number.parseFloat(x.width),z=V?V.offsetHeight:Number.parseFloat(x.height),j=x.backgroundColor,ee=r.getComputedStyle(t.body).backgroundColor,J=ce=>!ce||ce==="transparent"||ce==="rgba(0, 0, 0, 0)",Q=J(j)?J(ee)?"#fff":ee:j;if(!(te>0&&z>0))throw ut("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");H(),t.body.append(y),s(N,f,_u),V&&s(N,V,Tu);for(let ce=f.parentElement;ce;ce=ce.parentElement)s(N,ce,qa);const P=t.createElement("style");N.style=P;const w=`
2
+ [${qa}="${Y}"] {overflow:visible!important;scrollbar-width:none!important;}
3
+ [${qa}="${Y}"]::-webkit-scrollbar {display:none!important;}
4
+ [${Tu}="${Y}"] {transform:none!important;transition:none!important;}
5
+ `,B=(ce,pe,ye=0,he=0)=>`${R} {position:absolute!important;left:${ce}px!important;top:${pe}px!important;width:${te}px!important;height:${z}px!important;transform:translate(${ye}px,${he}px) rotate(${G}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${Q}!important;}`;P.textContent=w+B(0,0),H(),t.head.append(P);const O=f.getBoundingClientRect(),W=t.querySelector(vi.app),$=W&&f.contains(W)?W.getBoundingClientRect():void 0,Z=$&&$.width>0&&$.height>0?$:void 0,ie=Z?Math.floor(r.innerWidth-1-(Z.left-O.left)):r.innerWidth+64,me=Z?Math.floor(r.innerHeight-1-(Z.top-O.top)):32,De=ie-O.left,Pe=me-O.top;H(),P.textContent=w+B(De,Pe);const E=f.getBoundingClientRect();P.textContent=w+B(De,Pe,ie-E.left,me-E.top),H();const m=p.getBoundingClientRect(),M=Math.floor(qr(m.left+r.scrollX)),S=Math.floor(qr(m.top+r.scrollY)),C={x:M,y:S,width:Math.ceil(qr(m.right+r.scrollX))-M,height:Math.ceil(qr(m.bottom+r.scrollY))-S};if(!(C.width>0&&C.height>0)||C.x<0||C.y<0)throw ut("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(Z&&W){const ce=W.getBoundingClientRect();if(!(ce.left<r.innerWidth&&ce.top<r.innerHeight&&ce.right>0&&ce.bottom>0))throw ut("CAPTURE_LAYOUT_INVALID","无法保持 iframe 的最小绘制区域");const pe=f.getBoundingClientRect(),ye=Math.floor(qr(pe.left))-1,he=Math.floor(qr(pe.top))-1,Me=r.innerWidth-ye,Ne=r.innerHeight-he;if(ye<0||he<0||Me<=0||Ne<=0||Me>Au||Ne>Au||Me*Ne>S0)throw ut("CAPTURE_LAYOUT_INVALID","无法在有界角部保持完整设备绘制,请改用 --scale css");y.style.clipPath=`polygon(0 0,100% 0,100% ${he}px,${ye}px ${he}px,${ye}px 100%,0 100%)`,y.setAttribute("data-hb-preview-capture-corner",JSON.stringify({x:ye,y:he,width:Me,height:Ne}))}const K=t.createElement("div");if(K.setAttribute("aria-hidden","true"),K.style.cssText=`position:absolute;left:${C.x+C.width+2}px;top:${C.y+C.height+2}px;width:1px;height:1px;pointer-events:none;opacity:0;`,N.bounds=K,H(),t.body.append(K),N.target=p,N.rect=m,await M0(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:Y,clip:C,devicePixelRatio:r.devicePixelRatio,expiresAt:D}}catch(Y){throw a(N.token),Y}}return{prepare:u,restore:a,cancel:d=>i?.operationId!==d?!1:(a(i.token),!0),dispose:()=>{i&&a(i.token)}}}function M0(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",Mc="user.games.getOverview",Es="user.data.query",Qn="user.data.sync",gs="user.data.file",Rc="user.dataPermission.request",Cc="user.dataPermission.get",Lc="user.dataPermission.set",Pc="user.dataPermission.openSettings",vc="user.dataPermission.revokeSession",Wl=[Mc,Es,Qn,gs,Rc,Cc,Lc,Pc,vc],ps="workspaceCards.requestRefresh",_s="auth.getAccountState",Ts="auth.login",As="user.getFollowStatus",Is="user.requestFollowAuthor",R0="gameSaves.list",C0="gameSaves.sync",L0="gameSaves.getFile",P0="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"})),...[R0,C0,L0,P0].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),...Wl.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",$l=2,Kl="hb_mini_bridge_nonce",Zl="sdk.handshake",ki="runtime.location.probe",v0="sdk.location.report",k0="sdk.csp.violation",Xl="operation.progress",x0="companion.session.output",U0="companion.session.exit",B0="companion.session.ownershipLost";function H0(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===Zl&&e.error===void 0&&Q0(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||W0(e.error)):e.type==="event"?!We(e.method)||e.error!==void 0?!1:e.method===Xl?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 kc(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function Jl(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"]):Jl(e.root)&&kc(e.relativePath)&&bt(e,["kind","root","relativePath"])}function ef(e){return!Rt(e)||e.kind!=="directory"?!1:We(e.handleId)?bt(e,["kind","handleId"]):Jl(e.root)&&(e.relativePath==="."||kc(e.relativePath))&&bt(e,["kind","root","relativePath"])}function F0(e){return Rt(e)&&e.kind==="file"&&We(e.name)&&$0(e.mode)&&kr(e.ref)&&bt(e,["kind","name","mode","ref"])}const tf=20,Iu=["type","mimeType","size","width","height","previewUrl","file"];function z0(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&&(!K0(e.maxCount,1,tf)||e.source==="camera"&&e.maxCount!==1))}function rf(e){if(!Rt(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!bt(e,t?[...Iu,"durationMs"]:Iu)||!We(e.mimeType)||!fr(e.size)||!bu(e.width)||!bu(e.height)||!We(e.previewUrl)||!V0(e.file)?!1:t?fr(e.durationMs):!0}function j0(e){if(!Array.isArray(e)||e.length<1||e.length>tf)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!rf(e[t]))return!1;return!0}function V0(e){return!F0(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&We(e.ref.handleId)}function nf(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function G0(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 Y0(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 G0(e)||Y0(e)||Rt(e)&&bt(e,["watching"])&&e.watching===!0}function Q0(e){return Rt(e)&&We(e.href)&&typeof e.userAgent=="string"&&We(e.sdkVersion)}function W0(e){return Rt(e)&&We(e.code)&&typeof e.message=="string"}function $0(e){return e==="read"||e==="readwrite"}function fr(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function bu(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function K0(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 sf={ark:"明日方舟",black_myth_wukong:"黑神话悟空",task_bar_hero:"任务栏英雄",phantom_blade_zero:"影之刃零"},af=Object.keys(sf),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),Z0=new Set(Rr),X0=new Set(af);function dr(e){return Z0.has(e)}function yu(e){return X0.has(e)}function xc(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 J0="同步时,原始存档将上传至小黑盒;向小程序提供原始文件仍需单独许可。",zr=["userInfo","steamLibrary","share","storage","cloud_storage","cloud_rooms","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards","user_game_data","post"],Uc=[{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:Wl,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 eE=30;function tE(e){if(typeof e!="string")throw new Error("purpose 必须是字符串");const t=e.trim(),r=Array.from(t);if(r.length<1||r.length>eE)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 of(e,!1)}function rE(e){return of(e,!0)}function of(e,t){if(!Nu(e))throw new Error("resources 必须是资源声明对象;每项资源必须填写 purpose");const r={};for(const n of Object.keys(e).sort()){const i=e[n];if(!Nu(i)||Object.keys(i).length!==1||!Object.prototype.hasOwnProperty.call(i,"purpose"))throw new Error(`resources.${n} 必须且只能包含 purpose`);let s;try{s=tE(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 nE(e){return Rr.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function Nu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cf(e,t,r,n){return JSON.stringify(["user-game-data-purpose-v1",e,t,r,n])}const iE=new Set(zr);function sE(e){return iE.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),!!sE(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=rE(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 uf(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 aE(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 Bc(e){const t=ft(e.runtimePermissions),r=uf(e.localDevGrant),n=t.valid?t.permissions:{};for(const a of zr)e.declaredPermissions[a]?.enabled!==!0?delete n[a]:Uc.some(c=>c.key===a&&c.access==="declaration")?n[a]={key:a,status:"enabled",config:oE(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=df(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 oE(e,t){const r=Uc.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 df(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cn(e,t){return df(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const En=["identity","profile","steam_account"],cE=/^[a-z][a-z0-9-]{0,31}$/,lf=["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 wu;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.")}}(wu=globalThis).__zod_globalConfig??(wu.__zod_globalConfig={});const Du=globalThis.__zod_globalConfig;function Sn(e){return e&&Object.assign(Du,e),Du}function uE(e,t){return typeof t=="bigint"?t.toString():t}function dE(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ff(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const Su=Symbol("evaluating");function gt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Su)return n===void 0&&(n=Su,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}const hf="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function lE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ou(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fE(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 hE(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const mE={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 EE(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 mf(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 Ef=(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,uE,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},gE=Be("$ZodError",Ef),Ra=Be("$ZodError",Ef,{Parent:Error}),pE=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 hf(c,i?.callee),c}return a.value},_E=pE(Ra),TE=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 hf(c,i?.callee),c}return a.value},AE=TE(Ra),IE=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??gE)(s.issues.map(a=>wi(a,i,Sn())))}:{success:!0,data:s.value}},gf=IE(Ra),bE=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}},pf=bE(Ra),yE=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},NE=/^-?\d+$/,wE=/^-?\d+(?:\.\d+)?$/,DE=/^null$/i,Ca=Be("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),_f={number:"number",bigint:"bigint",object:"date"},SE=Be("$ZodCheckLessThan",(e,t)=>{Ca.init(e,t);const r=_f[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})}}),OE=Be("$ZodCheckGreaterThan",(e,t)=>{Ca.init(e,t);const r=_f[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})}}),ME=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]=mE[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=NE)}),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})}}),RE=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=()=>{})}),CE=Be("$ZodCheckRegex",(e,t)=>{RE.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})}}),LE={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=LE;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(EE(a)||!h._zod.def.when(a))continue}else if(d)continue;const f=a.issues.length,p=h._zod.check(a);if(p instanceof Promise&&u?.async===!1)throw new Wn;if(l||p instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await p,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=gf(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return pf(e,i).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),PE=Be("$ZodString",(e,t)=>{Ut.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??yE(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}}),Tf=Be("$ZodNumber",(e,t)=>{Ut.init(e,t),e._zod.pattern=e._zod.bag.pattern??wE,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}}),vE=Be("$ZodNumberFormat",(e,t)=>{ME.init(e,t),Tf.init(e,t)}),kE=Be("$ZodNull",(e,t)=>{Ut.init(e,t),e._zod.pattern=DE,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}}),xE=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 Mu(e,t,r){e.issues.length&&t.issues.push(...mf(r,e.issues)),t.value[r]=e.value}const UE=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=>Mu(d,r,a))):Mu(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(...mf(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 BE(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=hE(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function HE(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 p=u.run({value:t[f],issues:[]},n);p instanceof Promise?e.push(p.then(_=>Xs(_,r,f,t,l,h))):Xs(p,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 FE=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=dE(()=>BE(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=lE,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 p=h[f],_=p._zod.optin==="optional",y=p._zod.optout==="optional",D=p._zod.run({value:d[f],issues:[]},u);D instanceof Promise?l.push(D.then(N=>Xs(N,c,f,d,_,y))):Xs(D,c,f,d,_,y)}return s?HE(l,d,c,u,n.value,e):l.length?Promise.all(l).then(()=>c):c}});function Ru(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 zE=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=>ff(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=>Ru(c,n,e,i)):Ru(a,n,e,i)}}),jE=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"?Ou(n):n?Ou(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 Cu(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const VE=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(`^(${ff(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=>Cu(a,i)):Cu(s,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),GE=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 YE(e,t){return new e({type:"string",...Ct()})}function qE(e,t){return new e({type:"number",checks:[],...Ct()})}function QE(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Ct()})}function WE(e,t){return new e({type:"null",...Ct()})}function $E(e,t){return new e({type:"never",...Ct()})}function Te(e,t){return new SE({check:"less_than",...Ct(),value:e,inclusive:!0})}function Ae(e,t){return new OE({check:"greater_than",...Ct(),value:e,inclusive:!0})}function Ie(e,t){return new CE({check:"string_format",format:"regex",...Ct(),pattern:e})}Sn({jitless:!0});function Af(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 KE(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return Af(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)=>_E(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>gf(e,r,n),e.parseAsync=async(r,n)=>AE(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>pf(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)=>fE(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),ZE=Be("ZodMiniString",(e,t)=>{PE.init(e,t),Zt.init(e,t)});function L(e){return YE(ZE)}const If=Be("ZodMiniNumber",(e,t)=>{Tf.init(e,t),Zt.init(e,t)});function re(e){return qE(If)}const XE=Be("ZodMiniNumberFormat",(e,t)=>{vE.init(e,t),If.init(e,t)});function be(e){return QE(XE)}const JE=Be("ZodMiniNull",(e,t)=>{kE.init(e,t),Zt.init(e,t)});function ge(e){return WE(JE)}const eg=Be("ZodMiniNever",(e,t)=>{xE.init(e,t),Zt.init(e,t)});function tg(e){return $E(eg)}const rg=Be("ZodMiniArray",(e,t)=>{UE.init(e,t),Zt.init(e,t)});function fe(e,t){return new rg({type:"array",element:e,...Ct()})}const ng=Be("ZodMiniObject",(e,t)=>{FE.init(e,t),Zt.init(e,t),gt(e,"shape",()=>t.shape)});function Ee(e,t){return new ng({type:"object",shape:e,catchall:tg(),...Ct()})}const ig=Be("ZodMiniUnion",(e,t)=>{zE.init(e,t),Zt.init(e,t)});function k(e,t){return new ig({type:"union",options:e,...Ct()})}const sg=Be("ZodMiniLiteral",(e,t)=>{jE.init(e,t),Zt.init(e,t)});function we(e,t){return new sg({type:"literal",values:Array.isArray(e)?e:[e],...Ct()})}const ag=Be("ZodMiniOptional",(e,t)=>{VE.init(e,t),Zt.init(e,t)});function X(e){return new ag({type:"optional",innerType:e})}const og=Be("ZodMiniLazy",(e,t)=>{GE.init(e,t),Zt.init(e,t)});function ue(e){return new og({type:"lazy",getter:e})}const de={PcHardwareInfo:Ee({updatedAt:re(),cpu:X(Ee({name:L()})),gpu:X(Ee({name:L()})),memory:X(Ee({name:X(L()),capacityGiB:X(re())})),motherboard:X(Ee({name:L()})),disks:X(fe(Ee({name:L()})))}),ArkProfile:Ee({uid:L(),name:L(),level:re(),avatar:X(ue(()=>de.ArkPlayerAvatar)),characterCount:re(),totalCharacterCount:re(),mainStageProgress:L(),rogueLevel:re(),campaignFullKillCount:re(),tag:L(),observedAt:X(k([L(),re()])),lastOnlineTs:X(k([L(),re()])),registerTs:X(k([L(),re()])),changeTime:X(k([L(),re()])),operators:X(fe(ue(()=>de.ArkOperator)))}),ArkPlayerAvatar:Ee({url:L(),type:L(),id:L()}),ArkOperator:Ee({characterId:L(),name:L(),profession:L(),evolvePhase:re(),potentialRank:re()}),ArkGachaAnalysis:Ee({uid:L(),year:re(),total:re(),srCount:re(),upCount:re(),missCount:re(),careerEvaluation:L(),careerIsLucky:k([we(!1),we(!0)]),pools:fe(ue(()=>de.ArkGachaPoolStat)),records:fe(ue(()=>de.ArkGachaAnalysisRecord)),luckyLottery:fe(re())}),ArkGachaPoolStat:Ee({poolId:L(),totalCost:re(),ssrCount:re(),ssrCost:re(),records:fe(ue(()=>de.ArkGachaAnalysisRecord))}),ArkGachaAnalysisRecord:Ee({name:L(),timestamp:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),diff:re(),negativeDiff:re(),tag:L(),missUp:k([we(!1),we(!0)])}),GachaRecord:Ee({id:L(),name:L(),pool:L(),rarity:re(),timestamp:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),BlackMythWukongSave:Ee({level:X(re()),newGamePlusCount:X(re()),gameTotalTime:X(re()),playerDeathCount:X(re()),totalMoney:X(L()),meditationList:X(k([ge(),fe(re())])),monsterCollectionList:X(k([ge(),fe(re())])),returnPointList:X(k([ge(),fe(re())])),activatedWeaponIdList:X(k([ge(),fe(L())])),activatedEquipIdList:X(k([ge(),fe(re())])),magicArtifactList:X(k([ge(),fe(re())])),soulSkillIdList:X(k([ge(),fe(re())])),huluIdLits:X(k([ge(),fe(re())])),wineIdList:X(k([ge(),fe(re())])),wineIdPartnerList:X(k([ge(),fe(re())])),cropIdList:X(k([ge(),fe(re())])),recipeIdList:X(k([ge(),fe(re())])),wearedWaeponId:X(L()),wearedMagicArtifact:X(re()),wearedSoulSkill:X(re()),wearedHead:X(re()),wearedUpware:X(re()),wearedArm:X(re()),wearedFoot:X(re()),wearedHulu:X(re()),wearedAccessoryList:X(k([ge(),fe(re())])),spellQishu:X(k([ge(),fe(re())])),spellShenfa:X(k([ge(),fe(re())])),spellHaomao:X(k([ge(),fe(re())])),spellBianshen:X(k([ge(),fe(re())])),bossRushBossgroup:X(ue(()=>de.BlackMythWukongBossRushData)),bossRushRefight:X(ue(()=>de.BlackMythWukongBossRefightData))}),BlackMythWukongBossRushData:Ee({bossGroups:X(k([ge(),fe(ue(()=>de.BlackMythWukongBossRushRecord))]))}),BlackMythWukongBossRushRecord:Ee({bossGroupId:X(re()),isPassed:X(k([we(!1),we(!0)])),bestRecords:X(k([ge(),fe(ue(()=>de.BlackMythWukongBattleRecord))])),encounterBossIndex:X(re()),battleCount:X(re())}),BlackMythWukongBattleRecord:Ee({battleId:X(L()),battleData:X(ue(()=>de.BlackMythWukongBattleData))}),BlackMythWukongBattleData:Ee({totalTime:X(re()),score:X(re()),debuffList:X(k([ge(),fe(re())])),targetId:X(re()),archiveTime:X(L()),roleBase:X(ue(()=>de.BlackMythWukongRoleBase)),battleStyleInfo:X(ue(()=>de.BlackMythWukongBattleStyleInfo)),damageInfo:X(ue(()=>de.BlackMythWukongDamageInfo))}),BlackMythWukongRoleBase:Ee({level:X(re()),atk:X(re()),hpMax:X(re()),staminaMax:X(re()),mpMax:X(re())}),BlackMythWukongBattleStyleInfo:Ee({spellList:X(k([ge(),fe(ue(()=>de.BlackMythWukongCast))])),fabaoInfo:X(ue(()=>de.BlackMythWukongCast)),soulInfo:X(ue(()=>de.BlackMythWukongCast)),itemCount:X(re()),wineCount:X(re()),rollCount:X(re()),defuseCount:X(re()),fourPeCount:X(re())}),BlackMythWukongCast:Ee({castId:X(re()),castCount:X(re())}),BlackMythWukongDamageInfo:Ee({totalDamage:X(k([L(),re()])),hightestDamage:X(k([L(),re()])),criticalDmgRate:X(re()),totalBeDamaged:X(k([L(),re()])),criticalDmgTotal:X(k([L(),re()])),elemDotDmgTotal:X(k([L(),re()])),elemDotDmgRate:X(re())}),BlackMythWukongBossRefightData:Ee({bossList:X(k([ge(),fe(ue(()=>de.BlackMythWukongBossRefightRecord))]))}),BlackMythWukongBossRefightRecord:Ee({bossId:X(re()),passedMaxLevel:X(re()),lastChallengeLevel:X(re()),bestRecords:X(k([ge(),fe(ue(()=>de.BlackMythWukongBattleRecord))])),refightStatisticsList:X(k([ge(),fe(ue(()=>de.BlackMythWukongRefightStatistic))]))}),BlackMythWukongRefightStatistic:Ee({challengeLevel:X(re()),battleCount:X(re())}),TaskBarHeroSave:Ee({update_time:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),game_version:L(),account_version:L(),play_time:re(),last_saved_time:L(),common:ue(()=>de.TaskBarHeroCommon),summary:ue(()=>de.TaskBarHeroSummary),heroes:k([ge(),fe(ue(()=>de.TaskBarHeroHero))]),rune_save_data:k([ge(),fe(ue(()=>de.TaskBarHeroRune))]),pets:k([ge(),fe(ue(()=>de.TaskBarHeroPet))]),attributes:k([ge(),fe(ue(()=>de.TaskBarHeroAttribute))]),inventory_slots:k([ge(),fe(ue(()=>de.TaskBarHeroItemSlot))]),stash_slots:k([ge(),fe(ue(()=>de.TaskBarHeroItemSlot))]),item_instances:k([ge(),fe(ue(()=>de.TaskBarHeroItemInstance))]),values:ue(()=>de.TaskBarHeroValueSummary)}),TaskBarHeroCommon:Ee({max_completed_stage:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_key:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_wave:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),arranged_hero_keys:k([ge(),fe(k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),arranged_pet_key:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroSummary:Ee({max_hero_level:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),learned_rune_count:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unlocked_hero:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total_hero:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_count:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inventory_slots:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stash_slots:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroHero:Ee({hero_key:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),hero_level:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:k([we(!1),we(!0)]),hero_exp:re(),ability_point:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),allocated_hero_ability_point:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),equipped_item_ids:k([ge(),fe(L())]),equipped_skill_keys:k([ge(),fe(k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),unlocked_attribute_group_keys:k([ge(),fe(k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]))])}),TaskBarHeroRune:Ee({rune_key:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroPet:Ee({pet_key:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:k([we(!1),we(!0)])}),TaskBarHeroAttribute:Ee({key:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroItemSlot:Ee({index:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_unique_id:L(),is_unlock:k([we(!1),we(!0)]),is_unlocked_by_rune:k([we(!1),we(!0)])}),TaskBarHeroItemInstance:Ee({item_key:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unique_id:L(),is_chaotic:k([we(!1),we(!0)]),is_blocked:k([we(!1),we(!0)]),is_server_pending_item:k([we(!1),we(!0)]),enchant_count:k([ge(),fe(k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),enchant_data:k([ge(),fe(ue(()=>de.TaskBarHeroEnchantData))]),item_get_source_type:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),decoration_applied_total_count:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),engraving_applied_total_count:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inscription_applied_total_count:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroEnchantData:Ee({stat_mod_key:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),tier:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),value:re(),recipe_type:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),mod_type:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),material_key:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stat_type:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroValueSummary:Ee({market_value:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),price_state:L(),currency:L()}),PhantomBladeZeroSave:Ee({defaultSlot:L(),slots:fe(ue(()=>de.PhantomBladeZeroSaveSlot))}),PhantomBladeZeroSaveSlot:Ee({slot:L(),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:k([ge(),ue(()=>de.PhantomBladeZeroQuestDetails)]),inventory_details:k([ge(),fe(ue(()=>de.PhantomBladeZeroInventoryItem))]),detail:ue(()=>de.PhantomBladeZeroSlotDetail)}),PhantomBladeZeroSlotHead:Ee({saveTime:L(),currentLevel:L(),cycle:L(),difficulty:ue(()=>de.PhantomBladeZeroSlotDifficulty)}),PhantomBladeZeroSlotDifficulty:Ee({raw:re(),name:L()}),PhantomBladeZeroSlotFirstClear:Ee({clearDate:ue(()=>de.PhantomBladeZeroUnavailableValue),cycles:k([ge(),fe(ue(()=>de.PhantomBladeZeroClearanceRecord))])}),PhantomBladeZeroUnavailableValue:Ee({value:ge(),reason:L()}),PhantomBladeZeroClearanceRecord:Ee({Cycle:X(k([ge(),re()])),Ending:re(),Difficulty:re(),GameTime:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),Completion:re(),DiedTimes:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotProgress:Ee({playTimeSeconds:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),playTime:L(),lastLaunch:ue(()=>de.PhantomBladeZeroUnavailableValue),narrativePercentage:re(),chapter:L(),remainingDays:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCombat:Ee({loadout:X(ue(()=>de.PhantomBladeZeroSlotLoadout)),totalDeaths:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),cycleDeaths:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bossKillTotal:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),currentMainWeapon:X(k([ge(),ue(()=>de.PhantomBladeZeroNamedItem)])),mainWeapon:ue(()=>de.PhantomBladeZeroCollectionCount),currentShaqi:X(k([ge(),ue(()=>de.PhantomBladeZeroNamedItem)])),shaqi:ue(()=>de.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroSlotLoadout:Ee({states:X(k([ge(),fe(ue(()=>de.PhantomBladeZeroLoadoutState))])),main_weapons:k([ge(),fe(L())]),shaqi_weapons:k([ge(),fe(L())]),accessory_ids:k([ge(),fe(L())]),top_medicine:L(),bottom_medicine:L(),current_weapon_index:re(),current_shaqi_weapon_index:re()}),PhantomBladeZeroLoadoutState:Ee({category:L(),id:L(),level:X(re()),soul_forged:X(k([we(!1),we(!0)])),reincarnation_count:X(re())}),PhantomBladeZeroNamedItem:Ee({id:L(),name:L()}),PhantomBladeZeroCollectionCount:Ee({unknown:X(k([L(),re()])),done:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotAchievementSummary:Ee({unlocked:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:L()}),PhantomBladeZeroSlotBossSummary:Ee({groups:k([ge(),fe(ue(()=>de.PhantomBladeZeroBossGroup))])}),PhantomBladeZeroBossGroup:Ee({map:L(),mapName:L(),count:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bosses:k([ge(),fe(ue(()=>de.PhantomBladeZeroBoss))])}),PhantomBladeZeroBoss:Ee({id:L(),classPath:L(),map:L(),mapName:L(),encountered:k([we(!1),we(!0)]),killed:k([we(!1),we(!0)]),kill:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),records:k([ge(),fe(ue(()=>de.PhantomBladeZeroBossRecord))])}),PhantomBladeZeroBossRecord:Ee({cycle:L(),diff:L(),diffName:L(),kill:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCollectibles:Ee({overall:ue(()=>de.PhantomBladeZeroCollectionSummary),craneBellCount:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),byBigMap:k([ge(),fe(ue(()=>de.PhantomBladeZeroBigMapProgress))]),currentChapter:ue(()=>de.PhantomBladeZeroChapterProgress)}),PhantomBladeZeroCollectionSummary:Ee({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:Ee({unknown:X(k([L(),re()])),mapID:L(),name:L(),pct:re(),done:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),subMaps:k([ge(),fe(L())])}),PhantomBladeZeroChapterProgress:Ee({unknown:X(k([L(),re()])),mapID:L(),pct:re(),done:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:L()}),PhantomBladeZeroQuestDetails:Ee({CurrentMainQuestPath:L(),CurrentTutorialQuestPath:L(),TrackedQuestPath:L(),TrackedBranchID:L(),TrackedTaskPointID:L(),ManualTrackingOptOut:k([we(!1),we(!0)]),NarrativeSavedQuests:k([ge(),fe(ue(()=>de.PhantomBladeZeroQuest))])}),PhantomBladeZeroQuest:Ee({QuestClass:L(),QuestCompletion:L(),QuestBranches:k([ge(),fe(ue(()=>de.PhantomBladeZeroQuestBranch))]),CompletedBranches:k([ge(),fe(L())]),ReachedStateNames:k([ge(),fe(L())])}),PhantomBladeZeroQuestBranch:Ee({BranchID:L(),TasksProgress:k([ge(),fe(k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),BranchType:L()}),PhantomBladeZeroInventoryItem:Ee({id:L(),amount:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotDetail:Ee({bell:k([ge(),fe(ue(()=>de.PhantomBladeZeroBellDetail))]),weapon:k([ge(),fe(ue(()=>de.PhantomBladeZeroItemDetail))]),shaqi:k([ge(),fe(ue(()=>de.PhantomBladeZeroItemDetail))]),accessory:k([ge(),fe(ue(()=>de.PhantomBladeZeroItemDetail))]),medicine:k([ge(),fe(ue(()=>de.PhantomBladeZeroItemDetail))]),challenge:k([ge(),fe(ue(()=>de.PhantomBladeZeroChallengeDetail))]),hupo:k([ge(),fe(ue(()=>de.PhantomBladeZeroWorldItemDetail))]),heishi:k([ge(),fe(ue(()=>de.PhantomBladeZeroWorldItemDetail))]),flower:k([ge(),fe(ue(()=>de.PhantomBladeZeroItemDetail))]),achievements:k([ge(),fe(ue(()=>de.PhantomBladeZeroAchievementDetail))])}),PhantomBladeZeroBellDetail:Ee({unknown:X(k([we(!1),we(!0)])),id:L(),done:k([we(!1),we(!0)]),equip:k([we(!1),we(!0)])}),PhantomBladeZeroItemDetail:Ee({level:X(re()),soul_forged:X(k([we(!1),we(!0)])),reincarnation_count:X(re()),unknown:X(k([we(!1),we(!0)])),id:L(),name:L(),done:k([we(!1),we(!0)]),equip:k([we(!1),we(!0)]),locs:k([ge(),fe(ue(()=>de.PhantomBladeZeroLocation))])}),PhantomBladeZeroLocation:Ee({map:L(),mapName:L(),x:re(),y:re(),z:re()}),PhantomBladeZeroChallengeDetail:Ee({key:X(L()),unknown:X(k([we(!1),we(!0)])),index:k([be().check(Ae(-9007199254740991),Te(9007199254740991)),L().check(Ie(new RegExp("^-?(0|[1-9][0-9]*)$")))]),guids:k([ge(),fe(L())]),done:k([we(!1),we(!0)]),locs:k([ge(),fe(ue(()=>de.PhantomBladeZeroLocation))])}),PhantomBladeZeroWorldItemDetail:Ee({key:X(L()),unknown:X(k([we(!1),we(!0)])),id:L(),saveGuid:L(),mobDomain:L(),done:k([we(!1),we(!0)]),locs:k([ge(),fe(ue(()=>de.PhantomBladeZeroLocation))])}),PhantomBladeZeroAchievementDetail:Ee({id:L(),name:L(),desc:L(),grade:L(),hidden:k([we(!1),we(!0)]),done:k([we(!1),we(!0)])}),UserGameDataSaveFilePage:Ee({items:fe(ue(()=>de.UserGameDataSaveInfo)),hasMore:we(!1)}),UserGameDataSaveInfo:Ee({saveId:L(),createdAt:L(),files:fe(ue(()=>de.UserGameDataSaveFileInfo))}),UserGameDataSaveFileInfo:Ee({fileId:L(),name:L(),sizeBytes:re(),modifiedAt:L()})},cg=new Map([["account.pc_hardware",ue(()=>de.PcHardwareInfo)],["ark.profile",ue(()=>de.ArkProfile)],["ark.gacha-analysis",ue(()=>de.ArkGachaAnalysis)],["ark.gacha-record-page",Ee({items:fe(ue(()=>de.GachaRecord)),nextCursor:X(L()),hasMore:k([we(!1),we(!0)]),total:X(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 ug(e,t){return cg.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 bf(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 yf="METHOD_FORBIDDEN";function Ot(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=yf,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 dg=/^[A-Za-z0-9_-]{1,64}$/,Lu=1e3;function Nf(e){return dg.test(e)?e:mg(e)}function lg(e){return`id_${Nf(e.trim())}`}function Wr(e,t){return`hb_miniprogram_${e}_${t}`}function Ui(e){return`hb_miniprogram_keys_${e}`}const fg="hb_user_game_data_consent_";function hg(e){return`${fg}${e}`}function mg(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 Eg=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 Hc(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 D=0;D<16;D+=1)s[D]=a.getUint32(c+D*4,!1);for(let D=16;D<64;D+=1){const N=s[D-15],v=s[D-2],I=Ht(N,7)^Ht(N,18)^N>>>3,H=Ht(v,17)^Ht(v,19)^v>>>10;s[D]=s[D-16]+I+s[D-7]+H>>>0}let[u,d,l,h,f,p,_,y]=i;for(let D=0;D<64;D+=1){const N=y+(Ht(f,6)^Ht(f,11)^Ht(f,25))+(f&p^~f&_)+Eg[D]+s[D]>>>0,v=(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+v>>>0}[u,d,l,h,f,p,_,y].forEach((D,N)=>{i[N]=i[N]+D>>>0})}return Array.from(i,c=>c.toString(16).padStart(8,"0")).join("")}function Ht(e,t){return e>>>t|e<<32-t}const gg=Object.freeze({upload:"你允许读取的数据可能会被上传至开发者服务器。",no_network:"此小程序未获准将你允许读取的数据上传至开发者服务器。"});function pg(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&&!Ag(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 _g(e){return Hc(`${e.miniProgramId}\0${e.userId}\0${e.environment}`).slice(0,32)}function Tg(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 Ag(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 Ig(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?ke("RUNTIME_ERROR",e.message):ke("UNKNOWN_ERROR","小程序运行时异常",e)}function Ig(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"],Pu={"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"],[Mc]:wr,[Es]:Qa,[Qn]:Qa,[gs]:[...Qa,"files.sandbox","files.removeFile","network.stream","files.transfer"],[Rc]:[...wr,"presentation.confirmDataPermission"],[Cc]:wr,[Lc]:wr,[Pc]:[...wr,"presentation.openDataPermissions"],[vc]:wr},bg=new Set([oi]);function wf(e,t){if(t[e]!==!0)throw bg.has(e)?ke("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):Ot(e)}const yg=32*1024*1024,Ng=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function wg(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:yg},i);return Dg(s,c)}catch(c){throw a=c,c}finally{try{await r.release(s.body)}catch(c){if(a===void 0)throw c}}}}}}function Dg(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:Sg(t,Mg(e,"content-type"))}}function Sg(e,t){Og(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||!Ng.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function Og(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 Mg(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function le(e){return typeof e=="function"}function vu(e){return(...t)=>{throw Ot(e)}}function Ze(e){return async(...t)=>{throw Ot(e)}}const Rg=(e,t)=>{},Cg=()=>()=>{};function Lg(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):Cg},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):vu("presentation.getViewportMetrics"),getNavigationBarHeight:le(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):vu("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):Rg,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 Pg(e,t={}){const r=vg(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 vg(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 ku(e,t){return t?.[e]!==!1}function kg(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function xg(e,t={}){const r={};for(const n of Object.keys(Pu)){const s=Pu[n].every(c=>e[c]),a=!kg(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=ku(n,t.callerCapabilities)&&ku(n,t.hostCapabilities)&&s&&a}return r}function Df(e={},t={}){const r=Pg(e,t),n=xg(r,t);return{ports:Lg(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]):Ug(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function Ug(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 Bg(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 Hg=4,Fg=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],zg=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),jg=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1","/user_miniprogram/cloud/rooms"],Vg=["/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 Gg(e,t){const r=Qg(e);return r===null||xu(r,jg)?!0:t&&xu(r,Vg)}function Yg(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Fg.some(r=>t===r||t.endsWith(`.${r}`))}function qg(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||zg.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Qg(e){let t=e;for(let r=0;r<Hg;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Uu(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Uu(t)}function xu(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Uu(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Wg(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 Sf(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=Wg(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 Bu(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(Bu(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(Bu(d))))})}async function $g(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),p=h.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(f.overflowY)&&(l.top+t.top<p.top-1||l.top+t.top+t.height>p.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 Kg(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 Of(e,t){return Zg(t)??Xg(e.pathname)}function Zg(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Xg(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const Jg=2,Mf="allow-scripts allow-same-origin allow-pointer-lock",ep="",tp="no-referrer";function rp(e=Mf){return!e.split(/\s+/).includes("allow-same-origin")}function Hu(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const np=new Set(["javascript:","data:","blob:","file:"]),Fu="xiaoheihe.cn";function ip(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(np.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!ap(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function sp(e,t){const r=new URL(e);return r.searchParams.set(Kl,t),r.toString()}function Rf(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const s=Of(n,r);return i.pathname.startsWith(s)}catch{return!1}}function zu(e){const t=new URL(e);return Fc(t)?"loopback":zc(t)?"lan":"production"}function ap(e,t,r){return op(e)||Fc(e)||zc(e)&&up(t,r)}function op(e){return e.protocol==="https:"&&fp(e.hostname)}function Fc(e){return e.protocol==="http:"&&cp(e.hostname)}function cp(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function zc(e){return e.protocol==="http:"&&dp(e.hostname)}function up(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Fc(r)||zc(r)}catch{return!1}}function dp(e){const t=lp(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function lp(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 fp(e){return e===Fu||e.endsWith(`.${Fu}`)}function hp(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||!Rf(e.launchUrl,c.href,e.locationBasePath))return;const u=new URL(c.href);if(!(u.username||u.password||u.searchParams.get(Kl)!==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 Cf(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 mp(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 Ep(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const gp=1e3;function pp(e,t=Ep()){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<=gp}const _p="runtime.gate.probe",Lf=new Set(pr.map(e=>e.method));class Tp{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=$l;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:Xl,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=pp(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&&H0(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:Zl,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===_p){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,ke("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Lf.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})||!Ap(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 Ap(e){return typeof e=="string"&&Lf.has(e)}function T(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function _e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jc(){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 Pf(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):kf,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 vf(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=>Pf(e.file(c),n,{allowRemove:s}),directory:c=>vf(e.directory(c),n,{allowRemove:s}),create:i?(c,u)=>e.create(c,u):Uo,remove:a?(c,u)=>e.remove(c,u):kf,stat:c=>e.stat(c),list:(c,u)=>e.list(c,u)})}function Uo(){return Promise.reject(T("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function kf(){return Promise.reject(T("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const Ip=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"]),bp={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=Vc(e),r=t&&Ip.has(t)?T(t,bp[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 Vc(e){try{if(!_e(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const ju=1024;class Gc{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new Gc(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>ju)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 Gu(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=Np(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=wp(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 qu(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"&&_e(c)&&typeof c.name=="string"&&xf(c.name)||s.push(this.describeListedEntry(t,c))}return this.assertCanonicalDetail(),s})}describeListedEntry(t,r){return Xt(()=>{if(_e(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Bi(n.handle,Vu(t.ref,n.handle.name))}if(_e(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return Gu(n.handle,yp(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:Vu(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw T("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Xt(()=>{qu(t);const i=n??t.mode;return Yu(t.mode,i),{handle:Pf(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Xt(()=>{Op(t,i);const s=n??t.mode;return Yu(t.mode,s),{handle:vf(t,s,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>ju)throw T("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const s=jc();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(!Dp(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(!kc(e))throw T("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function $a(e,t){if(e==="sandbox"&&xf(t))throw T("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function xf(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 Vu(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 yp(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 Gu(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Yu(e,t){if(t==="readwrite"&&e!=="readwrite")throw T("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Np(e){return kr(e)||Uf(),e}function wp(e){return ef(e)||Uf(),e}function Uf(){throw T("INVALID_PARAMS","文件引用不合法")}function Dp(e){return/^[0-9a-f]{32}$/.test(e)}function Sp(e){return _e(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 qu(e){if(!Sp(e))throw T("FILE_IO_FAILED","Host 返回了无效 File handle");Di(e.name,"Host File name")}function Op(e,t=!1){if(!_e(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 Mp=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Rp=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Cp=new Set(["range","if-range","a-im"]),Lp=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"]),Pp=/^(?: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 vp{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 Ff()}normalizeHostError(t,r){return this.throwIfCancelled(),qc(t,r,this.signal)}}async function Bf(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 vp(s.signal);a.transition("target"),a.throwIfCancelled();let c;try{c=await Bp(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=Fp(u);zp(u,l);const h=jp(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=Hp(e,c,l,i);let p=0;const _=xp(h.expectedBytes,e.maxBytes);Za(t,Ka(0,h));const y={...s,onProgress(v){!Number.isSafeInteger(v)||v<p||_!==void 0&&v>_||(p=v,Za(t,Ka(p,h)))}};a.transition("transfer"),d=!0;let D;try{D=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(v){throw a.normalizeHostError(v,"transfer")}a.transition("committed"),p=kp(D,h,p,e.maxBytes),Za(t,Ka(p,h));const N=i.describeFile(f.handle,f.ref);return a.transition("completed"),N}finally{d||Up(n.network,u.body)}}function kp(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 xp(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Up(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Bp(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Bo(i.handle.mode),await $p(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Bo(n.handle.mode),await Kp(n.handle,r),{kind:"directory",...n}}function Hp(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Gp(e,r),s=n.deriveFile(t,i);return Bo(s.handle.mode),{...s,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Fp(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(!_e(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()||!Mp.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 zp(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:Wp(t,Rp)});if((t["content-range"]?.length??0)>0)throw T("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function jp(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=Vp(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 Vp(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 Gp(e,t){const r=t["content-disposition"]??[];for(const i of r){const s=Yp(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 Yc(e.suggestedName);const n=Qp(e.url);return n&&rs(n)?n:"download.bin"}function Yp(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 Qp(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Yc(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)||Pp.test(e))}function Wp(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function $p(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Hf()}catch(r){throw qc(r,"file",t.signal)}}async function Kp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Hf()}catch(r){throw qc(r,"file",t.signal)}}function Bo(e){if(e!=="readwrite")throw T("FILE_ACCESS_DENIED","下载目标只允许读取")}const Zp={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 qc(e,t,r){if(r.aborted)return Ff();const n=Xp(e);if(n&&Lp.has(n)){const s=T(n,Zp[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 Xp(e){return _e(e)&&typeof e.code=="string"?e.code:void 0}function Hf(){return T("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Ff(){return T("DOWNLOAD_CANCELLED","下载已取消")}function Jp(e){if(!e)return;const t=Object.keys(e).find(r=>Cp.has(r.trim().toLowerCase()));if(t)throw T("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Qu=8*1024*1024,e_=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>Qu)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(!bf(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(Qu,e_-r);if(f<=0)throw T("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达上限");const p=e.files.sandbox.file(`.hb-game-saves/${jc()}.zip`);if(!p.remove)throw T("REQUEST_UNSUPPORTED","宿主不支持私有存档清理");r+=f;let _=!1;try{await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},d),await p.create({recursive:!0,exclusive:!0},d);const y=e.registry.createTransferScope();try{const I=y.registerFile(p,"game-save","readwrite");await Bf({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 D=(await p.stat(d)).size;if(!Number.isSafeInteger(D)||D<0||D>f)throw T("FILE_TOO_LARGE","存档实际大小超过限额");await u(d),a(d);const N=async()=>{throw T("FILE_ACCESS_DENIED","存档文件只读")},v={kind:"file",mode:"read",name:l.name,create:N,write:N,async read(I){a(I),await u(I);const H=await p.read(I);try{if(a(I),await u(I),H.byteLength!==D)throw T("INVALID_RESPONSE","私有存档副本长度不匹配");return H}catch(Y){throw H.fill(0),Y}},async stat(I){return a(I),await u(I),await p.stat(I),a(I),await u(I),{kind:"file",size:D,...typeof l.modified_at=="number"&&Number.isSafeInteger(l.modified_at)?{modifiedAt:l.modified_at}:{}}}};return r-=f-D,t.set(v,{target:p,size:D}),_=!0,v}finally{_||(r-=f,await i(p))}}}}const t_=/^(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 r_(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 n_(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=t_.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 i_(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 Wu(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function zf(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,D){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:y,type:D})).catch(()=>{})}catch{}}function l(y){const D=r.get(y);if(!D)throw new Error("Unknown runtime cache scope");return D}function h(y,D){return y.flatMap((N,v)=>{const I=JSON.stringify(y.slice(0,v+1));return[JSON.stringify([I]),JSON.stringify([I,D])]})}function f(y,D){return JSON.stringify(h(y,D).map(N=>n.get(N)??0))}async function p(y,D){const N=l(y),v=JSON.stringify([JSON.stringify(N),...D?[D]:[]]),I=(n.get(v)??0)+1;n.set(v,I),i.add(v);for(const H of c)H(N,D);if(!e.store){i.delete(v),d(D??"*","invalidation");return}try{await e.store.invalidate(N,D)}catch(H){throw d(D??"*","storage_error"),H}n.get(v)===I&&i.delete(v),d(D??"*","invalidation")}function _(y){if(u)throw new Error("Runtime cache manager disposed");const D=s.get(y.namespace);if(D){if(D.sourceCodec!==y.codec||D.definition.codec.version!==y.codec.version||JSON.stringify(D.definition.policy)!==JSON.stringify(y.policy))throw new Error("Conflicting runtime cache namespace");return D.cache}if(!y.namespace||!y.codec.version)throw new Error("Invalid runtime cache definition");const N=Object.freeze({...y.policy}),v=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 P of[N.ttlMs,N.memoryMaxEntries,N.diskMaxEntries,N.diskMaxBytes,N.maxEntryBytes])if(!Number.isFinite(P)||P<0)throw new Error("Invalid runtime cache policy");const H=new Map,Y=new Map,R=new Map;let x=!1;function U(P,w,B){if(u||x||P.aborted||f(w,I)!==B)throw $r()}function G(P){return N.ttlMs>0&&N.persistence==="memory-and-disk"&&!!e.store&&!h(P,I).some(w=>i.has(w))}function V(P,w,B){const O=t();return P.envelopeVersion===1&&JSON.stringify(P.address)===JSON.stringify(w)&&Wu(P.revisions,B)&&P.payload.byteLength<=N.maxEntryBytes&&Number.isFinite(P.cachedAt)&&Number.isFinite(P.expiresAt)&&P.cachedAt<=O&&P.cachedAt>=0&&P.expiresAt>P.cachedAt&&Math.min(P.expiresAt,P.cachedAt+N.ttlMs)>O}function te(P,w,B,O,W){if(!(N.ttlMs<=0||N.memoryMaxEntries<1)){for(const[$,Z]of H)Math.min(Z.entry.expiresAt,Z.entry.cachedAt+N.ttlMs)<=t()&&H.delete($);for(H.delete(P);H.size>=Math.floor(N.memoryMaxEntries);){const $=H.keys().next();if($.done)break;H.delete($.value)}H.set(P,{entry:w,value:B,epoch:O,persistent:W})}}async function z(P,w,B,O){const W={namespace:I,codecVersion:v.version,scopeIds:w,key:P.key},$=JSON.stringify(W);let Z=[],ie=G(w);if(ie)try{Z=await e.store.readRevisions(w,I)}catch{ie=!1,d(I,"storage_error")}U(O.signal,w,B);async function me(){if(!ie)return!0;try{return Wu(Z,await e.store.readRevisions(w,I))}catch{return ie=!1,d(I,"storage_error"),!1}}const De=H.get($);if(N.ttlMs>0&&De&&De.epoch===B&&V(De.entry,W,Z)&&De.persistent===ie&&await me())return U(O.signal,w,B),d(I,"memory_hit"),De.value;if(H.delete($),ie){let m,M;try{m=await e.store.read(W,N.maxEntryBytes),m&&V(m,W,Z)?M=v.decode(m.payload):m=void 0}catch{m=void 0,d(I,"storage_error")}if(U(O.signal,w,B),m&&await me())return U(O.signal,w,B),te($,m,M,B,!0),d(I,"disk_hit"),M}d(I,"miss");const Pe=v.validate(await P.load(O.signal));U(O.signal,w,B);const E=v.clone(Pe);if(!await me()&&ie)throw $r();if(U(O.signal,w,B),N.ttlMs>0){const m=t();let M;try{M=v.encode(E)}catch{return E}const S={envelopeVersion:1,address:W,revisions:ie?Z:[],cachedAt:m,expiresAt:m+N.ttlMs,payload:M};if(ie&&M.byteLength<=N.maxEntryBytes){let C=!0,K=!1;try{C=await e.store.publish(S,N),K=C}catch{d(I,"storage_error")}if(U(O.signal,w,B),!C)throw $r();K&&d(I,"published")}U(O.signal,w,B),te($,S,E,B,ie)}return E}async function j(P){if(u||x||P.signal?.aborted)return Promise.reject($r());const w=l(P.scope),B=f(w,I);let O;if(G(w)){const ie=new AbortController;R.set(ie,w);const me=()=>ie.abort();P.signal?.addEventListener("abort",me,{once:!0});let De=()=>{};try{O=await Promise.race([e.store.readRevisions(w,I),new Promise((Pe,E)=>{const m=()=>E($r());ie.signal.addEventListener("abort",m,{once:!0}),De=()=>ie.signal.removeEventListener("abort",m)})])}catch{ie.signal.aborted||d(I,"storage_error")}finally{De(),R.delete(ie),P.signal?.removeEventListener("abort",me)}}U(P.signal??new AbortController().signal,w,B);const W=JSON.stringify([w,P.key,B,O]);let $=Y.get(W);if($?.controller.signal.aborted&&($=void 0),!$){const ie=new AbortController;$={ids:w,controller:ie,waiters:0,promise:Promise.resolve(void 0)};const me=$;me.promise=z(P,w,B,ie).finally(()=>{Y.get(W)===me&&Y.delete(W)}),Y.set(W,me)}const Z=$;return Z.waiters+=1,new Promise((ie,me)=>{let De=!1;function Pe(m){De||(De=!0,P.signal?.removeEventListener("abort",E),Z.controller.signal.removeEventListener("abort",E),Z.waiters-=1,Z.waiters===0&&Z.controller.abort(),m())}function E(){Pe(()=>me($r()))}P.signal?.addEventListener("abort",E,{once:!0}),Z.controller.signal.addEventListener("abort",E,{once:!0}),Z.promise.then(m=>Pe(()=>{try{U(P.signal??new AbortController().signal,w,B),ie(v.clone(m))}catch(M){me(M)}}),m=>Pe(()=>me(m)))})}function ee(P,w){if(w&&w!==I)return;const B=O=>P.every((W,$)=>O[$]===W);for(const[O,W]of H)B(W.entry.address.scopeIds)&&H.delete(O);for(const[O,W]of Y)B(W.ids)&&(W.controller.abort(),Y.delete(O));for(const[O,W]of R)B(W)&&O.abort()}function J(){if(!x){x=!0,H.clear();for(const P of R.keys())P.abort();R.clear();for(const P of Y.values())P.controller.abort();Y.clear(),a.delete(J),c.delete(ee),s.get(I)?.cache===Q&&s.delete(I)}}const Q={read:j,invalidateScope:P=>p(P,I),dispose:J};return a.add(J),c.add(ee),s.set(I,{definition:{namespace:I,codec:v,policy:N},sourceCodec:y.codec,cache:Q}),Q}return{createScope(y,D){if(u||!y)throw new Error("Invalid runtime cache scope");const N=Object.freeze({});return r.set(N,[...D?l(D):[],y]),N},register:_,invalidateScope:y=>p(y),dispose(){if(!u){u=!0;for(const y of[...a])y();s.clear(),n.clear(),i.clear()}}}}function s_(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 a_=".hb-runtime-cache-v1",o_=1e3,Xa=64*1024,Kr=1e3,c_=2048,Ln=32*1024*1024,u_=1024,is=new TextEncoder,$u=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 Ku(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function d_(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function Zu(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function l_(e,t){const r=e.sandbox.directory(a_),n=r.directory("revisions"),i=r.directory("entries");for(const z of[r,n,i,i.directory("capability-check")])Zu(z,["directory","file","create","stat","list","remove"]),Zu(z.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(z){d=z,s.abort(),t.signal.removeEventListener("abort",a)}function h(z){if(d_(z))throw l(z),z}function f(){if(d)throw d;if(c.signal.aborted)throw Pn()}function p(z,j=c.signal){const ee=u.then(()=>{if(j.aborted)throw d??Pn();return f(),z()},()=>{if(j.aborted)throw d??Pn();return f(),z()}).catch(w=>{throw h(w),w});if(u=ee.catch(()=>{}),j.aborted)return Promise.reject(d??Pn());let J=()=>{};const Q=new Promise((w,B)=>{const O=()=>B(d??Pn());j.addEventListener("abort",O,{once:!0}),J=()=>j.removeEventListener("abort",O)}),P=setTimeout(()=>{l(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},o_);return Promise.race([ee,Q]).finally(()=>{clearTimeout(P),J()})}async function _(){f(),await n.create({recursive:!0,exclusive:!1},c),f(),await i.create({recursive:!0,exclusive:!1},c),f()}async function y(z,j){const ee=n.file(`${await Fi([z,j??null])}.revision`);await N(ee);let J=!1;try{await ee.create({recursive:!1,exclusive:!0},c),J=!0}catch(w){h(w),f()}if(J){const w=Ku();return await ee.write(is.encode(w),c),f(),w}const Q=await ee.stat(c);if(Q.size<1||Q.size>128)throw new Error("缓存 revision 文件损坏");const P=$u.decode(await ee.read(c));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(P))throw new Error("缓存 revision 文件损坏");return f(),P}async function D(z){const j=await z.list({limit:Kr},c);if(j.length>=Kr)throw new Error("缓存目录超过治理上限");return j}async function N(z){try{await z.stat(c);return}catch(ee){if(!zi(ee))throw ee}if((await D(n)).length>=Kr-1)throw new Error("缓存 metadata 超过治理上限")}async function v(z,j){await _();const ee=[];for(let J=0;J<z.length;J+=1){const Q=z.slice(0,J+1);ee.push(await y(Q),await y(Q,j))}return ee}async function I(z){return r.directory(`entries/${await Fi([z.namespace,z.codecVersion,z.scopeIds])}`)}async function H(z){return(await I(z)).file(`${await Fi(z.key)}.cache`)}async function Y(z,j){const ee=await z.stat(c);if(ee.size<5||ee.size>j+Xa+4)throw new Error("缓存条目超过大小限制");const J=await z.read(c);if(f(),J.length!==ee.size)throw new Error("缓存条目读取不完整");const Q=new DataView(J.buffer,J.byteOffset,J.byteLength).getUint32(0);if(Q<1||Q>Xa||Q+4>J.length)throw new Error("缓存信封损坏");const P=JSON.parse($u.decode(J.subarray(4,Q+4))),w=J.slice(Q+4);if(P.envelopeVersion!==1||!P.address||!Array.isArray(P.address.scopeIds)||!P.address.scopeIds.every(B=>typeof B=="string")||typeof P.address.namespace!="string"||typeof P.address.codecVersion!="string"||typeof P.address.key!="string"||!Array.isArray(P.revisions)||P.revisions.length!==P.address.scopeIds.length*2||!P.revisions.every(B=>typeof B=="string"&&B.length>0)||!Number.isSafeInteger(P.cachedAt)||!Number.isSafeInteger(P.expiresAt)||P.cachedAt<0||P.expiresAt<=P.cachedAt||P.payloadBytes!==w.length||w.length>j)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:P.address,revisions:P.revisions,cachedAt:P.cachedAt,expiresAt:P.expiresAt,payload:w}}async function R(z){if(!z.remove)throw new Error("Host 不支持缓存文件删除");await z.remove(c)}async function x(z){try{if((await z.file.stat(c)).size!==z.size)return!1;const j=await Y(z.file,Ln);return!Ft(j.address,z.entry.address)||!Ft(j.revisions,z.entry.revisions)||j.cachedAt!==z.entry.cachedAt||j.expiresAt!==z.entry.expiresAt||!Ft(await U(j.payload),await U(z.entry.payload))?!1:(await R(z.file),!0)}catch(j){if(zi(j))return!0;throw j}}async function U(z){const j=await globalThis.crypto.subtle.digest("SHA-256",z);return Array.from(new Uint8Array(j),ee=>ee.toString(16).padStart(2,"0")).join("")}async function G(){const z=await D(n);let j=0;for(const P of z)if(P.kind==="file"&&(j+=(await P.stat(c)).size,j>Ln))throw new Error("缓存扫描超过字节上限");const ee=[];let J=0,Q=j;for(const P of await D(i)){if(P.kind!=="directory")throw new Error("缓存目录结构损坏");for(const w of await D(P)){if(w.kind!=="file"||++J>c_)throw new Error("缓存文件超过治理上限");const B=(await w.stat(c)).size;if(Q+=B,Q>Ln)throw new Error("缓存扫描超过字节上限");try{const O=await Y(w,Ln);ee.push({file:w,entry:O,size:(await w.stat(c)).size,bucketName:P.name})}catch(O){h(O),f(),zi(O)||await R(w)}}}return{entries:ee,metadataBytes:j}}async function V(){for(const z of await D(i))if(z.kind==="directory"&&z.remove&&(await D(z)).length===0)try{await z.remove({recursive:!1},c)}catch(j){h(j),f()}}function te(z){const{payload:j,...ee}=z,J=is.encode(JSON.stringify({...ee,payloadBytes:j.length}));if(J.length>Xa)throw new Error("缓存信封过大");const Q=new Uint8Array(4+J.length+j.length);return new DataView(Q.buffer).setUint32(0,J.length),Q.set(J,4),Q.set(j,J.length+4),Q}return{readRevisions:(z,j)=>p(()=>v(z,j)),read:(z,j)=>p(async()=>{f();const ee=await H(z);let J;try{J=await Y(ee,j)}catch(Q){if(f(),zi(Q))return;throw Q}if(!(!Ft(J.address,z)||J.expiresAt<=Date.now())&&Ft(J.revisions,await v(z.scopeIds,z.namespace)))return J}),publish:(z,j)=>p(async()=>{f();const{address:ee}=z;if(!Ft(z.revisions,await v(ee.scopeIds,ee.namespace)))return!1;const J=te(z);if(z.payload.length>j.maxEntryBytes||J.length>j.diskMaxBytes||j.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await _();const Q=await I(ee),P=await H(ee),w=await G(),B=[],O=new Map;for(const Z of w.entries){if(Z.bucketName===Q.name&&Z.file.name===P.name)continue;const ie=JSON.stringify([Z.entry.address.scopeIds,Z.entry.address.namespace]);let me=O.get(ie);if(me||(me=await v(Z.entry.address.scopeIds,Z.entry.address.namespace),O.set(ie,me)),Z.entry.expiresAt<=Date.now()||!Ft(Z.entry.revisions,me)){if(!await x(Z))throw new Error("缓存治理期间条目已变化")}else B.push(Z)}B.sort((Z,ie)=>Z.entry.cachedAt-ie.entry.cachedAt);function W(){const Z=B.filter(ie=>ie.bucketName===Q.name);return B.length+1>u_||J.length+w.metadataBytes+B.reduce((ie,me)=>ie+me.size,0)>Ln||Z.length+1>Math.min(j.diskMaxEntries,Kr-1)||J.length+Z.reduce((ie,me)=>ie+me.size,0)>j.diskMaxBytes}for(;W();){const Z=B.filter(De=>De.bucketName===Q.name),me=Z.length+1>Math.min(j.diskMaxEntries,Kr-1)||J.length+Z.reduce((De,Pe)=>De+Pe.size,0)>j.diskMaxBytes?Z[0]:B[0];if(!me||!await x(me))throw new Error("缓存容量不足或条目已变化");B.splice(B.indexOf(me),1)}await V();const $=await D(i);if(!$.some(Z=>Z.name===Q.name)&&$.length>=Kr-1)throw new Error("缓存目录超过治理上限");if(await Q.create({recursive:!0,exclusive:!1},c),!Ft(z.revisions,await v(ee.scopeIds,ee.namespace)))return!1;try{await P.create({recursive:!1,exclusive:!0},c)}catch(Z){h(Z),await P.stat(c)}return await P.write(J,c),f(),Ft(z.revisions,await v(ee.scopeIds,ee.namespace))}),invalidate:(z,j)=>p(async()=>{await _();const ee=n.file(`${await Fi([z,j??null])}.revision`);await N(ee);try{await ee.create({recursive:!1,exclusive:!0},c)}catch(J){h(J),await ee.stat(c)}await ee.write(is.encode(Ku()),c),f();try{const{entries:J}=await G();for(const Q of J){if(j!==void 0&&Q.entry.address.namespace!==j||!z.every((w,B)=>Q.entry.address.scopeIds[B]===w))continue;const P=await v(Q.entry.address.scopeIds,Q.entry.address.namespace);Ft(Q.entry.revisions,P)||await x(Q)}await V()}catch(J){h(J),f()}})}}function zi(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const f_="RATE_LIMITED_BY_RUNTIME",h_="RATE_LIMITED",jf=20,Vf=40,Gf=150,Yf=20,qf=1e4,Qf=45e3,Wf=1,m_=300*1e3,E_=64;function Zr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function g_(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function p_(e={}){const t=e.now??Date.now,r=g_(e.coalesceWindowMs,Gf),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,Zr(e.budget?.ratePerSecond,jf)),burst:Math.max(1,Math.floor(Zr(e.budget?.burst,Vf)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(Zr(e.loopDetection?.maxCalls,Yf))),windowMs:Math.max(1,Math.floor(Zr(e.loopDetection?.windowMs,qf)))},s=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(Zr(e.circuitBreaker?.failureThreshold,Wf))),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 p(x){try{e.onReport?.(x)}catch{}}function _(x,U){if(!i)return{exceeded:!1,count:0};const G=c.get(x)??[],V=U-i.windowMs;let te=0;for(;te<G.length&&G[te]<=V;)te+=1;te>0&&G.splice(0,te);const z=G.length>=i.maxCalls;return z||(G.push(U),G.length>i.maxCalls+1&&G.splice(0,G.length-(i.maxCalls+1))),c.set(x,G),{exceeded:z,count:G.length}}function y(x){if(!n)return!0;const U=Math.max(0,x-l.updatedAt)/1e3;return l.tokens=Math.min(n.burst,l.tokens+U*n.ratePerSecond),l.updatedAt=x,l.tokens<1?!1:(l.tokens-=1,!0)}function D(x){if(!n)return 0;const U=Math.max(0,x-l.updatedAt)/1e3,G=Math.min(n.burst,l.tokens+U*n.ratePerSecond);return Math.max(0,Math.ceil((1-G)/n.ratePerSecond*1e3))}function N(x,U,G,V,te){if(!s)return;const z=d.get(U),j=(z?.open?0:z?.failures??0)+1;if(j<s.failureThreshold){d.set(U,{open:!1,openedAt:0,openMs:0,failures:j});return}const ee=Math.min(Math.max(s.openMs,V),m_);d.set(U,{open:!0,openedAt:te,openMs:ee,failures:j}),h.circuitOpened+=1,p({type:"circuit_opened",capability:x,endpointId:U,status:G,openMs:ee,timestamp:te})}function v(x){const U=d.get(x);U&&!U.open&&d.delete(x)}function I(x){for(const[U,G]of a)!G.pending&&G.expiresAt<=x&&a.delete(U);for(;a.size>=E_;){const U=[...a].find(([,G])=>!G.pending);if(!U)break;a.delete(U[0])}}function H(x,U){if(x===void 0)return;const G=a.get(x);G?.promise===U&&(G.pending=!1)}function Y(x,U){if(x===void 0)return;a.get(x)?.promise===U&&a.delete(x)}async function R(x){if(f)return x.load();const U=t();if(s){const z=d.get(x.endpointId);if(z?.open){const j=z.openedAt+z.openMs-U;if(j>0)throw h.circuitRejected+=1,p({type:"circuit_rejected",capability:x.capability,endpointId:x.endpointId,retryAfterMs:j,timestamp:U}),A_("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:x.endpointId,retryAfterMs:j});d.delete(x.endpointId)}}const G=_(x.endpointId,U);G.exceeded&&i?u.has(x.endpointId)||(u.add(x.endpointId),p({type:"loop_detected",capability:x.capability,endpointId:x.endpointId,count:G.count,windowMs:i.windowMs,timestamp:U})):u.delete(x.endpointId);const V=r>0?x.coalesceKey:void 0;if(V!==void 0){const z=a.get(V);if(z&&(z.pending||z.expiresAt>U))return h.coalesced+=1,p({type:"coalesced",capability:x.capability,endpointId:x.endpointId,timestamp:U}),z.promise;z&&a.delete(V)}if(G.exceeded&&i)throw h.loopRejected+=1,Xu("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:x.capability,endpointId:x.endpointId,count:G.count,windowMs:i.windowMs});if(!y(U)){h.budgetRejected+=1;const z=D(U);throw p({type:"budget_exhausted",capability:x.capability,endpointId:x.endpointId,retryAfterMs:z,timestamp:U}),Xu("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:x.capability,endpointId:x.endpointId,retryAfterMs:z})}V!==void 0&&I(U);const te=x.load().then(z=>(H(V,te),v(x.endpointId),z),z=>{Y(V,te);const j=__(z);throw j!==void 0&&N(x.capability,x.endpointId,j,T_(z),U),z});return V!==void 0&&a.set(V,{endpointId:x.endpointId,promise:te,expiresAt:U+r,pending:!0}),te}return{execute:R,invalidateCoalescing(x){if(x===void 0){a.clear();return}for(const[U,G]of a)x.includes(G.endpointId)&&a.delete(U)},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 __(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 T_(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 Xu(e,t){return{code:f_,message:e,data:t}}function A_(e,t){return{code:h_,message:e,data:t}}const $f=3e4,Kf=6e4,Ho=1440*60*1e3;function I_(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??$f)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??Kf)):0,steamGameListTtlMs:t?b_(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:jf,burst:Vf},coalesceWindowMs:r?.coalesceWindowMs??Gf,loopDetection:r?.loopDetection??{maxCalls:Yf,windowMs:qf},circuitBreaker:r?.circuitBreaker??{failureThreshold:Wf,openMs:Qf}}}}function b_(e){return e===void 0||!Number.isFinite(e)?Ho:Math.max(0,Math.floor(e))}function Zf(e){return typeof e=="object"&&e!==null}function Wc(e,t){const r=e.data;if(!Zf(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(!Zf(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"},y_={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 N_(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function w_(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=N_(r.consent_challenge)),{...t,result:n}}const D_={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,"小程序授权取消接口响应异常")},S_={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,"小程序授权撤销接口响应异常")},O_={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}:{}}}}},M_={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=>w_(e)},R_={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}}}},C_=64;function Fo(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??C_)),n=e.now??Date.now,i=new Map,s=new Map;let a=0,c=!1;function u(h){for(const[f,p]of i)p.expiresAt<=h&&i.delete(f)}function d(h,f,p){if(c||t<=0||p!==a)return;const _=n();for(u(_),i.delete(h);i.size>=r;){const y=i.keys().next();if(y.done)break;i.delete(y.value)}i.set(h,{expiresAt:_+t,value:f})}function l(h,f){if(c)return f();if(t>0){const D=i.get(h);if(D&&D.expiresAt>n())return Promise.resolve(D.value);D&&i.delete(h)}const p=s.get(h);if(p)return p;const _=a,y=f().then(D=>(d(h,D,_),D)).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 L_(e,t){return t?e?"server":"local":"legacy"}function P_(e,t){if(e==="local")throw T("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const v_=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],k_=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),x_=/authorization|cookie|pkey|password|secret|token/i,Jf=/authorization|cookie|pkey|token|password|secret/i;function zt(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function U_(e){for(const t of Object.keys(e))if(!k_.has(t))throw new Je(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of v_)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))x_.test(n)||(r[n]=ea(i));return r}function Ju(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Jf.test(r)||(t[r]=n);return t}function B_(e){if(!e)return;const t=Object.keys(e).find(r=>Jf.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 ed=1440*60*1e3,H_=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function F_(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,ed):void 0}if(!H_.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const s=i-t();return s>0?Math.min(s,ed):void 0}function z_(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 eh(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,eh(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,eh(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function j_(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:Ju(s),method:e.method,metadata:{endpointId:e.id},query:ea(n),timeout:e.timeout,url:r},data:c.data,headers:Ju(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(U_(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;B_(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(p){throw p instanceof Je?p:new pn({endpointId:t.id,cause:p})}if(h.status<200||h.status>=300)throw new Oi({endpointId:t.id,status:h.status,responseData:h.data,retryAfterMs:F_(h.headers)});const f=j_(t,r,i,s,a,c,n,h);if(t.parse)try{return await t.parse(f,r)}catch(p){throw new Mi({endpointId:t.id,cause:p})}return f.data},d=n.gate;if(!d)return u();const l=z_(t,s,a,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...l===void 0?{}:{coalesceKey:l},load:u})}const V_=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),G_=new Set(En),$c="steam_account",th=new Set(En.filter(e=>e!==$c)),Y_=1e3;function q_(e){const t=new Set,r=Fo({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??$f))}),n=new Set;let i=0,s=!1,a=Promise.resolve(),c;const u=e.steamAccount===!0,d=e.userDataMode??L_(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 w;try{w=await e.authorizationContext.get(e.operationContext)}catch(O){throw jo(O)?Ja(O.code,O.message,O):Ja("REQUEST_FAILED","读取 Runtime auth context 失败",O)}if(w.steamAccount!==u||w.userDataMode!==d)throw T("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const B=w.token.trim();if(!B)throw T("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:B}}const p=e.account.onChange(w=>{if(_(),y("heybox_app_login_change",w?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),w&&e.account.getAccountKey){const B=i;Y().then(O=>{!s&&i===B&&y("heybox_app_login_change",O)}).catch(()=>{})}});function _(){i+=1,c?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function y(w,B){w==="user_info_authorization_change"&&X_(B)&&r.invalidate();for(const O of t)try{O(w,B)}catch{}}function D(){const w=e.identity.get()?.miniProgramId?.trim();if(!w)throw T("INVALID_STATE","当前能力缺少 canonical 小程序身份");return w}function N(){if(s||e.operationContext.signal.aborted)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function v(){N();let w;try{w=await e.account.getCurrentUserId(e.operationContext)}catch(B){throw id(B,e.operationContext.signal,"读取小黑盒账号失败")}return typeof w=="string"&&w.trim()?w.trim():void 0}async function I(w,B){const O=await v();if(i!==B||O!==w)throw T("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function H(w,B,O=D()){if(!e.account.getAccountKey)throw T("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let W;try{W=await e.account.getAccountKey(O,w,e.operationContext)}catch{throw N(),T("REQUEST_FAILED","读取本地账号标识失败")}if(await I(w,B),D()!==O)throw T("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof W!="string"||!W.trim())throw T("INVALID_RESPONSE","Host 返回了无效的账号标识");return W}async function Y(){const w=D(),B=i,O=await v();if(N(),i!==B)throw T("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return O?{isHeyboxAppLoggedIn:!0,accountKey:await H(O,B,w)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function R(w){N();try{await e.account.ensureAuthenticated({trustedUserGesture:w,reason:"runtime_auth",signal:e.operationContext.signal})}catch(O){throw id(O,e.operationContext.signal,"小黑盒登录失败")}const B=await v();if(!B)throw T("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return B}async function x(w,B,O=e.operationContext.signal){try{if(O.aborted)throw zo();return await Z_(Pa(e.network,w,B,{...e.operationContext,credentials:"heybox-session",signal:O,...h?{gate:h}:{}}),O)}catch(W){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):W instanceof Je?T("REQUEST_UNSUPPORTED",W.message):W instanceof Mi?T("INVALID_RESPONSE","授权接口响应不合法"):W instanceof pn?T("REQUEST_FAILED","授权请求失败"):W instanceof Oi?l&&(W.status===403||W.status===429)?T("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:W.status,...W.retryAfterMs===void 0?{}:{retryAfterMs:W.retryAfterMs}}):T("REQUEST_FAILED",W.message):jo(W)?W:T("REQUEST_FAILED","授权请求失败")}}async function U(w,B){await x(D_,{runtimeContext:{miniProgramId:w,...await f()},challenge:B}).catch(()=>{})}function G(w){const B=async()=>{const W=rd(e.operationContext.signal);c=W;try{return await w(W.signal)}finally{c===W&&(c=void 0),W.abort()}},O=a.then(B,B);return a=O.then(()=>{},()=>{}),O}async function V(w,B,O,W,$){if(!O)throw await U(w,B.challenge),T("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await U(w,B.challenge),T("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return G(async Z=>{await I(W,$);const ie=await te(w,B.displayedScopes,Z);await I(W,$);let me;try{me=await e.authPresentation.confirmAuthorization({miniProgramId:w,scopes:B.displayedScopes,...ie,signal:Z})}catch(Pe){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await I(W,$),await U(w,B.challenge),Ja("REQUEST_FAILED","授权确认界面执行失败",Pe))}if(await I(W,$),me.status!=="granted")throw await U(w,B.challenge),T("AUTHORIZATION_CANCELLED","用户取消授权");const De=$_(me.grantedScopes,B.displayedScopes,u);if(!De.includes("identity"))throw await U(w,B.challenge),T("AUTHORIZATION_CANCELLED","用户拒绝授权");return De})}async function te(w,B,O){const W=rd(O),$=setTimeout(()=>W.abort(),Y_);try{const Z=K_(e.miniProgramPresentation),[ie,me]=await Promise.all([Z?Promise.resolve(Z):z(w,W.signal),B.includes("profile")?j(W.signal):Promise.resolve(void 0)]);return{...ie?{miniProgram:ie}:{},...me?{userProfile:me}:{}}}finally{clearTimeout($),W.abort()}}async function z(w,B){try{const O=e.identity.get()?.version?.trim(),W=await x(y_,{mini_program_id:w,...O?{miniprogram_version:O}:{}},B),$=Xr(W,"小程序公开资料"),Z=an($.name),ie=an($.icon_url);return Z||ie?{...Z?{name:Z}:{},...ie?{avatarUrl:ie}:{}}:void 0}catch{return}}async function j(w){try{const B=await x(Xf,void 0,w),O=Xr(B,"账号基础信息"),W=an(O.display_username),$=an(O.display_avatar);return W||$?{...W?{nickname:W}:{},...$?{avatar:$}:{}}:void 0}catch{return}}async function ee(w,B){if(P_(d,"auth.login"),!u&&w.includes($c))throw T("INVALID_PARAMS","auth.login 参数不合法");const O=D(),W=await R(B),$=i,Z=await x(M_,{runtimeContext:{miniProgramId:O,...await f()},scopes:w});await I(W,$);const ie=Xr(Z,"小程序登录"),me=nd(ie,"loginCode"),De=nd(ie,"consentChallenge");if(me===De)throw T("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let Pe;if(me)Pe=td(ie.loginCode,u);else{const m=Q_(ie.consentChallenge,u),M=await V(O,m,B,W,$);await I(W,$);const S=await x(R_,{runtimeContext:{miniProgramId:O,...await f()},challenge:m.challenge,selectedScopes:M});if(await I(W,$),Pe=td(Xr(S,"小程序登录确认"),u),Pe.scopes.some(C=>!M.includes(C)))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(W,$,O):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 J(w,B){const O=i,W=await x(O_,{runtimeContext:{miniProgramId:B,...await f()}});await I(w,O);const $=W_(Xr(W,"用户本地身份"),u);for(const Z of u?En:th)n.add(Z);return y("user_info_authorization_change",eo(n,u)),$}function Q(w){N();const B=D(),O=`${w}\0${B}\0${i}\0${u}`;return r.read(O,()=>J(w,B))}async function P(w){if(!w)throw T("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const B=D(),O=i,W=await v();if(!W)throw T("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const $=await x(S_,{runtimeContext:{miniProgramId:B,...await f()}});await I(W,O),Xr($,"用户授权撤销"),_(),y("user_info_authorization_change",{identity:"denied",profile:"denied",...u?{steam_account:"denied"}:{}})}return{getAccountState:Y,login:ee,async confirmGameSaves(w){if(!w)throw T("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw T("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const B=D(),O=await R(w),W=i;await G(async $=>{await I(O,W);const Z=await te(B,["identity"],$),ie=await e.authPresentation.confirmAuthorization({miniProgramId:B,scopes:["identity","game_saves"],...Z,signal:$});if(await I(O,W),ie.status!=="granted"||!ie.grantedScopes.includes("game_saves")||!ie.grantedScopes.includes("identity"))throw T("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:Q,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>eo(n,u),revoke:P,onEvent(w){return t.add(w),()=>t.delete(w)},dispose(){s||(s=!0,_(),r.dispose(),p(),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(!_e(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":V_.has(r)?r:"REQUEST_FAILED";throw T(n,r)}if(!_e(e.result))throw T("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function td(e,t){if(!_e(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 Q_(e,t){if(!_e(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 W_(e,t){if(!_e(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 $_(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 K_(e){const t=an(e?.name),r=an(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function rd(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 Z_(e,t){return t.aborted?Promise.reject(zo()):new Promise((r,n)=>{let i=!1;const s=c=>{i||(i=!0,t.removeEventListener("abort",a),c())},a=()=>s(()=>n(zo()));t.addEventListener("abort",a,{once:!0}),e.then(c=>s(()=>r(c)),c=>s(()=>n(c)))})}function zo(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function ta(e,t,r){const n=r?G_:th;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!==$c);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function nd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function X_(e){return _e(e)?Object.values(e).some(t=>t==="denied"):!1}function jo(e){return _e(e)&&typeof e.code=="string"&&typeof e.message=="string"}function id(e,t,r){return t.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):jo(e)?e:T("REQUEST_FAILED",r)}const J_=new Set(En);function eT(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(tT(t),r.trustedUserGesture)}}function tT(e){if(e===void 0)return["identity"];if(!_e(e)||Object.keys(e).some(t=>t!=="scopes"))throw sd();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!J_.has(t))||new Set(e.scopes).size!==e.scopes.length)throw sd();return[...e.scopes]}function sd(){return T("INVALID_PARAMS","auth.login 参数不合法")}const Re=e=>({code:e,message:`房间操作失败:${e}`,data:{}});function ss(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw Re("INVALID_PARAMS");const r=e;if(Object.keys(r).some(n=>!t.includes(n)))throw Re("INVALID_PARAMS");return r}function Dr(e,t=/^[A-Za-z0-9_-]{1,80}$/){if(typeof e!="string"||!t.test(e))throw Re("INVALID_PARAMS");return e}function ad(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 rT=80,nT=64,ir=e=>e?.code||"RESULT_UNKNOWN",iT=e=>["RESULT_UNKNOWN","ROOM_BUSY","RATE_LIMITED","SERVICE_UNAVAILABLE","INTERNAL_ERROR"].includes(e),ji=e=>iT(e)||e.startsWith("runtime.transport."),od=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 cd(){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 Re("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 Re("UNAUTHORIZED");return r}function ud(e){if(!e||!un(e.revision)||!Array.isArray(e.members)||e.members.length>8)throw Re("INVALID_RESPONSE");return{members:e.members.map(({member_id:r,phase:n,owner:i})=>{if(n!=="active"&&n!=="grace")throw Re("INVALID_RESPONSE");return{id:r,phase:n,owner:i}}),locked:e.locked,status:{connection:"connected",room:"open"}}}function sT(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,p=new Map;function _(E){if(E.aborted||e.operationContext.signal.aborted)throw Re("ABORTED")}function y(E){if(_(E),!e.roomSocket||!e.authorizationContext)throw Re("METHOD_NOT_SUPPORTED");n??=e.account.onChange(De)}function D(){c=!1;for(const E of u)E()}function N(){r=void 0,D()}function v(E,m){if(!(!c||E.aborted||m?.aborted))return new Promise(M=>{function S(){clearTimeout(C),E.removeEventListener("abort",S),m?.removeEventListener("abort",S),u.delete(S),M()}const C=setTimeout(S,2e3);u.add(S),E.addEventListener("abort",S),m?.addEventListener("abort",S)})}function I(){const E=t.signal;if(y(E),r)return r;const m=e.roomSocket,M={...e.operationContext,signal:E},S=e.account.getCurrentUserId(M).then(C=>{if(_(E),!C)throw Re("UNAUTHORIZED");return m.connect({onPush(K){E.aborted||r!==S||(i?J(i,K):s&&(d.length<256?d.push(K):l=!0))},onDisconnect(){E.aborted||r!==S||(c=!0,a++,i&&(clearTimeout(i.leaseTimer),i.leaseTimer=void 0,x(i)))},onReconnect(){E.aborted||r!==S||(D(),i&&B(i))},onClose(){E.aborted||r!==S||(a++,N(),i&&B(i))}},M)}).then(C=>{if(E.aborted)throw C.close(),Re("ABORTED");return C});return r=S,S.catch(()=>{r===S&&N()}),S}async function H(E,m,M=t.signal){_(M);const S=I(),C=await S;_(M);const K=await C.request(`heybox/cloud_room/${E}`,m).catch(ce=>{throw ir(ce)==="UNAUTHORIZED"&&r===S&&(E==="list"||E==="create"||E==="join")&&(N(),a++,C.close(),E==="list"&&i&&B(i)),ce});return _(M),K}async function Y(E,m){await I(),_(m);const M=e.authorizationContext,S={...e.operationContext,signal:m},C=await(M.getForRoom?M.getForRoom(S,E):M.get(S));if(_(m),!C.token)throw Re("UNAUTHORIZED");return C.token}function R(E){clearTimeout(E.gapTimer),E.gapTimer=void 0}function x(E){i!==E||E.offline||(R(E),clearTimeout(E.leaseTimer),E.leaseTimer=void 0,E.offline=!0,e.onRoomEvent?.({type:"status",roomId:E.grant.room_id,code:"RESULT_UNKNOWN"}))}function U(E){i===E&&(i=void 0,R(E),E.pending.clear(),clearTimeout(E.leaseTimer))}function G(E,m){E===i&&(E.terminalCode=m,U(E),e.onRoomEvent?.({type:"status",roomId:E.grant.room_id,code:m}))}function V(E,m,M=!1){if(m.revision>E.version){const S=ud(m),C=E.snapshot;if(E.version=m.revision,!M&&S.locked===C.locked&&S.members.length===C.members.length&&S.members.every((K,ce)=>{const pe=C.members[ce];return K.id===pe.id&&K.phase===pe.phase&&K.owner===pe.owner}))return;E.snapshot=S}else if(!M)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 z(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)&&(R(E),E.pending.clear())}function j(E){E!==i||E.offline||E.recovery||E.catchingUp||E.gapTimer||(E.gapTimer=setTimeout(()=>{E.gapTimer=void 0,w(E)},rT))}function ee(E,m,M=!1){if(!un(m.recv_seq)||!m.message_id||!m.params){G(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),z(E),E.pending.size>0&&!M&&j(E);return}if(!M){if(E.pending.size<nT){E.pending.set(m.recv_seq,m),j(E);return}R(E),w(E)}}}function J(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"?G(E,m.status.code):"action"in m&&m.action?ee(E,m.action):"members"in m&&m.members&&V(E,m.members))}function Q(E){if(clearTimeout(E.leaseTimer),i!==E)return;const m=E.grant,M=m.token_expires_at_ms-Date.now();E.leaseTimer=setTimeout(async()=>{if(i!==E)return;if(E.offline){B(E);return}const S=a;try{const C=t.signal,ce=E.grant.preview_release||E.grant.token_expires_at_ms<=Date.now()+2e4?await Y(!0,C):void 0;if(E!==i||E.offline||a!==S)return;const pe=await H("heartbeat",{...sr(E.grant),...ce?{room_token:ce}:{}},C);if(i!==E||E.offline||a!==S)return;E.grant=Jr(pe,E.grant),pe.members&&V(E,pe.members),E.grant.recv_seq>E.cursor&&j(E)}catch{i===E&&a===S&&B(E);return}Q(E)},!m.preview_release&&M<2e4?Math.max(3e3,M-1e4):1e4)}async function P(E,m,M){const S=await Y(!0,M);return H("rejoin",{...sr(E),room_token:S,after_seq:m===0?0:m()},M)}function w(E){if(E!==i||E.offline||E.recovery||E.catchingUp)return E.catchingUp;if(R(E),E.cursor>=Math.max(E.grant.recv_seq,E.observed))return;const m=t.signal,M=a,S=E.cursor;return E.catchingUp=(async()=>{const C=await H("rejoin",{...sr(E.grant),after_seq:S},m);if(!(i!==E||M!==a||E.offline)){E.grant=Jr(C,E.grant),E.commandSeq=Math.max(E.commandSeq,E.grant.command_seq);for(const K of C.replay)i===E&&ee(E,K,!0);z(E),C.members&&V(E,C.members)}})().catch(C=>{if(E!==i)return;const K=ir(C);if(K==="ROOM_REPLAY_EXPIRED"){E.cursor===S&&B(E);return}if(K==="ROOM_CLOSED"||K==="INVALID_RESPONSE"){G(E,K);return}B(E)}).finally(()=>{E.catchingUp=void 0,i===E&&!E.offline&&E.cursor<Math.max(E.grant.recv_seq,E.observed)&&j(E)}),E.catchingUp}function B(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&&B(E)});return}const M=t.signal,S=a;return E.recovery=(async()=>{const C=await P(E.grant,()=>{if(i!==E||S!==a)throw Re("RESULT_UNKNOWN");return E.cursor},M);if(i!==E||S!==a)throw Re("RESULT_UNKNOWN");E.grant=Jr(C,E.grant),E.commandSeq=E.grant.command_seq;for(const K of C.replay)i===E&&ee(E,K,!0);if(z(E),E.cursor<E.grant.recv_seq)throw Re("RESULT_UNKNOWN");if(E===i){if(E.offline=!1,E.retryDelay=500,!C.members)throw Re("INVALID_RESPONSE");V(E,C.members,!0),Q(E)}})().catch(C=>{if(E!==i)return;const K=ir(C);if(!ji(K)){if(E.finishing&&(K==="UNAUTHORIZED"||K==="ROOM_CLOSED"))return K;G(E,K);return}clearTimeout(E.leaseTimer),E.leaseTimer=setTimeout(()=>{B(E)},E.retryDelay),E.retryDelay=Math.min(5e3,E.retryDelay*2)}).finally(()=>{E.recovery=void 0,E.cursor<E.observed&&j(E)}),E.recovery}async function O(E){if(s||i)throw Re("ROOM_ALREADY_JOINED");const m=Symbol();s=m;try{return await E()}finally{s===m&&(s=void 0,d=[],l=!1)}}async function W(E,m,M){const S=t.signal,C=s,K=()=>M?.aborted||C!==s;if(K())throw Re("ABORTED");const ce=ss(m,E==="create"?["definition","visibility"]:["definition","code"]),pe=ad(ce.definition),ye=E==="join"?Dr(ce.code,/^[a-f0-9]{12}$/):void 0,he=E==="create"?ce.visibility??"invite":void 0;if(he!==void 0&&he!=="public"&&he!=="invite")throw Re("INVALID_PARAMS");const Me=ye&&f.get(ye);if(Me&&await Me,K())throw Re("ABORTED");const Ne=await Y(!1,S),He={definition:pe,request_id:cd(),room_token:Ne},$e=()=>{if(K())throw Re("ABORTED");return E==="join"?H("join",{...He,code:ye},S):H("create",{...He,visibility:he},S)};let Fe=a,ze,ct=!1;try{ze=await $e()}catch(mt){if(_(S),!ji(ir(mt)))throw mt;Fe!==a&&await v(S,M),ct=!0,ze=await $e()}async function Yr(mt,Xm){if(Xm)try{mt=Jr(await P(mt,0,S),mt)}catch{}throw await H("leave",{...sr(mt),command_seq:mt.command_seq+1},S).catch(()=>{}),Re("ABORTED")}let Ke=Jr(ze);if(K())return Yr(Ke,ct||Fe!==a);const mu=e.operationContext.miniProgramDetail?.releaseChannel;if(mu==="public"&&Ke.preview_release||mu==="preview"&&!Ke.preview_release)throw Re("UNAUTHORIZED");if(ct||Ke.recv_seq>0||Fe!==a){Fe=a;try{ze=await P(Ke,0,S)}catch(mt){if(K())return Yr(Ke,Fe!==a);throw mt}if(Ke=Jr(ze,Ke),K())return Yr(Ke,Fe!==a)}_(S);const Zm=ud(ze.members),Lt={grant:Ke,cursor:0,observed:0,commandSeq:Ke.command_seq,version:ze.members.revision,snapshot:Zm,queue:Promise.resolve(),pending:new Map,offline:!1,retryDelay:500};i=Lt;for(const mt of ze.replay)i===Lt&&ee(Lt,mt,!0);for(const mt of d)J(Lt,mt);if(i!==Lt)throw Re("ROOM_CLOSED");return Q(Lt),Fe!==a?B(Lt):(l||Lt.cursor<Ke.recv_seq)&&w(Lt),{id:Ke.room_id,code:Ke.code,memberId:Ke.member_id,definition:pe,sequence:0,current:Lt.snapshot,streamId:Ke.generation,version:Lt.version}}async function $(E,m){const M=t.signal,S=ss(E,["definition","cursor"]),C=ad(S.definition),K=S.cursor===void 0?void 0:Dr(S.cursor,/^\d{1,19}$/);if(m?.aborted)throw Re("ABORTED");const ce=JSON.stringify([C.name,C.hash,K]);let pe=p.get(ce);if(!pe){const he=new Set,Me=Y(!1,M).then(Ne=>{if([...he].every(He=>He?.aborted))throw Re("ABORTED");return H("list",{definition:C,room_token:Ne,cursor:K},M)}).finally(()=>{p.get(ce)?.page===Me&&p.delete(ce)});pe={callers:he,page:Me},p.set(ce,pe)}pe.callers.add(m);const ye=await pe.page;if(_(M),m?.aborted)throw Re("ABORTED");if(!Array.isArray(ye.rooms)||ye.rooms.length>32)throw Re("INVALID_RESPONSE");return{rooms:ye.rooms.map(he=>{if(!/^[a-f0-9]{12}$/.test(he.code)||!un(he.member_count)||!un(he.capacity)||he.capacity<2||he.capacity>8||he.member_count>=he.capacity)throw Re("INVALID_RESPONSE");return{code:he.code,members:he.member_count,capacity:he.capacity}}),...ye.next_cursor?{nextCursor:ye.next_cursor}:{}}}async function Z(E,m,M,S,C){const K=()=>H("recover",{...sr(E.grant),command_seq:m},S);let ce=!0;async function pe(){try{return await K()}catch(Ne){_(S);const He=ir(Ne);if(od.has(He))throw Ne;ce=ji(He)||He==="UNAUTHORIZED"}}const ye=await pe();if(ye)return ye;if(c&&(await v(S,C),_(S),C?.aborted))throw Re("ABORTED");if(E.finishing&&M!==a){const Ne=await pe();if(Ne)return Ne}const he=await B(E,!0)??E.terminalCode;if(_(S),!(E.finishing&&(he==="ROOM_CLOSED"||he==="UNAUTHORIZED"))&&(E!==i||E.offline||!ce))throw Re("RESULT_UNKNOWN");try{return await K()}catch(Ne){throw he?G(E,he):ir(Ne)==="UNAUTHORIZED"&&B(E),Ne}}async function ie(E,m,M){const S=ss(m,E==="send"?["roomId","action","params","to"]:E==="lifecycle"?["roomId","operation"]:["roomId"]),C=i;if(!C||C.grant.room_id!==Dr(S.roomId)){if(E==="dispose")return;throw Re("ROOM_CLOSED")}let K,ce={};if(E==="send"){if(K="dispatch",!S.params||typeof S.params!="object"||Array.isArray(S.params)||S.to!==void 0&&(!Array.isArray(S.to)||S.to.length===0||S.to.length>8))throw Re("INVALID_PARAMS");ce={action:Dr(S.action),params:S.params,...Array.isArray(S.to)?{to:S.to.map(he=>Dr(he,/^[a-f0-9]{32}$/))}:{}}}else if(E==="lifecycle"){if(S.operation!=="close"&&S.operation!=="lockJoin"&&S.operation!=="unlockJoin")throw Re("INVALID_PARAMS");K=S.operation==="close"?"close":S.operation==="lockJoin"?"lock_join":"unlock_join"}else K=E;const pe=t.signal,ye=C.queue.then(async()=>{if(_(pe),C!==i)throw Re("ROOM_CLOSED");if(M?.aborted)throw Re("ABORTED");if(K==="dispose"){U(C),C.offline||await H("dispose",{...sr(C.grant),command_seq:C.commandSeq+1},pe).catch(()=>{});return}if(C.offline)throw Re("RESULT_UNKNOWN");const he=C.commandSeq+1;if(!Number.isSafeInteger(he))throw Re("SESSION_EXPIRED");const Me={...sr(C.grant),command_seq:he,...ce},Ne=()=>{C.uncertainSeq=void 0,C.commandSeq=Math.max(C.commandSeq,he)};function He(ze){if(od.has(ze))throw Ne(),Re(ze)}const $e=a;C.finishing=K==="leave"||K==="close";let Fe;try{Fe=await H(K,Me,pe)}catch(ze){_(pe);const ct=ir(ze);if(ct==="ROOM_BUSY"||ct==="RATE_LIMITED"||ct==="PAYLOAD_TOO_LARGE")throw ze;if(He(ct),!ji(ct)||C.uncertainSeq===he)throw C.finishing=!1,await B(C),Re(ct);C.uncertainSeq=he;try{Fe=await Z(C,he,$e,pe,M)}catch(Yr){_(pe);const Ke=ir(Yr);throw He(Ke),Ke==="ABORTED"?Yr:Re(ct)}}finally{C.finishing=!1}if(Ne(),K==="leave"&&U(C),K==="close"&&G(C,"ROOM_CLOSED"),K==="dispatch"){if(typeof Fe.message_id!="string"||!Fe.message_id)throw Re("INVALID_RESPONSE");return{messageId:Fe.message_id}}if(E==="lifecycle")return{disposition:"committed",code:"OK",requestId:"action_"+cd()}});return C.queue=ye.catch(()=>{}),ye}function me(){s=void 0,d=[],l=!1;const E=i;if(!E)return;const m=t.signal;U(E);const M=E.grant.code,S=E.queue.then(()=>H("leave",{...sr(E.grant),command_seq:E.commandSeq+1},m)).then(()=>{},()=>{}).finally(()=>{f.get(M)===S&&f.delete(M)});f.set(M,S)}function De(){if(i){const E=i;U(E),e.onRoomEvent?.({type:"status",roomId:E.grant.room_id,code:"UNAUTHORIZED"})}f.clear(),p.clear(),t.abort(),r?.then(E=>E.close(),()=>{}),t=new AbortController,N(),d=[],l=!1,s=void 0,a++}function Pe(){t.signal.aborted||(De(),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)=>$(E,m?.signal),"cloud.rooms.create":(E,m)=>O(()=>W("create",E,m?.signal)),"cloud.rooms.join":(E,m)=>O(()=>W("join",E,m?.signal)),"cloud.rooms.send":async(E,m)=>{if(h>=32)throw Re("ROOM_BUSY");h++;try{return await ie("send",E,m?.signal)}finally{h--}},"cloud.rooms.leave":(E,m)=>ie("leave",E,m?.signal),"cloud.rooms.dispose":(E,m)=>ie("dispose",E,m?.signal),"cloud.rooms.lifecycle":(E,m)=>ie("lifecycle",E,m?.signal)},releaseForReload:me,dispose:Pe}}const aT={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,"排行榜记录删除接口响应异常")}},oT={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,"当前排行榜记录接口响应异常")}},cT={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,"排行榜信息接口响应异常")}},uT={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,"排行榜列表接口响应异常")}},dT={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,"排行榜提交接口响应异常")}},lT={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=fT(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 rh(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 rh(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,yf))return()=>{};throw r}}function rh(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(hT(r),n,{status:e.status,sbe:r}):oe("HEYBOX_API_ERROR",n,{status:e.status})}function fT(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 hT(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 lT[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 mT="default",br="排行榜",ET=/^[A-Za-z0-9_-]{1,64}$/,gT=300*1e3,pT=250,_T=3;class TT{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(dT,{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(uT,{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(oT,{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(aT,{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(cT,{miniProgramId:r,...t}),s=at(i,qt,br);if(!Le(s)||typeof s.key!="string"||!ET.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(p=>(this.assertAccountGeneration(l),s&&a&&s.generation===h&&(r==="list"?a.size>=pT&&a.delete(a.keys().next().value):a.clear(),a.set(n,{expiresAt:Date.now()+gT,value:p})),p)).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>=_T)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)dd(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){dd(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??mT)}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 AT(e){return new TT(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 dd(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 IT={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,"云端存储删除接口响应异常")}},ld={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,"云端存储读取接口响应异常")}},fd={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 列表接口响应异常")}},bT={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="云端存储",yT=3e4,NT=128,wT=500;class DT{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(fd,{}),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"?wT: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(IT,{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(bT,{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=hd({...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(ld,{key:t}).then(u=>{this.assertAccountGeneration(r);const d=hd(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>=NT&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+yT,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([ld.id,fd.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 ST(e){return new DT(e)}function hd(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 OT=/^[A-Za-z0-9_-]{1,64}$/,md=20,MT=100,Ed=2048,RT=/^[A-Za-z0-9_-]{1,128}$/,gd=16*1024;function CT(e){const t=AT(e),r=ST(e),n=sT(e);return{handlers:{...n.handlers,[tr]:async s=>t.submit(LT(s)),[vt]:async s=>t.getList(PT(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(pd(s,fn)),[hn]:async s=>{const{key:a,value:c}=vT(s);return r.setItem(a,c)},[mn]:async s=>r.removeItem(pd(s,mn)),[Fr]:async s=>(xT(s),r.getKeys())},releaseRoomsForDocumentReload:n.releaseForReload,dispose:()=>{t.dispose(),r.dispose(),n.dispose()}}}function LT(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{...Kc(t.key,tr),score:t.score,...t.extra===void 0?{}:{extra:UT(t.extra)}}}function PT(e){if(e===void 0)return{limit:md};const t=On(e,vt,!0);Mn(t,["key","limit","cursor"],vt);const r=t.limit===void 0?md:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>MT)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{...Kc(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),Kc(r.key,t)}function pd(e,t){const r=On(e,t,!1);return Mn(r,["key"],t),nh(r.key,t)}function vT(e){const t=hn,r=On(e,t,!1);Mn(r,["key","value"],t);const n=nh(r.key,t);if(typeof r.value!="string")throw _t("INVALID_PARAMS",`${t} value 必须是字符串`);if(kT(r.value))throw _t("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>gd)throw _t("INVALID_PARAMS",`${t} value 不能超过 ${gd} 字节`);return{key:n,value:r.value}}function kT(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 xT(e){const t=On(e,Fr,!0);Mn(t,[],Fr)}function nh(e,t){if(typeof e!="string"||!RT.test(e))throw _t("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function On(e,t,r){if(e===void 0&&r)return{};if(!ih(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 Kc(e,t){if(e===void 0)return{};if(typeof e!="string"||!OT.test(e))throw _t("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function UT(e){if(!ih(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>Ed)throw _t("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${Ed} 字节`);return e}function ih(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _t(e,t){return{code:e,message:t}}const BT={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,"游戏存档接口响应异常")}},HT=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function Vo(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=>Vo(r,t+1)):Le(e)&&Object.values(e).every(r=>Vo(r,t+1))}function FT(e,t){const r=HT.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)&&Vo(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function sh(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 p;const _=new Promise(D=>{p=D}),y=f.then(()=>_);r.set(h,y);try{return await Se(()=>f,d.signal),ve(d.signal),e?.withLock?await e.withLock(h,l):await l()}finally{p(),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 p=JSON.parse(f);if(!p||typeof p!="object")return;const _=p;return _.version!==1||_.miniProgramId!==u.miniProgramId||_.userId!==u.userId||_.gameId!==u.gameId||(u.resource?_.resource!==u.resource:typeof _.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(_.accountId))||typeof _.taskId!="string"||(u.resource?_.taskId.length<1||_.taskId.length>128:!/^[1-9][0-9]{0,19}$/.test(_.taskId))?void 0:(l||t.set(h,_),_)}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),p=f?.taskId===d&&f.accountId===u.accountId;let _;try{_=await s(u,l,!0)}catch{ve(l.signal),p&&t.set(h,void 0);return}_?.taskId===d&&_.accountId===u.accountId?(await a(u,void 0,l),f&&!p&&t.set(h,f)):p&&t.set(h,_)})}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 zT=2e3,jT=5*6e4;function VT(e){const t=sh(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=U=>s?.release(U)??Promise.resolve(),l=new Set;let h=new AbortController,f;const p=()=>{h.abort(),h=new AbortController,f=void 0},_=(U=!0)=>{U&&t.clear(u),r++,p();for(const G of l)G.abort();for(const G of a)d(G).catch(()=>{});a.clear(),c.clear()},y=Ci(e.account,U=>{i&&U!==i&&(_(),i=void 0)}),D=e.authorization.onEvent(()=>_());function N(U,G,V,te){if(v(V),te.signal.aborted||!U.account_id||!e.presentation?.showSteamLoginRequired)return;const z=`${U.account_id}:${U.game_id}:${U.task_id??"sync"}`;if(f!==z){f=z;try{e.presentation.showSteamLoginRequired({userId:G,accountId:U.account_id},Ue(e.operationContext,h.signal))}catch{}}}function v(U){if(n||e.operationContext.signal.aborted)throw oe("RUNTIME_DESTROYED","小程序已关闭");if(U!==r)throw oe("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function I(U,G,V){if(v(G),await e.account.getCurrentUserId(V)!==U)throw _(),oe("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");v(G)}async function H(U,G,V,te){if(await I(G,V,te),!e.authorizationContext)throw oe("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const z=await e.authorizationContext.get(te);if(!z.token||z.expiresAt<=Date.now())throw oe("UNAUTHORIZED","小程序运行上下文已过期");const j=await Ri({network:e.network,operationContext:te,subject:"游戏存档",assertUsable:()=>v(V),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},BT,{...U,runtime_auth_context_token:z.token});if(await I(G,V,te),j.status==="failed"&&Le(j.result)&&j.result.error_code==="RECENT_SAVE_AVAILABLE")throw oe("RECENT_SAVE_AVAILABLE",typeof j.msg=="string"&&j.msg?j.msg:"已有近期存档,请直接查询使用");const ee=at(j,U.action,"游戏存档");if(!Le(ee))throw oe("INVALID_RESPONSE","存档响应不合法");return ee}async function Y(U,G,V){const te=GT(U,G),z=r;if(v(z),U==="file"&&(!e.transfer||!e.files))throw oe("METHOD_FORBIDDEN","宿主不支持存档文件读取");const j=new AbortController;l.add(j);let ee=!1;const J=U==="sync"?setTimeout(()=>{ee=!0,j.abort()},jT):void 0,Q=Ue(Ue(e.operationContext,V.signal),j.signal);try{const P=await e.account.getCurrentUserId(Q);if(!P)throw oe("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==P)throw _(),oe("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=P,U==="sync"||U==="parsed"){if(U==="sync"&&p(),!te.account_id){const $=await H({action:"check",game_id:te.game_id},P,z,Q);te.account_id=Ti($.account_id)}if(U==="sync")return await R(te,P,z,Q)}const w=await H({action:U,...te},P,z,Q);if(U==="list")return YT(w);if(U==="parsed")return FT(w.parsed_data,te.game_id);if(ah(w.file).fileId!==te.file_id)throw oe("INVALID_RESPONSE","文件标识不匹配");if(!s)throw oe("REQUEST_UNSUPPORTED","宿主不支持存档下载");const O=await s.download(w,async $=>{try{v(z),await H({action:"check",game_id:te.game_id,account_id:te.account_id},P,z,$)}catch(Z){const ie=Le(Z)?String(Z.code):"";throw["RUNTIME_DESTROYED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED","UNAUTHORIZED"].includes(ie)?(_(),oe("FILE_ACCESS_REVOKED","游戏存档授权已失效")):Z}},Q);let W=!1;try{if(await I(P,z,Q),v(z),Q.signal.aborted)throw oe("DOWNLOAD_CANCELLED","存档下载已取消");const $=e.fileRegistry.registerFile(O,"game-save","read");return a.add(O),c.set(jc(),{file:O,sizeBytes:s.sizeOf(O)}),W=!0,$}finally{W||await s.release(O)}}catch(P){throw ee?oe("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):P}finally{J!==void 0&&clearTimeout(J),l.delete(j)}}async function R(U,G,V,te){const z=e.identity.get()?.miniProgramId;if(!z)throw oe("INVALID_STATE","小程序身份尚未确认");const j={miniProgramId:z,userId:G,gameId:U.game_id,accountId:U.account_id},ee=Q=>H({action:"status",...U,task_id:Q},G,V,te);let J;try{const Q=await t.run(j,te,async()=>{await I(G,V,te);const w=await t.get(j,te);if(w){J=w;try{return{taskId:w,status:await ee(w)}}catch(O){if(!Le(O)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(O.code)))throw O;await t.set(j,void 0,te),J=void 0}}const B=await H({action:"sync",...U},G,V,te);return J=Ti(B.task_id),await t.set(j,J,te),await I(G,V,te),{taskId:J,status:void 0}});J=Q.taskId;let P=Q.status;for(;;){if(v(V),te.signal.aborted)throw oe("REQUEST_CANCELLED","已停止等待存档同步");if(P??=await ee(J),P.state==="succeeded"||P.state==="failed"){if(await t.remove(j,J,te),await I(G,V,te),P.state==="succeeded")return{state:"succeeded"};throw oe(P.error_code?sa(P.error_code):"SYNC_FAILED",P.message?sa(P.message):"存档同步失败")}if(P.state!=="syncing"&&P.state!=="uploading")throw oe("INVALID_RESPONSE","同步状态不合法");P=void 0,await qT(zT,te.signal)}}catch(Q){if(Le(Q)){const P=String(Q.code);P==="STEAM_LOGIN_REQUIRED"&&N({...U,task_id:J},G,V,te),J&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(P)&&await t.remove(j,J,u)}throw Q}}return{handlers:{"gameSaves.list":(U,G)=>Y("list",U,G),"gameSaves.sync":(U,G)=>Y("sync",U,G),"gameSaves.readParsedData":(U,G)=>Y("parsed",U,G),"gameSaves.getFile":(U,G)=>Y("file",U,G)},diagnostics:{async getSnapshot(){const U=r;return i&&await I(i,U,e.operationContext),v(U),Array.from(c,([G,V])=>({id:G,name:V.file.name,sizeBytes:V.sizeBytes}))},async readFile(U,G){const V=r;v(V);const te=c.get(U);if(!te)throw oe("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const z=Ue(e.operationContext,G);z.signal.throwIfAborted();const j=await te.file.read(z);try{return z.signal.throwIfAborted(),v(V),{name:te.file.name,bytes:j}}catch(ee){throw j.fill(0),ee}}},allowsRead(U,G){return["file.readBytes","file.readText","file.stat","file.exists"].includes(U)&&Le(G)&&e.fileRegistry.isGameSaveRef(G.target)},dispose(){n||(n=!0,_(!1),y(),D())}}}function GT(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 Go(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw oe("INVALID_RESPONSE","服务端存档数值无效");return e}function ah(e){if(!Le(e))throw oe("INVALID_RESPONSE","存档文件信息无效");return{fileId:Ti(e.file_id),name:sa(e.name),originalPath:sa(e.original_path),sizeBytes:Go(e.size_bytes),modifiedAt:Go(e.modified_at)}}function YT(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:Go(t.created_at),files:t.files.map(ah)}})}}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 oh(e,t){return{auth:"optional",channel:"api",id:e,method:"GET",path:t,query(r){return{...r}},parse(r){return Wc(r,"赛事中心接口响应异常")}}}function ch(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 Wc(r,"赛事中心接口响应异常")}}}const QT=oh("heybox.bbs.app.link.tree.get","/bbs/app/link/tree"),WT=oh("heybox.bbs.app.comment.sub.comments.get","/bbs/app/comment/sub/comments"),$T=ch("heybox.bbs.app.comment.support.post","/bbs/app/comment/support"),KT=ch("heybox.bbs.app.comment.delete.post","/bbs/app/comment/delete");function va(e){return Ve(e,"社区评论响应异常")}const _d={...QT,parse:va},ZT={...WT,parse:va},XT={...$T,bodyEncoding:"form",body:e=>Object.fromEntries(Object.entries(e.body).map(([t,r])=>[t,String(r)])),parse:va},JT={...KT,bodyEncoding:"form",body:e=>Object.fromEntries(Object.entries(e.body).map(([t,r])=>[t,String(r)])),parse:va},eA={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,"社区操作响应异常")},tA={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,"社区操作响应异常")},rA={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,"关联帖子响应异常")},nA=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 uh(e){return e>=55296&&e<=57343}function iA(e){return e>=56320&&e<=57343}function sA(e,t){return(e-55296)*1024+9216+t}function dh(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function lh(e){return e>=64976&&e<=65007||nA.has(e)}var q;(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"})(q||(q={}));const aA=65536;class oA{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=aA,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(iA(r))return this.pos++,this._addGap(),sA(t,r)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,g.EOF;return this._err(q.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,uh(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){dh(t)?this._err(q.controlCharacterInInputStream):lh(t)&&this._err(q.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 fh(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 cA=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))),uA=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 dA(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=uA.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 lA=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 Yo(e){return e>=et.ZERO&&e<=et.NINE}function fA(e){return e>=et.UPPER_A&&e<=et.UPPER_F||e>=et.LOWER_A&&e<=et.LOWER_F}function hA(e){return e>=et.UPPER_A&&e<=et.UPPER_Z||e>=et.LOWER_A&&e<=et.LOWER_Z||Yo(e)}function mA(e){return e===et.EQUALS||hA(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 EA{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)|lA)===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(Yo(i)||fA(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(Yo(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(dA(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=gA(n,i,this.treeIndex+Math.max(1,s),a),this.treeIndex<0)return this.result===0||this.decodeMode===er.Attribute&&(s===0||mA(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 gA(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 F;(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"})(F||(F={}));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 pA=new Map([[F.A,o.A],[F.ADDRESS,o.ADDRESS],[F.ANNOTATION_XML,o.ANNOTATION_XML],[F.APPLET,o.APPLET],[F.AREA,o.AREA],[F.ARTICLE,o.ARTICLE],[F.ASIDE,o.ASIDE],[F.B,o.B],[F.BASE,o.BASE],[F.BASEFONT,o.BASEFONT],[F.BGSOUND,o.BGSOUND],[F.BIG,o.BIG],[F.BLOCKQUOTE,o.BLOCKQUOTE],[F.BODY,o.BODY],[F.BR,o.BR],[F.BUTTON,o.BUTTON],[F.CAPTION,o.CAPTION],[F.CENTER,o.CENTER],[F.CODE,o.CODE],[F.COL,o.COL],[F.COLGROUP,o.COLGROUP],[F.DD,o.DD],[F.DESC,o.DESC],[F.DETAILS,o.DETAILS],[F.DIALOG,o.DIALOG],[F.DIR,o.DIR],[F.DIV,o.DIV],[F.DL,o.DL],[F.DT,o.DT],[F.EM,o.EM],[F.EMBED,o.EMBED],[F.FIELDSET,o.FIELDSET],[F.FIGCAPTION,o.FIGCAPTION],[F.FIGURE,o.FIGURE],[F.FONT,o.FONT],[F.FOOTER,o.FOOTER],[F.FOREIGN_OBJECT,o.FOREIGN_OBJECT],[F.FORM,o.FORM],[F.FRAME,o.FRAME],[F.FRAMESET,o.FRAMESET],[F.H1,o.H1],[F.H2,o.H2],[F.H3,o.H3],[F.H4,o.H4],[F.H5,o.H5],[F.H6,o.H6],[F.HEAD,o.HEAD],[F.HEADER,o.HEADER],[F.HGROUP,o.HGROUP],[F.HR,o.HR],[F.HTML,o.HTML],[F.I,o.I],[F.IMG,o.IMG],[F.IMAGE,o.IMAGE],[F.INPUT,o.INPUT],[F.IFRAME,o.IFRAME],[F.KEYGEN,o.KEYGEN],[F.LABEL,o.LABEL],[F.LI,o.LI],[F.LINK,o.LINK],[F.LISTING,o.LISTING],[F.MAIN,o.MAIN],[F.MALIGNMARK,o.MALIGNMARK],[F.MARQUEE,o.MARQUEE],[F.MATH,o.MATH],[F.MENU,o.MENU],[F.META,o.META],[F.MGLYPH,o.MGLYPH],[F.MI,o.MI],[F.MO,o.MO],[F.MN,o.MN],[F.MS,o.MS],[F.MTEXT,o.MTEXT],[F.NAV,o.NAV],[F.NOBR,o.NOBR],[F.NOFRAMES,o.NOFRAMES],[F.NOEMBED,o.NOEMBED],[F.NOSCRIPT,o.NOSCRIPT],[F.OBJECT,o.OBJECT],[F.OL,o.OL],[F.OPTGROUP,o.OPTGROUP],[F.OPTION,o.OPTION],[F.P,o.P],[F.PARAM,o.PARAM],[F.PLAINTEXT,o.PLAINTEXT],[F.PRE,o.PRE],[F.RB,o.RB],[F.RP,o.RP],[F.RT,o.RT],[F.RTC,o.RTC],[F.RUBY,o.RUBY],[F.S,o.S],[F.SCRIPT,o.SCRIPT],[F.SEARCH,o.SEARCH],[F.SECTION,o.SECTION],[F.SELECT,o.SELECT],[F.SOURCE,o.SOURCE],[F.SMALL,o.SMALL],[F.SPAN,o.SPAN],[F.STRIKE,o.STRIKE],[F.STRONG,o.STRONG],[F.STYLE,o.STYLE],[F.SUB,o.SUB],[F.SUMMARY,o.SUMMARY],[F.SUP,o.SUP],[F.TABLE,o.TABLE],[F.TBODY,o.TBODY],[F.TEMPLATE,o.TEMPLATE],[F.TEXTAREA,o.TEXTAREA],[F.TFOOT,o.TFOOT],[F.TD,o.TD],[F.TH,o.TH],[F.THEAD,o.THEAD],[F.TITLE,o.TITLE],[F.TR,o.TR],[F.TRACK,o.TRACK],[F.TT,o.TT],[F.U,o.U],[F.UL,o.UL],[F.SVG,o.SVG],[F.VAR,o.VAR],[F.WBR,o.WBR],[F.XMP,o.XMP]]);function ka(e){var t;return(t=pA.get(e))!==null&&t!==void 0?t:o.UNKNOWN}const ae=o,_A={[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},qo=new Set([ae.H1,ae.H2,ae.H3,ae.H4,ae.H5,ae.H6]);F.STYLE,F.SCRIPT,F.XMP,F.IFRAME,F.NOEMBED,F.NOFRAMES,F.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 TA(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 AA(e){return e>=g.LATIN_SMALL_A&&e<=g.LATIN_SMALL_Z}function or(e){return AA(e)||Yn(e)}function Td(e){return or(e)||TA(e)}function Vi(e){return e+32}function hh(e){return e===g.SPACE||e===g.LINE_FEED||e===g.TABULATION||e===g.FORM_FEED}function Ad(e){return hh(e)||e===g.SOLIDUS||e===g.GREATER_THAN_SIGN}function IA(e){return e===g.NULL?q.nullCharacterReference:e>1114111?q.characterReferenceOutsideUnicodeRange:uh(e)?q.surrogateCharacterReference:lh(e)?q.noncharacterCharacterReference:dh(e)||e===g.CARRIAGE_RETURN?q.controlCharacterReference:null}class bA{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 oA(r),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new EA(cA,(n,i)=>{this.preprocessor.pos=this.entityStartPos+i-1,this._flushCodePointConsumedAsCharacterReference(n)},r.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(q.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:n=>{this._err(q.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+n)},validateNumericCharacterReference:n=>{const i=IA(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(fh(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(q.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(q.endTagWithAttributes),t.selfClosing&&this._err(q.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=hh(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(q.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(q.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(q.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(q.unexpectedNullCharacter),this._emitChars(Ye);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case g.NULL:{this._err(q.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(q.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=A.BOGUS_COMMENT,this._stateBogusComment(t);break}case g.EOF:{this._err(q.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(q.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(q.missingEndTagName),this.state=A.DATA;break}case g.EOF:{this._err(q.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(q.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(q.unexpectedNullCharacter),r.tagName+=Ye;break}case g.EOF:{this._err(q.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(q.unexpectedNullCharacter),this._emitChars(Ye);break}case g.EOF:{this._err(q.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(q.unexpectedNullCharacter),this.state=A.SCRIPT_DATA_ESCAPED,this._emitChars(Ye);break}case g.EOF:{this._err(q.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(q.unexpectedNullCharacter),this.state=A.SCRIPT_DATA_ESCAPED,this._emitChars(Ye);break}case g.EOF:{this._err(q.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)&&Ad(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(q.unexpectedNullCharacter),this._emitChars(Ye);break}case g.EOF:{this._err(q.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(q.unexpectedNullCharacter),this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Ye);break}case g.EOF:{this._err(q.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(q.unexpectedNullCharacter),this.state=A.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Ye);break}case g.EOF:{this._err(q.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)&&Ad(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(q.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(q.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case g.NULL:{this._err(q.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(q.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(q.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(q.unexpectedNullCharacter),this.currentAttr.value+=Ye;break}case g.EOF:{this._err(q.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(q.unexpectedNullCharacter),this.currentAttr.value+=Ye;break}case g.EOF:{this._err(q.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(q.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(q.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case g.EOF:{this._err(q.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(q.eofInTag),this._emitEOFToken();break}default:this._err(q.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(q.eofInTag),this._emitEOFToken();break}default:this._err(q.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(q.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(q.cdataInHtmlContent),this._createCommentToken(Et.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=A.BOGUS_COMMENT):this._ensureHibernation()||(this._err(q.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(q.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(q.abruptClosingOfEmptyComment),this.state=A.DATA,this.emitCurrentComment(r);break}case g.EOF:{this._err(q.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(q.unexpectedNullCharacter),r.data+=Ye;break}case g.EOF:{this._err(q.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(q.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(q.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(q.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(q.incorrectlyClosedComment),this.state=A.DATA,this.emitCurrentComment(r);break}case g.EOF:{this._err(q.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(q.eofInDoctype),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(q.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(q.unexpectedNullCharacter),this._createDoctypeToken(Ye),this.state=A.DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this._err(q.missingDoctypeName),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err(q.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(q.unexpectedNullCharacter),r.name+=Ye;break}case g.EOF:{this._err(q.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(q.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(q.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(q.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=A.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(q.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=A.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(q.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.EOF:{this._err(q.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(q.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(q.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.EOF:{this._err(q.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(q.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(q.unexpectedNullCharacter),r.publicId+=Ye;break}case g.GREATER_THAN_SIGN:{this._err(q.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err(q.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(q.unexpectedNullCharacter),r.publicId+=Ye;break}case g.GREATER_THAN_SIGN:{this._err(q.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err(q.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(q.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(q.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.EOF:{this._err(q.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(q.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(q.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(q.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(q.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(q.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=A.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(q.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.EOF:{this._err(q.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(q.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(q.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=A.DATA,this.emitCurrentDoctype(r);break}case g.EOF:{this._err(q.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(q.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(q.unexpectedNullCharacter),r.systemId+=Ye;break}case g.GREATER_THAN_SIGN:{this._err(q.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err(q.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(q.unexpectedNullCharacter),r.systemId+=Ye;break}case g.GREATER_THAN_SIGN:{this._err(q.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=A.DATA;break}case g.EOF:{this._err(q.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(q.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(q.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(q.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(q.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()&&Td(this.preprocessor.peek(1))?A.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(t){Td(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===g.SEMICOLON&&this._err(q.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t))}}const mh=new Set([o.DD,o.DT,o.LI,o.OPTGROUP,o.OPTION,o.P,o.RB,o.RP,o.RT,o.RTC]),Id=new Set([...mh,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]),yA=new Set([...aa,o.OL,o.UL]),NA=new Set([...aa,o.BUTTON]),bd=new Set([o.ANNOTATION_XML,o.MI,o.MN,o.MO,o.MS,o.MTEXT]),yd=new Set([o.DESC,o.FOREIGN_OBJECT,o.TITLE]),wA=new Set([o.TR,o.TEMPLATE,o.HTML]),DA=new Set([o.TBODY,o.TFOOT,o.THEAD,o.TEMPLATE,o.HTML]),SA=new Set([o.TABLE,o.TEMPLATE,o.HTML]),OA=new Set([o.TD,o.TH]);class MA{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(qo,ne.HTML)}popUntilTableCellPopped(){this.popUntilPopped(OA,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(SA,ne.HTML)}clearBackToTableBodyContext(){this.clearBackTo(DA,ne.HTML)}clearBackToTableRowContext(){this.clearBackTo(wA,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(yd.has(i))return!1;break}case ne.MATHML:{if(bd.has(i))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,aa)}hasInListItemScope(t){return this.hasInDynamicScope(t,yA)}hasInButtonScope(t){return this.hasInDynamicScope(t,NA)}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(qo.has(r))return!0;if(aa.has(r))return!1;break}case ne.SVG:{if(yd.has(r))return!1;break}case ne.MATHML:{if(bd.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&&mh.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&Id.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&Id.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 Nd={type:Yt.Marker};class RA{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(Nd)}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(Nd);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}}},Eh="html",CA="about:legacy-compat",LA="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",gh=["+//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//"],PA=[...gh,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],vA=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),ph=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],kA=[...ph,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function wd(e,t){return t.some(r=>e.startsWith(r))}function xA(e){return e.name===Eh&&e.publicId===null&&(e.systemId===null||e.systemId===CA)}function UA(e){if(e.name!==Eh)return wt.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===LA)return wt.QUIRKS;let{publicId:r}=e;if(r!==null){if(r=r.toLowerCase(),vA.has(r))return wt.QUIRKS;let n=t===null?PA:gh;if(wd(r,n))return wt.QUIRKS;if(n=t===null?ph:kA,wd(r,n))return wt.LIMITED_QUIRKS}return wt.NO_QUIRKS}const Dd={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},BA="definitionurl",HA="definitionURL",FA=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])),zA=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}]]),jA=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])),VA=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 GA(e){const t=e.tagID;return t===o.FONT&&e.attrs.some(({name:n})=>n===xr.COLOR||n===xr.SIZE||n===xr.FACE)||VA.has(t)}function _h(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===BA){e.attrs[t].name=HA;break}}function Th(e){for(let t=0;t<e.attrs.length;t++){const r=FA.get(e.attrs[t].name);r!=null&&(e.attrs[t].name=r)}}function Zc(e){for(let t=0;t<e.attrs.length;t++){const r=zA.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 YA(e){const t=jA.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 QA(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===Dd.TEXT_HTML||i===Dd.APPLICATION_XML}}return t===ne.SVG&&(e===o.FOREIGN_OBJECT||e===o.DESC||e===o.TITLE)}function WA(e,t,r,n){return(!n||n===ne.HTML)&&QA(e,t,r)||(!n||n===ne.MATHML)&&qA(e,t)}const $A="hidden",KA=8,ZA=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 XA={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Ah=new Set([o.TABLE,o.TBODY,o.TFOOT,o.THEAD,o.TR]),Sd={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:cr,onParseError:null};class JA{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={...Sd,...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 bA(this.options,this),this.activeFormattingElements=new RA(this.treeAdapter),this.fragmentContextID=n?ka(this.treeAdapter.getTagName(n)):o.UNKNOWN,this._setContextModes(n??this.document,this.fragmentContextID),this.openElements=new MA(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={...Sd,...r};t??(t=n.treeAdapter.createElement(F.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:XA,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)===F.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(F.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)===F.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 WA(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 Ah.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 _A[n].has(r)}onCharacter(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.IN_BODY:case b.IN_CAPTION:case b.IN_CELL:case b.IN_TEMPLATE:{bh(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:{Oh(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){Ob(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:{aI(this,t);break}case b.AFTER_AFTER_BODY:case b.AFTER_AFTER_FRAMESET:{oI(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case b.INITIAL:{cI(this,t);break}case b.BEFORE_HEAD:case b.IN_HEAD:case b.IN_HEAD_NO_SCRIPT:case b.AFTER_HEAD:{this._err(t,q.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,q.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?Rb(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case b.INITIAL:{kn(this,t);break}case b.BEFORE_HTML:{uI(this,t);break}case b.BEFORE_HEAD:{lI(this,t);break}case b.IN_HEAD:{Bt(this,t);break}case b.IN_HEAD_NO_SCRIPT:{mI(this,t);break}case b.AFTER_HEAD:{gI(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:{fb(this,t);break}case b.IN_COLUMN_GROUP:{eu(this,t);break}case b.IN_TABLE_BODY:{Ba(this,t);break}case b.IN_ROW:{Ha(this,t);break}case b.IN_CELL:{Eb(this,t);break}case b.IN_SELECT:{Ch(this,t);break}case b.IN_SELECT_IN_TABLE:{pb(this,t);break}case b.IN_TEMPLATE:{Tb(this,t);break}case b.AFTER_BODY:{Ib(this,t);break}case b.IN_FRAMESET:{bb(this,t);break}case b.AFTER_FRAMESET:{Nb(this,t);break}case b.AFTER_AFTER_BODY:{Db(this,t);break}case b.AFTER_AFTER_FRAMESET:{Sb(this,t);break}}}onEndTag(t){this.skipNextNewLine=!1,this.currentToken=t,this.currentNotInHTML?Cb(this,t):this._endTagOutsideForeignContent(t)}_endTagOutsideForeignContent(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:{hI(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:{Ua(this,t);break}case b.TEXT:{rb(this,t);break}case b.IN_TABLE:{Ai(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:{mb(this,t);break}case b.IN_TABLE_BODY:{Wo(this,t);break}case b.IN_ROW:{Rh(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:{vh(this,t);break}case b.IN_FRAMESET:{yb(this,t);break}case b.AFTER_FRAMESET:{wb(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:{Dh(this,t);break}case b.TEXT:{nb(this,t);break}case b.IN_TABLE_TEXT:{xn(this,t);break}case b.IN_TEMPLATE:{Ph(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:{Jc(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:{Ih(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:{Sh(this,t);break}}}}function eI(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):wh(e,t),r}function tI(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 rI(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>=ZA;!c||u?(u&&e.activeFormattingElements.removeEntry(c),e.openElements.remove(a)):(a=nI(e,c),n===t&&(e.activeFormattingElements.bookmark=c),e.treeAdapter.detachNode(n),e.treeAdapter.appendChild(a,n),n=a)}return n}function nI(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 iI(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 sI(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 Xc(e,t){for(let r=0;r<KA;r++){const n=eI(e,t);if(!n)break;const i=tI(e,n);if(!i)break;e.activeFormattingElements.bookmark=n;const s=rI(e,i,n.element),a=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(s),a&&iI(e,a,s),sI(e,i,n)}}function Qo(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function aI(e,t){e._appendCommentNode(t,e.openElements.items[0])}function oI(e,t){e._appendCommentNode(t,e.document)}function Jc(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 cI(e,t){e._setDocumentType(t);const r=t.forceQuirks?wt.QUIRKS:UA(t);xA(t)||e._err(t,q.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,r),e.insertionMode=b.BEFORE_HTML}function kn(e,t){e._err(t,q.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,wt.QUIRKS),e.insertionMode=b.BEFORE_HTML,e._processToken(t)}function uI(e,t){t.tagID===o.HTML?(e._insertElement(t,ne.HTML),e.insertionMode=b.BEFORE_HEAD):$n(e,t)}function dI(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 lI(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 fI(e,t){const r=t.tagID;r===o.HEAD||r===o.BODY||r===o.HTML||r===o.BR?Kn(e,t):e._err(t,q.endTagWithoutMatchingOpenElement)}function Kn(e,t){e._insertFakeElement(F.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,q.misplacedStartTagForHeadElement);break}default:Zn(e,t)}}function hI(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,q.endTagWithoutMatchingOpenElement)}}function Vr(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==o.TEMPLATE&&e._err(t,q.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(o.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,q.endTagWithoutMatchingOpenElement)}function Zn(e,t){e.openElements.pop(),e.insertionMode=b.AFTER_HEAD,e._processToken(t)}function mI(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,q.nestedNoscriptInHead);break}default:Xn(e,t)}}function EI(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,q.endTagWithoutMatchingOpenElement)}}function Xn(e,t){const r=t.type===xe.EOF?q.openElementsLeftAfterEof:q.disallowedContentInNoscriptInHead;e._err(t,r),e.openElements.pop(),e.insertionMode=b.IN_HEAD,e._processToken(t)}function gI(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,q.abandonedHeadElementChild),e.openElements.push(e.headElement,o.HEAD),Bt(e,t),e.openElements.remove(e.headElement);break}case o.HEAD:{e._err(t,q.misplacedStartTagForHeadElement);break}default:Jn(e,t)}}function pI(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,q.endTagWithoutMatchingOpenElement)}}function Jn(e,t){e._insertFakeElement(F.BODY,o.BODY),e.insertionMode=b.IN_BODY,xa(e,t)}function xa(e,t){switch(t.type){case xe.CHARACTER:{bh(e,t);break}case xe.WHITESPACE_CHARACTER:{Ih(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:{Dh(e,t);break}}}function Ih(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function bh(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function _I(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function TI(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(r,t.attrs))}function AI(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 II(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,ne.HTML)}function bI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&qo.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,ne.HTML)}function yI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function NI(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 wI(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 DI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.tokenizer.state=pt.PLAINTEXT}function SI(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 OI(e,t){const r=e.activeFormattingElements.getElementEntryInScopeWithTagName(F.A);r&&(Xc(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 MI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function RI(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(o.NOBR)&&(Xc(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function CI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function LI(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 yh(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ne.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function Nh(e){const t=fh(e,xr.TYPE);return t!=null&&t.toLowerCase()===$A}function PI(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ne.HTML),Nh(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function vI(e,t){e._appendElement(t,ne.HTML),t.ackSelfClosing=!0}function kI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._appendElement(t,ne.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function xI(e,t){t.tagName=F.IMG,t.tagID=o.IMG,yh(e,t)}function UI(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 BI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,pt.RAWTEXT)}function HI(e,t){e.framesetOk=!1,e._switchToTextParsing(t,pt.RAWTEXT)}function Od(e,t){e._switchToTextParsing(t,pt.RAWTEXT)}function FI(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 zI(e,t){e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML)}function jI(e,t){e.openElements.hasInScope(o.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,ne.HTML)}function VI(e,t){e.openElements.hasInScope(o.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(o.RTC),e._insertElement(t,ne.HTML)}function GI(e,t){e._reconstructActiveFormattingElements(),_h(t),Zc(t),t.selfClosing?e._appendElement(t,ne.MATHML):e._insertElement(t,ne.MATHML),t.ackSelfClosing=!0}function YI(e,t){e._reconstructActiveFormattingElements(),Th(t),Zc(t),t.selfClosing?e._appendElement(t,ne.SVG):e._insertElement(t,ne.SVG),t.ackSelfClosing=!0}function Md(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:{MI(e,t);break}case o.A:{OI(e,t);break}case o.H1:case o.H2:case o.H3:case o.H4:case o.H5:case o.H6:{bI(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:{II(e,t);break}case o.LI:case o.DD:case o.DT:{wI(e,t);break}case o.BR:case o.IMG:case o.WBR:case o.AREA:case o.EMBED:case o.KEYGEN:{yh(e,t);break}case o.HR:{kI(e,t);break}case o.RB:case o.RTC:{jI(e,t);break}case o.RT:case o.RP:{VI(e,t);break}case o.PRE:case o.LISTING:{yI(e,t);break}case o.XMP:{BI(e,t);break}case o.SVG:{YI(e,t);break}case o.HTML:{_I(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:{TI(e,t);break}case o.FORM:{NI(e,t);break}case o.NOBR:{RI(e,t);break}case o.MATH:{GI(e,t);break}case o.TABLE:{LI(e,t);break}case o.INPUT:{PI(e,t);break}case o.PARAM:case o.TRACK:case o.SOURCE:{vI(e,t);break}case o.IMAGE:{xI(e,t);break}case o.BUTTON:{SI(e,t);break}case o.APPLET:case o.OBJECT:case o.MARQUEE:{CI(e,t);break}case o.IFRAME:{HI(e,t);break}case o.SELECT:{FI(e,t);break}case o.OPTION:case o.OPTGROUP:{zI(e,t);break}case o.NOEMBED:case o.NOFRAMES:{Od(e,t);break}case o.FRAMESET:{AI(e,t);break}case o.TEXTAREA:{UI(e,t);break}case o.NOSCRIPT:{e.options.scriptingEnabled?Od(e,t):Md(e,t);break}case o.PLAINTEXT:{DI(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:Md(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 QI(e,t){e.openElements.hasInScope(o.BODY)&&(e.insertionMode=b.AFTER_BODY,vh(e,t))}function WI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r))}function $I(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 KI(e){e.openElements.hasInButtonScope(o.P)||e._insertFakeElement(F.P,o.P),e._closePElement()}function ZI(e){e.openElements.hasInListItemScope(o.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(o.LI),e.openElements.popUntilTagNamePopped(o.LI))}function XI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r))}function JI(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function eb(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker())}function tb(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(F.BR,o.BR),e.openElements.pop(),e.framesetOk=!1}function wh(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:{Xc(e,t);break}case o.P:{KI(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:{WI(e,t);break}case o.LI:{ZI(e);break}case o.DD:case o.DT:{XI(e,t);break}case o.H1:case o.H2:case o.H3:case o.H4:case o.H5:case o.H6:{JI(e);break}case o.BR:{tb(e);break}case o.BODY:{qI(e,t);break}case o.HTML:{QI(e,t);break}case o.FORM:{$I(e);break}case o.APPLET:case o.OBJECT:case o.MARQUEE:{eb(e,t);break}case o.TEMPLATE:{Vr(e,t);break}default:wh(e,t)}}function Dh(e,t){e.tmplInsertionModeStack.length>0?Ph(e,t):Jc(e,t)}function rb(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 nb(e,t){e._err(t,q.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function io(e,t){if(e.openElements.currentTagId!==void 0&&Ah.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:{Oh(e,t);break}case xe.WHITESPACE_CHARACTER:{Sh(e,t);break}}else Li(e,t)}function ib(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,ne.HTML),e.insertionMode=b.IN_CAPTION}function sb(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ne.HTML),e.insertionMode=b.IN_COLUMN_GROUP}function ab(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(F.COLGROUP,o.COLGROUP),e.insertionMode=b.IN_COLUMN_GROUP,eu(e,t)}function ob(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ne.HTML),e.insertionMode=b.IN_TABLE_BODY}function cb(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(F.TBODY,o.TBODY),e.insertionMode=b.IN_TABLE_BODY,Ba(e,t)}function ub(e,t){e.openElements.hasInTableScope(o.TABLE)&&(e.openElements.popUntilTagNamePopped(o.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function db(e,t){Nh(t)?e._appendElement(t,ne.HTML):Li(e,t),t.ackSelfClosing=!0}function lb(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:{cb(e,t);break}case o.STYLE:case o.SCRIPT:case o.TEMPLATE:{Bt(e,t);break}case o.COL:{ab(e,t);break}case o.FORM:{lb(e,t);break}case o.TABLE:{ub(e,t);break}case o.TBODY:case o.TFOOT:case o.THEAD:{ob(e,t);break}case o.INPUT:{db(e,t);break}case o.CAPTION:{ib(e,t);break}case o.COLGROUP:{sb(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 Sh(e,t){e.pendingCharacterTokens.push(t)}function Oh(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 Mh=new Set([o.CAPTION,o.COL,o.COLGROUP,o.TBODY,o.TD,o.TFOOT,o.TH,o.THEAD,o.TR]);function fb(e,t){const r=t.tagID;Mh.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 hb(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 eu(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 mb(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(F.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 Wo(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 Rh(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,Wo(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,Wo(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 Eb(e,t){const r=t.tagID;Mh.has(r)?(e.openElements.hasInTableScope(o.TD)||e.openElements.hasInTableScope(o.TH))&&(e._closeTableCell(),Ha(e,t)):ot(e,t)}function gb(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(),Rh(e,t));break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:break;default:Ua(e,t)}}function Ch(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 Lh(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 pb(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)):Ch(e,t)}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.hasInTableScope(r)&&(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode(),e.onEndTag(t)):Lh(e,t)}function Tb(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,eu(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 Ab(e,t){t.tagID===o.TEMPLATE&&Vr(e,t)}function Ph(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(o.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):Jc(e,t)}function Ib(e,t){t.tagID===o.HTML?ot(e,t):ca(e,t)}function vh(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 bb(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 yb(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 Nb(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.NOFRAMES:{Bt(e,t);break}}}function wb(e,t){t.tagID===o.HTML&&(e.insertionMode=b.AFTER_AFTER_FRAMESET)}function Db(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 Sb(e,t){switch(t.tagID){case o.HTML:{ot(e,t);break}case o.NOFRAMES:{Bt(e,t);break}}}function Ob(e,t){t.chars=Ye,e._insertCharacters(t)}function Mb(e,t){e._insertCharacters(t),e.framesetOk=!1}function kh(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 Rb(e,t){if(GA(t))kh(e),e._startTagOutsideForeignContent(t);else{const r=e._getAdjustedCurrentElement(),n=e.treeAdapter.getNamespaceURI(r);n===ne.MATHML?_h(t):n===ne.SVG&&(YA(t),Th(t)),Zc(t),t.selfClosing?e._appendElement(t,n):e._insertElement(t,n),t.ackSelfClosing=!0}}function Cb(e,t){if(t.tagID===o.P||t.tagID===o.BR){kh(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}}}F.AREA,F.BASE,F.BASEFONT,F.BGSOUND,F.BR,F.COL,F.EMBED,F.FRAME,F.HR,F.IMG,F.INPUT,F.KEYGEN,F.LINK,F.META,F.PARAM,F.SOURCE,F.TRACK,F.WBR;function Lb(e,t,r){typeof e=="string"&&(r=t,t=e,e=null);const n=JA.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 Pb(e,t){if(!Array.isArray(e))throw Oe("帖子响应列表无效");return e.map(t)}function vb(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 kb(e){const t=lr(e);return{id:At(t.id),name:At(t.name),avatar:At(t.avatar),isMe:os(t.isMe)}}function xb(e){const t=lr(e);return{url:At(t.url),width:Sr(t.width),height:Sr(t.height)}}function Ub(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:kb(t.author),content:Pb(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:xb(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 Bb=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 Hb(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=Bb.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(Lb(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 $o(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:Hb(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 Fb(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 $o(h,r,n,i);const f=Wt(h).comment;if(!Array.isArray(f)||!f.length)throw Oe("社区评论楼层无效");return $o(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 zb(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 $o(h,n,i,s)}throw{code:"COMMENT_UNAVAILABLE",message:"评论不存在或不可访问"}}const xh=3e4;function jb(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,xh*(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 Vb(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,D;const N=O=>{if(n||e.operationContext.signal.aborted)throw oe("RUNTIME_DESTROYED","小程序已关闭");if(r!==O)throw oe("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")};function v(){if(d)throw oe("BINDING_CHANGED","关联帖子已更换,请重新打开小程序")}function I(O){throw Le(O)&&O.code==="BINDING_CHANGED"&&(H(),v()),O}function H(){if(!d){d=!0,l=void 0,y?.abort(),c.abort(),J.setEnabled(!1);try{e.emit({changed:["binding"]})}catch{}}}function Y(O){return v(),u&&(u.revision!==O.revision||u.postId!==O.postId)&&(H(),v()),u??=O,u}async function R(O,W){N(O),v();const $=await e.account.getCurrentUserId(W);if(N(O),v(),i!==void 0&&i!==$)throw Q(),oe("AUTHORIZATION_CONTEXT_CHANGED","账号已变化,请重试");if(!$)throw oe("UNAUTHORIZED","请先登录小黑盒");if(a&&s!==$)throw oe("AUTHORIZATION_CONTEXT_CHANGED","账号已变化,请重试");i=$}async function x(O,W,$,Z=r){const ie=Ue(Ue(e.operationContext,c.signal),$);await R(Z,ie);const me=await W(ie);await R(Z,ie);const De=await Ri({network:e.network,operationContext:ie,subject:"关联帖子",assertUsable:()=>{N(Z),v()},...e.requestGate?{gate:{capability:"post",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},O,me);return await R(Z,ie),De}async function U(O,W,$){try{const Z=await x(rA,async me=>{if(!e.authorizationContext)throw oe("METHOD_FORBIDDEN","宿主不支持关联帖子授权上下文");const De=await e.authorizationContext.get(me);if(!De.token||De.expiresAt<=Date.now())throw oe("UNAUTHORIZED","小程序运行上下文已过期");return{runtime_auth_context_token:De.token,action:O,payload:JSON.stringify(W)}},$),ie=at(Z,O,"关联帖子");if(!Le(ie)||!Le(ie.data))throw oe("INVALID_RESPONSE","关联帖子响应缺少数据");return ie.data}catch(Z){return I(Z)}}function G(){if(_)return _;const O=r,W=f,$=U("get",{},e.operationContext.signal).then(Z=>{if(N(O),W!==f)return _=void 0,G();Y(vb(Z.binding));const ie=Ub(Z);if(Z.commentsRevision!==void 0&&(typeof Z.commentsRevision!="string"||!/^\d+$/.test(Z.commentsRevision)))throw oe("INVALID_RESPONSE","评论版本无效");const me=[];if(l){const{stats:De,viewer:Pe,...E}=l,{stats:m,viewer:M,...S}=ie;JSON.stringify(E)!==JSON.stringify(S)&&me.push("content"),JSON.stringify([De,Pe])!==JSON.stringify([m,M])&&me.push("stats")}return Z.commentsRevision!==void 0&&p!==void 0&&p!==Z.commentsRevision&&me.push("comments"),l=ie,h=Date.now(),Z.commentsRevision!==void 0&&(p=Z.commentsRevision),me.length&&J.invalidate({changed:me}),ie}).catch(Z=>{if(r===O&&f===W&&Le(Z)&&["POST_UNAVAILABLE","POST_NOT_BOUND","POST_TYPE_UNSUPPORTED"].includes(String(Z.code))){const ie=l!==void 0;l=void 0,ie&&J.invalidate({changed:["content","stats"]})}throw Z}).finally(()=>{_===$&&(_=void 0)});return _=$,$}function V(O){N(O),v(),f++,h=0}async function te(O,W){const $=r;try{await W()}catch(Z){if(n||e.operationContext.signal.aborted||r!==$||Z instanceof Error&&Z.name==="AbortError")return;try{e.onBackgroundError?.(O,Z)}catch{}}}function z(O,W){return V(O),J.invalidate({changed:["comments"]}),U("comments.changed",{bindingRevision:u.revision},W)}async function j(O){const W=r;await R(W,Ue(e.operationContext,O));const $=l&&Date.now()-h<xh?l:await Se(G,O).catch(Z=>{throw v(),Z});return N(W),v(),$}async function ee(O,W,$,Z,ie){const De=await x(O==="post.setLiked"?tA:eA,()=>({targetId:$,enabled:W.liked===!0||W.favorited===!0}),Z,ie);(!Le(De)||De.status!=="ok")&&at(De,O,"帖子互动")}const J=jb({emit:e.emit,refresh:G});function Q(){r++,l&&J.invalidate({changed:["content","stats"]}),l=void 0,h=0,p=void 0,_=void 0,y?.abort(),c.abort(),c=new AbortController,i=void 0,J.reset()}const P=Ci(e.account,O=>{s=O,a=!0,i!==void 0&&O!==i&&Q()}),w=e.authorization.onEvent(Q),B={};for(const O of[...ga,...ai])B[O]=async(W,$)=>{if(N(r),O==="post.watch"){if(W!==void 0)throw oe("INVALID_ARGUMENT","变化订阅无需参数");if(t.size>=32)throw oe("RATE_LIMITED_BY_RUNTIME","帖子订阅过多");const m=r;if(v(),await j($.signal),N(m),v(),$.signal.aborted)return;if(t.size>=32)throw oe("RATE_LIMITED_BY_RUNTIME","帖子订阅过多");return new Promise((M,S)=>{const C=()=>{$.signal.removeEventListener("abort",C),t.delete(C),J.setEnabled(t.size>0&&!d),M()};t.add(C),$.signal.addEventListener("abort",C,{once:!0}),J.setEnabled(!0);try{$.postProgress({watching:!0})}catch(K){$.signal.removeEventListener("abort",C),t.delete(C),J.setEnabled(t.size>0&&!d),S(K)}})}if(ai.includes(O)&&!$.trustedUserGesture)throw oe("USER_GESTURE_REQUIRED","请通过用户操作发起帖子互动");const ie=Gb(O,W);v();const me=r;if(O==="post.get")return JSON.parse(JSON.stringify(await j($.signal)));let De;O==="post.comments.openEditor"&&(y?.abort(),y=De=new AbortController,D=$.requestId,$={...$,...Ue($,De.signal)});const Pe=await j($.signal),E=i;if(N(me),v(),O==="post.comments.delete"||O==="post.comments.setLiked"){const m=await x(O==="post.comments.delete"?JT:XT,()=>({body:{comment_id:ie.commentId,...O==="post.comments.setLiked"?{support_type:ie.liked?1:2}:{}}}),$.signal,me);(!Le(m)||m.status!=="ok")&&at(m,O,"帖子评论"),te("post.comments.changed",()=>z(me,c.signal));return}if(O.startsWith("post.comments.")){const{cursor:m,limit:M}=ie,S=$.signal;if(O==="post.comments.list"){const C=String(ie.rootCommentId??""),K=C?1:Number(m||1),ce=C?{root_comment_id:C,lastval:m||"",limit:M??20}:{link_id:Pe.id,page:K,limit:M??20,owner_only:0,hide_cy:1,sort_filter:0,index:2},pe=await x(C?ZT:_d,()=>ce,S,me);return Fb(pe,at(pe,O,"帖子评论"),C,E,Pe.author.id,K)}if(O==="post.comments.openEditor"){const C=e.presentation?.openPostCommentEditor;if(!C||!De)throw oe("METHOD_FORBIDDEN","当前宿主不支持评论编辑器");let K;if(ie.replyToCommentId){const ye=String(ie.replyToCommentId),he=String(ie.rootCommentId??ye),Me=await x(_d,()=>({link_id:Pe.id,root_comment_id:he,comment_id:ye,page:1,limit:20,owner_only:0,hide_cy:1,sort_filter:0,index:2}),S,me);K=zb(Me,at(Me,O,"帖子评论"),ye,he,E,Pe.author.id)}const ce=Ue(Ue(e.operationContext,c.signal),De.signal),pe=Ue(ce,S);await R(me,pe),await Se(()=>C({postId:Pe.id,...K?{reply:K}:{},lifetimeSignal:ce.signal,onSubmitted(){y!==De||ce.signal.aborted||r!==me||te("post.comments.changed",async()=>{await R(me,ce),!ce.signal.aborted&&await z(me,ce.signal)})}},pe),pe.signal),await R(me,pe);return}}await ee(O,ie,Pe.id,$.signal,me),V(me),te("post.get",G)};return{handlers:B,setVisible:J.setVisible,dismissEditor(O){O===D&&(D=void 0,y?.abort())},dispose(){if(!n){n=!0;for(const O of[...t])O();r++,c.abort(),J.dispose(),P(),w()}}}}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 Gb(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 Yb=new Set(["stdio","attachments","notifications"]),Uh=new Set(["windows-x64","macos-arm64"]),qb=new Set(["unsigned","valid","invalid","unknown"]),Qb=/^[a-f0-9]{64}$/,Wb=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),$b=new Set(lf),Kb=new Set([...lf,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Bh=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 Zb(e){const t=async(n,i,s,a)=>{const c=Xb(n);try{Gt(i.signal);const u=await s(c,{...e.operationContext,signal:i.signal});return Gt(i.signal),u}catch(u){throw Zo(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=>Jb(d,i)).catch(d=>{throw Zo(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)=>Ko(await e.companion.getInfo(s,a),s)),[_a]:(n,i)=>t(n,i,async(s,a)=>Rd(await e.companion.getPreparationStatus(s,a))),[Ta]:(n,i)=>t(n,i,async(s,a)=>{const c=Rd(await e.companion.getPreparationStatus(s,a));return Gt(i.signal),c.state!=="ready"&&c.state!=="preparing"&&await r("prepare",s,i),Gt(i.signal),Ko(await e.companion.prepare(s,{...a,onProgress:u=>i.postProgress(Fh(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)=>Cd(await e.companion.getActiveSession(s,a),s)),[ba]:(n,i)=>t(n,i,async(s,a)=>{const c=Cd(await e.companion.getActiveSession(s,a),s);return Gt(i.signal),c||(await r("launch",s,i),Gt(i.signal),zh(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 Xb(e){if(!_e(e)||typeof e.alias!="string"||!cE.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(!_e(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](ey(e,n),{...r.operationContext,signal:t.signal});return Gt(t.signal),i}catch(i){throw Zo(i)}}function xt(){throw T("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Hh(e){return!Array.isArray(e)||e.some(t=>!Yb.has(t))?xt():Object.freeze([...new Set(e)])}function Ko(e,t){return!_e(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Uh.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:Hh(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function Jb(e,t){const r=Ko(e,t);return!_e(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!Qb.test(e.sha256)?xt():Object.freeze({...r,sha256:e.sha256})}function Fh(e){return _e(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 Rd(e){return _e(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Fh(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&_e(e.error)&&typeof e.error.code=="string"&&$b.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:Bh[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):xt():xt()}function zh(e,t){return!_e(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Uh.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:Hh(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Cd(e,t){return e===void 0?void 0:zh(e,t)}function ey(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!nf(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 ty(e){return!_e(e)||!Wb.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 ry(e){if(!_e(e)||!_e(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||!nf(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:ty(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 Zo(e,t){return _e(e)&&typeof e.code=="string"&&Kb.has(e.code)?T(e.code,Bh[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&_e(e)&&e.name==="AbortError"?T(t,"Companion 准备已取消"):T("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Ld=5e3,Pd=1e4;function lt(e){throw{code:"INVALID_PARAMS",message:e}}function tu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jh(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&lt(`${r} 不支持字段: ${n.join(", ")}`)}function ny(e){if(e===void 0)return{intensity:"light",delay:0};if(!tu(e))return lt("device.vibrate 参数必须是对象");jh(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>Ld?lt(`device.vibrate delay 必须是 0-${Ld} 的整数毫秒`):{intensity:r,delay:n}}function iy(e){return tu(e)?(jh(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?lt("device.setClipboard text 必须是非空字符串"):e.text.length>Pd?lt(`device.setClipboard text 不能超过 ${Pd} 字符`):{text:e.text}):lt("device.setClipboard 参数必须是对象")}function sy(e){return typeof e=="string"?e.trim()?e:lt("device.executeProtocol 协议字符串不能为空"):tu(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?lt("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(Xo(e,new Set),e):lt("device.executeProtocol 参数必须是协议字符串或协议对象")}function Xo(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)Xo(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))Xo(i,t);t.delete(r)}function ay(e){return{[qs]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),await Se(()=>e.presentation.vibrate(ny(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(iy(t),n),n.signal)},[Ws]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal);const i=sy(t);await Se(()=>e.protocol.invoke(i,n),n.signal)}}}const vd=1e3,oy=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function cy(e){const t=r=>Ue(e.operationContext,r.signal);return{files:{[vs]:async(r,n)=>{ao(n);const i=oo(e.picker),s=uy(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=dy(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=ly(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(kd(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 xd(async()=>{const s=await e.registry.resolveFile(i.target).stat(t(n));if(!_e(s)||s.kind!=="file")throw Bd()})},[fi]:async(r,n)=>{const i=yt(r),s=Ud(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 Ud(s)},[Hs]:async(r,n)=>{const i=yt(r,["content"]),s=e.registry.resolveFile(i.target);tn(s.mode),await Tt(()=>s.write(hy(i.content),t(n)))},[mi]:async(r,n)=>{const i=yt(r),s=await Tt(()=>e.registry.resolveFile(i.target).stat(t(n)));return my(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(kd(i),t(n)))},[Ei]:async(r,n)=>{const i=yt(r,["recursive"]);if(_e(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 xd(async()=>{const s=await e.registry.resolveDirectory(i.target).stat(t(n));if(!_e(s)||s.kind!=="directory")throw Bd()})},[js]:async(r,n)=>{const i=yt(r,["limit"]),s=fy(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 uy(e){if(e===void 0)return{mode:"read",multiple:!1};_e(e)||Mt("pickFiles 参数必须是对象"),Fa(e,["mode","accept","multiple"]);const t=Vh(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 dy(e){return e===void 0?{mode:"read"}:(_e(e)||Mt("pickDirectory 参数必须是对象"),Fa(e,["mode"]),{mode:Vh(e.mode,"read")})}function ly(e){return _e(e)||Mt("saveFile 参数必须是对象"),Fa(e,["suggestedName"]),{suggestedName:Di(e.suggestedName,"suggestedName")}}function yt(e,t=[]){return(!_e(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Mt("文件操作参数必须包含 target"),Fa(e,["target",...t]),e}function kd(e){return{recursive:e.recursive===void 0?!1:ua(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:ua(e.exclusive,"exclusive")}}function Vh(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 fy(e){if(e===void 0)return vd;if((!Number.isSafeInteger(e)||e<=0)&&Mt("limit 必须是正整数"),e>vd)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 xd(e){try{return await e(),!0}catch(t){if(oy.has(Vc(t)??""))return!1;throw gn(t)}}async function Tt(e){try{return await e()}catch(t){throw gn(t)}}function hy(e){return e instanceof Uint8Array||Mt("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Mt("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Ud(e){if(!(e instanceof Uint8Array))throw T("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Bd(){return T("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function my(e){if(!_e(e)||e.kind!=="file"||!Ey(e.size))throw T("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!gy(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 Ey(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function gy(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Mt(e){throw T("INVALID_PARAMS",e)}const Hd=16*1024,Fd=200;function py(e){const t=Cf(e.runtimePermissions);function r(n,i){e.capabilities&&wf(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 Jo(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 zd(()=>a.handle.list({limit:Fd},s),s);return e.registry.describeListedEntries(a,c,Fd).map(({name:u,kind:d})=>({name:u,kind:d}))},async read(n,i={}){const s=i.maxBytes??Hd;if(!Number.isSafeInteger(s)||s<1||s>Hd)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 zd(()=>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 Jo(e){if(e.signal.aborted)throw T("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")}async function zd(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 Jo(t),n}catch(n){throw t.signal.aborted&&Jo(t),gn(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const _y=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 Ty(e){if(e instanceof Je)return T("REQUEST_UNSUPPORTED",co.REQUEST_UNSUPPORTED);const t=Gh(e);return t!==void 0&&_y.has(t)?T(t,co[t]??"媒体操作失败"):T("MEDIA_PREPARE_FAILED",co.MEDIA_PREPARE_FAILED)}function Gh(e){try{if(!_e(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Ay=["source","mediaType","maxCount"],cs=Object.freeze({source:"album",mediaType:"all",maxCount:1});function Iy(e){if(e===void 0)return cs;if(!z0(e))throw T("INVALID_PARAMS",yy(e));return by(e)}function by(e){return Object.freeze({source:e.source??cs.source,mediaType:e.mediaType??cs.mediaType,maxCount:e.maxCount??cs.maxCount})}function yy(e){if(!_e(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!Ay.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 Ny=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),wy={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class Dy{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=Sy(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const s=n.map((a,c)=>My(a,i[c]));if(!j0(s))throw Qt("Host 返回的媒体结果未通过协议校验");for(const a of n)this.committed.add(a);return s}catch(s){throw this.registry.revokeFiles(i.map(Ry).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=Gh(n);throw i!==void 0&&Ny.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 jd(e,t){if(e.signal.aborted)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw T("REQUEST_CANCELLED","media.pick 已取消")}function Sy(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 返回了稀疏媒体结果");Oy(e[n],n)}return e}function Oy(e,t){if(!_e(e))throw Qt(`第 ${t+1} 项不是对象`);if(!rf({...e,file:wy}))throw Qt(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!_e(e.file))throw Qt(`第 ${t+1} 项缺少文件句柄`)}function My(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 Ry(e){return"handleId"in e.ref?e.ref.handleId:void 0}function Qt(e){return T("MEDIA_PREPARE_FAILED",e)}function Cy(e){const t=e.media?new Dy(e.registry,e.media,e.operationContext):void 0;return{handlers:{[gi]:async(n,i)=>{const s=Iy(n);Py(i);const a=e.media,c=t;if(!a||typeof a.pick!="function"||!c)throw Ot(gi);const u=Ue(e.operationContext,i.signal);jd(e.operationContext,i.signal);const d=await Ly(a,s,u,e.operationContext,i.signal);jd(e.operationContext,i.signal);try{return c.commit(d,s)}catch(l){throw c.releaseBatch(d,u),l}}},dispose(){t?.dispose()}}}async function Ly(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 已取消"):Ty(s)}}function Py(e){if(!e.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Yi=4294967296;function vy(e){const t=new ky;return t.write(e),t.finish()}class ky{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=xy(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 xy(e){const t=new Uint8Array(Uy(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 Uy(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 Yh(e){ec(e);const t=vy(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 ec(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)ec(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");ec(a,t+1,r)}r.delete(e)}const By=["pc","console","mobile"],Hy=["game","wiki"];function da(e){throw{code:"INVALID_PARAMS",message:e}}function Fy(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 Vd(e,t,r){return typeof e!="string"||!t.includes(e)?da(r):e}function zy(e){const t={target:"game_detail",appId:_r(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Vd(e.gameType,By,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Vd(e.page,Hy,"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 jy(e){return{target:"user_detail",userId:_r(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Vy(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 Gy(e){const t={target:"mini_program",miniProgramId:_r(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Yy(e){return Fy(e)?e.target==="game_detail"?zy(e):e.target==="user_detail"?jy(e):e.target==="post_detail"?Vy(e):e.target==="mini_program"?Gy(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 Qy(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Wy(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 $y(e){const t=e;return t.target==="game_detail"?qy(t):t.target==="user_detail"?Qy(t):Wy(t)}const Ky="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",Zy="data-hb-sdk-fullscreen-exit",Xy=3e3,Jy=2e3,Gd="var(--white-70a,rgba(255,255,255,.7))",Yd="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function eN(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(Zy,""),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 ${Gd}`,`box-shadow:${Yd}`,"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=Ky,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 p(D=Jy){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")},D)}function _(){f(),s=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Gd,t.style.boxShadow=Yd,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),p()}async function y(){if(!(a||c)){if(!s){_();return}c=!0,clearTimeout(u),f();try{await e()}catch{}finally{c=!1,a||_()}}}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"})),p(Xy),{dispose(){a=!0,clearTimeout(u),f(),t.removeEventListener("click",y),window.removeEventListener("resize",h),t.remove()}}}const qh=1e4;function Qh(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 qd(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 tN(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(_){if(!_.hideCapsule){u();return}c??=eN(()=>p.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",u,{once:!0});function l(_,y){if(n===_){if(n=void 0,clearTimeout(_.timer),e.operationContext.signal.removeEventListener("abort",h),"error"in y)_.controller.abort();else if(i={options:_.options,result:y.result},s=_.options,d(_.options),e.onApplied?.(_.options),y.result.supported&&!uo(a,_.options)){a={..._.options};try{e.onDisplayChange?.({orientation:a.mode,fullscreen:a.hideCapsule,source:_.source})}catch{}}for(const D of _.subscribers)D.dispose(),"error"in y?D.reject(y.error):D.resolve(y.result);_.subscribers.clear()}}function h(){n&&l(n,{error:Un()})}function f(_,y){return new Promise((D,N)=>{const v=()=>{_.subscribers.delete(I),I.dispose(),N(Un()),_.subscribers.size===0&&l(_,{error:Un()})},I={resolve:D,reject:N,dispose:()=>y?.removeEventListener("abort",v)};_.subscribers.add(I),y?.addEventListener("abort",v,{once:!0}),y?.aborted&&v()})}const p={async runDisplayRequest(_,y,D){const N=++t,v=Qh(y,e.operationContext.signal);try{return await v.run(async()=>{if(await D(v.signal),v.signal.aborted)throw Un();if(qd(_),N<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=N,p.apply(_,v.signal)})}finally{v.dispose()}},async apply(_,y,D="api"){if(ve(e.operationContext.signal),y?.aborted)throw Un();const N=qd(_),v=n?.options??s,I={mode:N.orientation??v.mode,hideCapsule:N.fullscreen??v.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 Y={options:I,source:D,controller:new AbortController,subscribers:new Set};n=Y;const R=f(Y,y);return e.operationContext.signal.addEventListener("abort",h,{once:!0}),y||(Y.timer=setTimeout(()=>{l(Y,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},qh)),Se(()=>H.call(e.presentation,I,{...e.operationContext,signal:Y.controller.signal}),Y.controller.signal).then(x=>l(Y,{result:x??{supported:!0}}),x=>l(Y,{error:x})),R},dispose(){e.operationContext.signal.removeEventListener("abort",u),u()}};return p}function Wh(e){throw{code:"INVALID_PARAMS",message:e}}function Qd(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Wh(`${t} 不支持参数`)}function rN(e){return{[$s]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),Qd(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),Qd(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=Yy(t);if(i.target==="mini_program"){let s;if(i.extra!==void 0)try{s=Yh(i.extra)}catch{Wh("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const a=e.resetDisplay;if(a){const c=Qh(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($y(i),n),n.signal)}}}const Wd={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function nN(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,...p}=e,_=await n.upload(c,{...p,expectedBytes:u.size,...e.format==="multipart"?{fileName:e.fileName??c.name}:{}},{...s,onProgress:h});if(l=!0,!Number.isSafeInteger(_.uploadedBytes)||_.uploadedBytes<d||_.uploadedBytes>u.size)throw T("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(_.status>=200&&_.status<300&&_.uploadedBytes!==u.size)throw T("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:_.uploadedBytes,total:u.size,lengthComputable:!0}),_}catch(f){l=!0;const p=Vc(f);throw p&&Wd[p]?T(p,Wd[p]):s.signal.aborted?T("UPLOAD_CANCELLED","上传已取消"):p?.startsWith("FILE_")||p?.startsWith("DIRECTORY_")?gn(f):T("UPLOAD_NETWORK_FAILED","上传网络失败")}}const ru="withCredentials",iN=new Set(["url","method","params","data","headers","timeout",ru]),sN=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",ru]),aN=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),$d=3e4,tc=2*1024*1024,oN=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,$h=/[\u0000-\u0008\u000A-\u001F\u007F]/,cN=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,uN="network.request 不支持 multipart/form-data,请使用专用上传能力";function dN(e){const t=lN(e.runtimePermissions);t.allowDevelopmentHttp=e.allowDevelopmentHttp===!0,t.firstParty=e.firstParty===!0,t.networkPolicy=t.firstParty?void 0:Sf(e.networkPolicy);const r=wN(e.allowedHttpOrigins);return{[Ps]:async(n,i)=>{const s=hN(n,{permission:t,allowedHttpOrigins:r}),a=await nN(s,i,e),{uploadedBytes:c,...u}=a;return Zd(u)},[Ls]:async(n,i)=>{const s=mN(n,{permission:t,allowedHttpOrigins:r});return Bf(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=fN(n,{permission:t,allowedHttpOrigins:r});let c;try{c=await Se(()=>e.network.request(a,s),s.signal)}catch(u){throw SN(u)?u:ON(u,"REQUEST_UNSUPPORTED")?Ce("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):Ce("REQUEST_FAILED","网络请求失败")}return Zd(c)}}}function lN(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 fN(e,t){const r=Tn(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(u=>!iN.has(u));if(n.length>0)throw Ce("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Kh(r,"network.request");const i=nu(r,t,"network.request"),s=gN(r.method),a=r.data;a!==void 0&&TN(a),IN(i.headers,a);const c=bN(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 hN(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 Ce("INVALID_PARAMS","network.upload 包含不支持的字段");const i=nu(r,t,"network.upload");if(!t.permission.firstParty&&i.official)throw Ce("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw Ce("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!kr(r.from))throw Ce("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Ce("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw Ce("INVALID_PARAMS","format 必须是 raw 或 multipart");const s=r.method??(r.format==="raw"?"PUT":"POST");if(s!=="POST"&&(r.format!=="raw"||s!=="PUT"))throw Ce("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 Ce("INVALID_PARAMS","raw 不接受 multipart 字段");return a}if(Object.keys(i.headers??{}).some(l=>l.toLowerCase()==="content-type"))throw Ce("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const c=Kd(r.fieldName),u=r.fields===void 0?void 0:Tn(r.fields,"fields 必须是字符串字典");for(const[l,h]of Object.entries(u??{}))if(Kd(l),typeof h!="string"||l===c)throw Ce("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw Ce("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||$h.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw Ce("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>tc)throw Ce("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...a,fieldName:c,...u===void 0?{}:{fields:{...u}},...r.fileName===void 0?{}:{fileName:Yc(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function Kd(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw Ce("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function mN(e,t){const r=Tn(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(u=>!sN.has(u));if(n.length>0)throw Ce("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Kh(r,"network.download");const i=nu(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw Ce("INVALID_PARAMS","network.download timeout 必须是有限正数");Jp(i.headers);const s=kr(r.to),a=ef(r.to);if(!s&&!a)throw Ce("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(s&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw Ce("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let c;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw Ce("INVALID_PARAMS","suggestedName 必须是字符串");c=Yc(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw Ce("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw Ce("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 nu(e,t,r){const n=EN(e.url,t.allowedHttpOrigins,r,t.permission.allowDevelopmentHttp===!0),i=Yg(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 Ce("PERMISSION_DENIED",`${r} 目标不在平台批准的域名清单中`);if(i&&!t.permission.useOfficialDomain)throw Ce("PERMISSION_DENIED","当前小程序暂不支持访问官方域名")}if(Gg(n.pathname,i))throw Ce("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:pN(e.headers,r),timeout:_N(e.timeout,r)}}function EN(e,t,r="network.request",n=!1){if(typeof e!="string"||!e.trim())throw Ce("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let i;try{i=new URL(e)}catch{throw Ce("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw Ce("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(i.username||i.password)throw Ce("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(i.protocol==="http:"&&!n&&!t.has(i.origin))throw Ce("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return i}function gN(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw Ce("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!aN.has(t))throw Ce("INVALID_PARAMS","network.request method 不合法");return t}function pN(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||!oN.test(a)||typeof s!="string"||$h.test(s))throw Ce("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(qg(a))throw Ce("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[a]=s}return n}function Kh(e,t){const r=e[ru];if(r!==void 0&&typeof r!="boolean")throw Ce("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function _N(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw Ce("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>$d)throw Ce("INVALID_PARAMS",`${t} timeout 不能超过 ${$d}ms`);return e}}function TN(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw Ce("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(AN(e)>tc)throw Ce("INVALID_PARAMS",`network.request data 不能超过 ${tc} 字节`)}function AN(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 Ce("INVALID_PARAMS","network.request data 必须可序列化")}}function IN(e,t){const r=Zh(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 Ce("INVALID_PARAMS",uN)}function bN(e,t,r){if(t===void 0)return;const n=Zh(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)||NN(t))?"form":yN(t)?"json":void 0}function Zh(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function yN(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function NN(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function wN(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&&DN(n.hostname)&&t.add(n.origin)}catch{}return t}function DN(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 Zd(e){return Object.keys(e.headers).some(Xd)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Xd(t)))}:e}function Xd(e){const t=e.trim().toLowerCase();return cN.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function SN(e){return e instanceof Error&&e.name==="AbortError"}function ON(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 Ce("INVALID_PARAMS",t);return e}function lo(e){return new TextEncoder().encode(e).length}function Ce(e,t){return{code:e,message:t}}function MN(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function RN(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 CN(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=RN(i);s?r.has(s)||(r.add(s),n.push(s)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function LN(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 Xh(e,t){if(e==null)return{};if(!MN(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=CN(e.topicIds),n=LN(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 PN(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function vN(e){try{if(PN(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 rc(e,t){return typeof e!="string"||!e.trim()?nt(t):e}function kN(e,t){const r=rc(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?nt(t):r}catch{return nt(t)}}function xN(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Jh(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 UN(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&&!xN(r))return nt("share.showShareMenu channel 不合法");const n=em(e.extra,"share.showShareMenu");return{title:rc(e.title,"share.showShareMenu title 必须是非空字符串"),description:rc(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Jh(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:kN(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function em(e,t){if(e!==void 0)try{return Yh(e)}catch{return nt(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function tm(e,t){return e.invalidMessage&&await Se(()=>vN(t.environment),t.operationContext.signal)?nt(e.invalidMessage):e.post}function Jd(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function BN(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Jd(t.windowWidth,0),height:Jd(t.windowHeight,0)}}function nc(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?nt(t):r}function el(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?nt(t):r}function HN(e){return Pi(e)?{left:nc(e.left,"share.screenshot rect.left 必须是非负数字"),top:nc(e.top,"share.screenshot rect.top 必须是非负数字"),width:el(e.width,"share.screenshot rect.width 必须是正数"),height:el(e.height,"share.screenshot rect.height 必须是正数")}:nt("share.screenshot rect 必须是对象")}function tl(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?BN(t):HN(r.rect),...r.delay===void 0?{}:{delay:nc(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function FN(e,t){ve(t.operationContext.signal);const r=UN(e,t);let n=Xh(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await tm(n,t);return Se(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function zN(e,t){if(ve(t.operationContext.signal),e!==void 0&&!Pi(e))return nt("share.copyLink 参数必须是对象");const r=em(e?.extra,"share.copyLink"),n=Jh(t,"share.copyLink",r);return await Se(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function rl(e,t,r,n=!1){ve(t.operationContext.signal);const i=Xh(Pi(e)?e.post:void 0,{method:"share.screenshot"}),s=await tm(i,t),a=t.identity.get()?.miniProgramId.trim()||void 0,c=jN(),{watermarkTheme:u,...d}=r;let l=!1,h,f,p;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 D=await t.prepareLongScreenshot(r.rect,t.operationContext.signal);h=D.restore,d.rect=D.rect}f=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,u),p={status:"fulfilled",value:await Se(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:s,...a?{sourceMiniProgramId:a}:{}},t.operationContext),t.operationContext.signal)}}catch(y){p={status:"rejected",error:y}}finally{try{f?.()}finally{h?.()}}const _=l?await VN(t.presentation,c,t.operationContext.signal):void 0;if(p.status==="rejected")throw p.error;if(_)throw _;return p.value}function jN(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function VN(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 GN(e){let t=Promise.resolve();const r=async(n,i)=>{const s=Ue(e.operationContext,i.signal,i.requestId),a=tl(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(()=>rl(n,{...e,operationContext:s},a,!0));return t=c.then(()=>{},()=>{}),c};return{[Os]:r,[ws]:(n,i)=>zN(n,{...e,operationContext:Ue(e.operationContext,i.signal,i.requestId)}),[Ds]:(n,i)=>FN(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=tl(n,e.presentation),c=t.then(()=>rl(n,{...e,operationContext:s},a));return t=c.then(()=>{},()=>{}),Se(()=>c,s.signal)}}}const nl=new WeakMap,qi=new Map;function rm(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return lg(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Nf(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function nm(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=nl.get(t);h||(h=new Map,nl.set(t,h));const f=h.get(l)??Promise.resolve(),p=async()=>(ve(u.signal,{preserveReason:!0}),d(l)),_=f.catch(()=>{}).then(()=>e.lock?e.lock(l,p):p());h.set(l,_);try{return await _}finally{h.get(l)===_&&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(_=>_.key.startsWith(h)&&_.value!=="").map(_=>_.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 p;try{p=f?JSON.parse(f):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(p)||p.length>Lu||p.some(_=>typeof _!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(_)))throw new Error("本地数据索引异常");return[...new Set(p)]},a=async(u,d)=>{if(e.diagnostics){const f=Wr(u,"");return(await e.diagnostics.listRaw(d)).filter(p=>p.key.startsWith(f)&&p.value!=="").map(p=>({...p,key:p.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 p=await Promise.all(h.slice(f,f+16).map(async _=>{const y=await e.storage.getRaw(Wr(u,_),d);return y!==void 0&&y!==""?{area:"local",key:_,value:y}:void 0}));for(const _ of p)_&&l.push(_)}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>=Lu)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const p=[...new Set([...f,u])];await e.storage.setRaw(Ui(h),JSON.stringify(p),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 p=(await Promise.allSettled(l.slice(h,h+16).map(_=>e.storage.setRaw(Wr(d,_),"",u)))).find(_=>_.status==="rejected");if(p)throw p.reason}ve(u.signal,{preserveReason:!0}),await e.storage.setRaw(Ui(d),"[]",u)})}}}function im(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 YN=128,qN=/^[A-Za-z0-9_-]+$/;function QN(e){const t=e.scopedStorage??nm({storage:e.storage,resolveScope:()=>rm({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[ci]:async n=>{ve(e.operationContext.signal);const i=il(n,ci,e.storageLimits?.maxKeyLength),s=await Se(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:sl(s)}},[ui]:async n=>{ve(e.operationContext.signal);const i=sm(n,"storage.setStorage 参数必须是对象"),s=il(i,ui,e.storageLimits?.maxKeyLength),a=WN(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:sl(s),serializedValue:s,bytes:am(s)}}).sort((i,s)=>i.key.localeCompare(s.key)))}}}function il(e,t,r=YN){const i=sm(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 WN(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&&am(r)>t)throw Ur("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function sl(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function sm(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Ur("INVALID_PARAMS",t);return e}function am(e){return new TextEncoder().encode(e).length}function Ur(e,t){return{code:e,message:t}}const al=120;function mr(e){throw{code:"INVALID_PARAMS",message:e}}function iu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function om(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&mr(`${r} 不支持字段: ${n.join(", ")}`)}function $N(e){if(!iu(e))return mr("ui.showToast 参数必须是对象");if(om(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>al)return mr(`ui.showToast message 不能超过 ${al} 字符`);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 KN(e){return e===void 0?{dismissible:!1}:iu(e)?(om(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?mr("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):mr("ui.showLoading 参数必须是对象")}function ZN(e){e!==void 0&&(!iu(e)||Object.keys(e).length)&&mr("ui.hideLoading 不支持参数")}function XN(e){return{[Vs]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),await Se(()=>e.presentation.showToast($N(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(KN(t),n),n.signal)},[Ys]:async(t,r)=>{const n=Ue(e.operationContext,r.signal,r.requestId);ve(n.signal),ZN(t),await Se(()=>e.presentation.hideLoading(n),n.signal)}}}const JN={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return Ve(e,"当前用户首页资料接口响应异常")}},ew=3e4;function tw(e,t,r={}){const n=r.ttlMs??ew,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,JN,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):nw(f)?f:T("REQUEST_FAILED","user home_v2 请求失败")}return rw(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 p=a,_=d().then(y=>(a===p&&(c={userId:h,value:y,expiresAt:Date.now()+n}),y)).finally(()=>{u?.promise===_&&(u=void 0)});return u={userId:h,generation:p,promise:_},_}return{get:l,clear(){a+=1,c=void 0,u=void 0}}}function rw(e,t){if(!_e(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(!_e(e.result))throw T("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function nw(e){return _e(e)&&typeof e.code=="string"&&typeof e.message=="string"}const iw={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,"关注用户接口响应异常")}},sw={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 接口响应异常")}},aw={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 接口响应异常")}},ow={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 游戏库接口响应异常")}},cw={auth:"optional",channel:"api",id:"heybox.workshop.open.steam.accounts.post",method:"POST",path:"/workshop/open/steam/accounts",bodyEncoding:"form",failurePresentation:"none",query(e){return e.query},body(e){return e.body??{}},parse(e,t){return Wc(e,"Steam 账号列表接口响应异常")}};function uw(e,t=Ho){const r=s_({version:"2",validate:fw}),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 dw(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 lw(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 fw(e){if(!_e(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(ol(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw on();for(const t of e.gameList){if(!_e(t)||!ic(t.appid)||!ic(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw on();for(const r of["image","portraitImage","icon"])hw(t,r);for(const r of["playtimeForever","playtime2Weeks"])ol(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 ic(e){return typeof e=="number"&&Number.isFinite(e)}function ol(e,t){if(e[t]!==void 0&&!ic(e[t]))throw on()}function hw(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw on()}function on(){return T("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const cm=20,mw=3e4,Ew=100,gw=128,um=0,dm="weeks",pw=100,_w=new Set(["weeks","all","achieved"]);function Tw(){return{nickname:"",avatar:""}}function Aw(e){const t=tw(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??zf(),i=uw(n,r?e.steamGameListTtlMs:0);let s;const a=new Map;let c=Promise.resolve();function u(Q,P){const w=JSON.stringify([Q,P]);return(!s||s.key!==w)&&(s={key:w,scope:n.createScope(P,n.createScope(Q))}),s.scope}function d(){const Q=s;s=void 0,Q&&n.invalidateScope(Q.scope).catch(()=>{}),a.clear()}const l=Fo({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??Kf))}),h=Fo({ttlMs:mw}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let p,_,y=0,D=!1;const N=e.account.onChange(()=>{y+=1,t.clear(),l.invalidate(),h.invalidate(),d()}),v=e.authorization.onEvent((Q,P)=>{Q==="user_info_authorization_change"&&Object.values(P).some(w=>w==="denied")&&(y+=1,t.clear(),l.invalidate(),d(),c=c.then(async()=>{if(D)return;const w=await e.account.getCurrentUserId(e.operationContext);typeof w=="string"&&w.trim()&&await n.invalidateScope(u(H(),w.trim()))}).catch(()=>{}))});function I(){if(D||e.operationContext.signal.aborted)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function H(){const Q=e.identity.get()?.miniProgramId?.trim();if(!Q)throw T("INVALID_STATE","用户能力缺少 canonical 小程序身份");return Q}async function Y(){I(),await c,I();let Q;try{Q=await e.account.getCurrentUserId(e.operationContext)}catch(P){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Bn(P)?P:T("REQUEST_FAILED","读取小黑盒账号失败")}return typeof Q=="string"&&Q.trim()?Q.trim():void 0}async function R(Q,P){const w=await Y();if(y!==P||w!==Q)throw T("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function x(Q,P,w=e.operationContext.signal){try{return await Pa(e.network,Q,P,{...e.operationContext,signal:w,credentials:"heybox-session",...f?{gate:f}:{}})}catch(B){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):B instanceof Je?T("REQUEST_UNSUPPORTED",B.message):B instanceof Mi?T("INVALID_RESPONSE","用户接口响应不合法"):B instanceof pn?T("REQUEST_FAILED","用户请求失败"):B instanceof Oi?r&&(B.status===403||B.status===429)?T("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:B.status,...B.retryAfterMs===void 0?{}:{retryAfterMs:B.retryAfterMs}}):T("REQUEST_FAILED",B.message):Bn(B)?B:T("REQUEST_FAILED","用户请求失败")}}async function U(Q,P){if(!e.authorizationContext)return{mini_program_id:Q};let w;try{w=await Se(()=>e.authorizationContext.get({...e.operationContext,signal:P}),P)}catch(B){if(Bn(B))throw B;const O=T("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(O,"cause",{configurable:!0,value:B}),O}if(!w.token?.trim())throw T("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:Q,runtime_auth_context_token:w.token}}async function G(){I();const Q=H(),P=y,w=await Y();if(!w){if(y!==P)throw T("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const B=await U(Q,e.operationContext.signal);await R(w,P);const O=await x(sw,B);if(await R(w,P),H()!==Q)throw T("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return dl(ul(O))}function V(Q,P){if(!Q)return Promise.reject(T("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(P?.aborted)return Promise.reject(T("REQUEST_CANCELLED","关注操作已取消"));if(p)return Promise.reject(T("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(T("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const w=te(P).finally(()=>{p===w&&(p=void 0)});return p=w,w}async function te(Q){I();const P=H(),w=new AbortController;_=w;const B=()=>w.abort();e.operationContext.signal.addEventListener("abort",B,{once:!0}),Q?.addEventListener("abort",B,{once:!0});let O=()=>{},W=!1;try{try{await Se(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:w.signal}),w.signal)}catch(C){throw Bn(C)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(C.code)?T("FOLLOW_CANCELLED","已取消小黑盒登录"):C}I();const $=y;O=e.account.onChange(()=>{W=!0,B()});const Z=await Se(Y,w.signal);if(!Z)throw T("FOLLOW_CANCELLED","未完成小黑盒登录");const ie=async()=>{if(await Se(()=>R(Z,$),w.signal),I(),H()!==P)throw T("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await ie();const me=await U(P,w.signal);await ie();const De=Cw(),Pe=await Se(()=>x(aw,{...me,request_id:De},w.signal),w.signal);await ie();const E=ul(Pe);if(E.status!=="notFollowing")return dl(E);if(E.rateLimited)throw T("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const m=await Se(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:P,signal:w.signal}),w.signal);if(await ie(),m!=="confirmed")throw T("FOLLOW_CANCELLED","已取消关注作者");const M=E.authorId,S=await Se(()=>x(iw,{body:{following_id:M}},w.signal),w.signal);if(await ie(),S.status!=="ok"){const C=["login","relogin","lack_token"].includes(S.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw T(C,typeof S.msg=="string"&&S.msg.trim()?S.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch($){throw I(),W?T("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):Q?.aborted?T("REQUEST_CANCELLED","关注操作已取消"):Bn($)?$:T("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{O(),e.operationContext.signal.removeEventListener("abort",B),Q?.removeEventListener("abort",B),_===w&&(_=void 0)}}async function z(){H();const Q=y,P=await Y();if(!P)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[w,B,O]=await Promise.all([e.authorization.getOrCreateLocalIdentity(P),ee(P).catch(()=>Tw()),e.steamAccount?j(P).catch(()=>{}):Promise.resolve(void 0)]);await R(P,Q);const W=e.authorization.getAuthorization(),$=O??(w.steamId?[Mw(w.steamId)]:void 0);return{isHeyboxAppLoggedIn:!0,authorization:W,userInfo:{app_user_id:w.appUserId,profile:B,...w.steamId?{steam_id:w.steamId}:{},...$?{steam_accounts:$}:{}}}}async function j(Q){return h.read(Q,async()=>{const P=await x(cw,{body:{}});if(!Array.isArray(P.list))throw T("INVALID_RESPONSE","Steam 账号列表 list 必须是数组");return P.list.map(Ow)})}function ee(Q){return l.read(Q,()=>x(Xf,void 0).then(P=>{const w=sc(P,"账号基础信息");if(w.display_username!==void 0&&typeof w.display_username!="string")throw T("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(w.display_avatar!==void 0&&typeof w.display_avatar!="string")throw T("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:w.display_username??"",avatar:w.display_avatar??""}}))}async function J(Q){const P=Iw(Q),w=H(),B=y,O=await Y();if(!O)return d(),{isLogin:!1,isBound:!1,data:null};const[W,$]=await Promise.all([t.get(O),e.steamAccount?j(O).catch(()=>{}):Promise.resolve(void 0)]);await R(O,B);const Z=lm(W.steam_id_info),ie=dw({...P,steamId:void 0},Z),me=$?.find(Ne=>Ne.is_main)?.steam_id??ie;if(!P.steamId&&($?.length===0||!$&&Object.keys(Z).length===0))return await n.invalidateScope(u(w,O)).catch(()=>{}),await R(O,B),a.delete(JSON.stringify([w,O])),{isLogin:!0,isBound:!1,data:null};const De=JSON.stringify([w,O]),Pe=u(w,O),E=P.steamId??me,m=fm(Z.personal_infomation_open??Z.personal_information_open),M=JSON.stringify([E??null,m??null]),S=a.get(De);S&&S.identity!==M&&(await n.invalidateScope(Pe).catch(()=>{}),await R(O,B));const C={identity:M,scope:n.createScope(M,Pe)};a.set(De,C);const K=P.steamId??me,ce=K?{...P,steamId:K}:P,pe=K?i.persistent:i.unresolved,ye=n.createScope(K??"unresolved",C.scope),he=async()=>{if(await R(O,B),H()!==w||a.get(De)?.identity!==M)throw T("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},Me=await pe.read({scope:ye,key:lw({miniProgramId:w,userId:O,effectiveSteamId:K,personalInformationOpen:m,query:ce}),signal:e.operationContext.signal,load:async Ne=>{const He=await x(ow,{userId:O,...ce,personalInformationOpen:m},Ne);return await he(),Dw(sc(He,"Steam 游戏库"),ce)}}).catch(async Ne=>{throw await he(),Ne});return await he(),{isLogin:!0,isBound:!0,data:Me}}return{getFollowStatus:G,requestFollowAuthor:V,getInfo:z,getSteamGameList:J,async invalidateSteamGameListCache(){const Q=H(),P=y,w=await Y();if(!w)return;const B=u(Q,w);await Promise.all([i.persistent.invalidateScope(B),i.unresolved.invalidateScope(B)]),h.invalidate(),t.clear(),a.delete(JSON.stringify([Q,w])),await R(w,P)},dispose(){D||(D=!0,_?.abort(),h.dispose(),y+=1,N(),v(),t.clear(),l.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function Iw(e){if(e==null)return{limit:cm,offset:um,sort:dm,includeHidden:!1};if(!_e(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:bw(e.limit),offset:yw(e.offset),sort:Nw(e.sort),includeHidden:ww(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>gw)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,pw))}return r}function bw(e){if(e===void 0)return cm;if(!Number.isInteger(e)||Number(e)<1)throw Er("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),Ew)}function yw(e){if(e===void 0)return um;if(!Number.isInteger(e)||Number(e)<0)throw Er("user.getSteamGameList offset 必须是非负整数");return Number(e)}function Nw(e){if(e===void 0)return dm;if(typeof e!="string"||!_w.has(e))throw Er("user.getSteamGameList sort 不支持");return e}function ww(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Er("user.getSteamGameList includeHidden 必须是 boolean");return e}function Dw(e,t){if(!Array.isArray(e.game_list))throw T("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(Sw).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=fm(e.is_me);return a!==void 0&&(s.isMe=a),s}function Sw(e){const t=lm(e),r=la(t.appid),n=la(t.steam_appid)??r,i=su(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),cl(s,"playtimeForever",t.playtime_forever),cl(s,"playtime2Weeks",t.playtime_2weeks);const a=Rw(t.external_tags??t.tags);return a.length&&(s.tags=a),s}function sc(e,t){if(!_e(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(!_e(e.result))throw T("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function lm(e){return _e(e)?e:{}}function Ow(e){if(typeof e.steam_id!="string"||!e.steam_id.trim()||typeof e.nickname!="string"||typeof e.avatar_url!="string"||typeof e.is_main!="boolean")throw T("INVALID_RESPONSE","Steam 账号响应不合法");return{steam_id:e.steam_id.trim(),nickname:e.nickname,avatar_url:e.avatar_url,is_main:e.is_main}}function Mw(e){return{steam_id:e,nickname:"",avatar_url:"",is_main:!0}}function su(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function Rw(e){return Array.isArray(e)?e.map(su).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 fm(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=su(r);n&&Object.assign(e,{[t]:n})}function cl(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 _e(e)&&typeof e.code=="string"&&typeof e.message=="string"}function ul(e){const t=sc(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 dl(e){return e.status}function Cw(){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 Lw(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 Pw(){return T("USER_DATA_PERMISSION_STATE_INVALID","本地用户数据许可状态异常,已停止访问")}function ll(e){return T("USER_DATA_PERMISSION_SAVE_FAILED","本次运行已停止访问,设置未保存,请重试",e===void 0?void 0:{reason:e instanceof Error?e.message:String(e)})}function vw(e){const t=e.managedResources??Rr,r=typeof e.storage.withLock=="function"||typeof navigator<"u"&&!!navigator.locks,n=e.hash??Hc,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 im(l(I),H);throw T("REQUEST_UNSUPPORTED","当前宿主不支持跨实例保存资料许可")}function d(I){return Tg({miniProgramId:e.resolveMiniProgramId(),userId:I,environment:e.resolveEnvironment()})}function l(I){return hg(_g(d(I)))}function h(I,H){return e.purposeOf?n(cf(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 p(I,H){let Y;try{Y=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 R=Y===void 0||Y===""?void 0:pg(Y);if(Y!==void 0&&Y!==""&&R===void 0)throw Pw();return R??{schema_version:1,records:{}}}async function _(I,H,Y){if(c(),Y.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");await e.storage.setRaw(l(I),JSON.stringify(H),Y)}function y(I){return I?.revision??0}function D(I,H,Y){const R=new Set(Y.declared??[]),x=new Set(t);for(const V of Object.keys(H.records))dr(V)&&x.add(V);for(const V of i.keys())V.startsWith(`${I}\0`)&&x.add(V.slice(I.length+1));const G=[...x].sort((V,te)=>{const z=Rr.indexOf(V),j=Rr.indexOf(te);return(z<0?Number.MAX_SAFE_INTEGER:z)-(j<0?Number.MAX_SAFE_INTEGER:j)}).map(V=>{const te=H.records[V],z=y(te),j=Y.egressTier===void 0?void 0:h(V,Y.egressTier),ee=i.get(f(I,V)),J=ee!==void 0&&ee.revision===z&&(j===void 0||ee.consentFingerprint===j);return{resource:V,name:xc(V)?.name??V,purposeText:e.purposeOf?.(V)??"",scopeFingerprint:j??"",declared:R.has(V),available:R.has(V),decision:te?.decision??"ask",revision:z,...te?.decision==="allow"&&te.consentFingerprint?{consentFingerprint:te.consentFingerprint}:{},sessionAllowed:J,allowed:!s.has(f(I,V))&&R.has(V)&&te?.decision!=="deny"&&(J||r&&te?.decision==="allow"&&j!==void 0&&te.consentFingerprint===j)}});return Object.freeze({schema_version:1,canPersist:r,resources:Object.freeze(G),...Y.egressTier===void 0?{}:{egressTier:Y.egressTier}})}function N(I,H,Y,R){const x=H.records[Y],U=f(I,Y);if(s.has(U))return{status:"denied",reason:"tightening"};if(x?.decision==="deny")return{status:"denied",reason:"deny"};const G=h(Y,R);if(r&&x?.decision==="allow"&&x.consentFingerprint===G)return{status:"allowed",source:"persistent"};const V=i.get(U);return V&&V.revision===y(x)&&V.consentFingerprint===G?{status:"allowed",source:"session"}:{status:"ask"}}function v(I){if(typeof I!="string"||!Rr.includes(I))throw T("INVALID_PARAMS","用户数据资源标识不合法")}return{canPersist:r,async read(I,H,Y={}){c();const R=await p(I,H);return D(I,R,Y)},async evaluate(I,H,Y){c(),v(H.resource);const R=await p(I,Y);return N(I,R,H.resource,H.egressTier)},async decide(I,H){c(),v(I.resource);const Y=async()=>{c();const R=await p(I.userId,H);if(c(),H.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");const x=R.records[I.resource],U=y(x);if(I.expectedRevision!==void 0&&U!==I.expectedRevision)throw T("AUTHORIZATION_CONTEXT_CHANGED","资料许可已变化,请重新确认");const G=f(I.userId,I.resource),V=h(I.resource,I.egressTier);if(I.expectedFingerprint!==void 0&&I.expectedFingerprint!==V)throw T("AUTHORIZATION_CONTEXT_CHANGED","资料披露范围已变化,请重新确认");if(I.scope==="session"){if(I.decision!=="allow")throw T("INVALID_PARAMS","本次许可只支持允许");return i.set(G,Object.freeze({revision:U,consentFingerprint:V})),D(I.userId,R,{egressTier:I.egressTier})}const te=U+1,z=I.decision==="allow"?{decision:"allow",revision:te,consentFingerprint:V}:{decision:I.decision,revision:te},j={schema_version:1,records:{...R.records,[I.resource]:z}};I.decision!=="allow"&&(s.add(G),i.delete(G));try{await _(I.userId,j,H)}catch(ee){throw ll(ee)}return s.delete(G),i.delete(G),D(I.userId,j,{egressTier:I.egressTier})};return I.scope==="session"?Y():u(I.userId,Y)},async revokeSession(I,H){c(),I.resource!==void 0&&v(I.resource);for(const R of[...i.keys()])R.startsWith(`${I.userId}\0`)&&(I.resource===void 0||R===f(I.userId,I.resource))&&i.delete(R);const Y=await p(I.userId,H);return D(I.userId,Y,{})},async reset(I,H){return c(),u(I.userId,async()=>{c();const Y=await p(I.userId,H);if(c(),H.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");const R=new Set(t);for(const G of Object.keys(Y.records))R.add(G);for(const G of i.keys())G.startsWith(`${I.userId}\0`)&&R.add(G.slice(I.userId.length+1));for(const G of R)s.add(f(I.userId,G));for(const G of[...i.keys()])G.startsWith(`${I.userId}\0`)&&i.delete(G);const x={...Y.records};for(const G of R)x[G]={decision:"ask",revision:(x[G]?.revision??0)+1};const U={schema_version:1,records:x};try{await _(I.userId,U,H)}catch(G){throw ll(G)}for(const G of R)s.delete(f(I.userId,G));return D(I.userId,U,{})})},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 kw={...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}}}},xw={...za,id:"heybox.user_miniprogram.runtime.user_game_data.sync.post",path:"/user_miniprogram/runtime/user_game_data/sync",body:ja},fl={...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}}},Uw={...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 Bw(e){const t=sh(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),p=at(f,"user.data","游戏资料");if(!Le(p))throw oe("INVALID_RESPONSE","游戏资料响应无效");return i(h),p}const c=d=>{const l=xc(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 p=await a(kw,{...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(p.resource!==d.resource||p.operation!==d.operation||p.schema_version!==f.version||p.disclosure_revision!==h.disclosureRevision)throw oe("INVALID_RESPONSE","游戏资料合同不匹配");if(p.status==="ready"){if(!ug(f.schema,p.data))throw oe("INVALID_RESPONSE","游戏资料正文不匹配公开 schema");return{status:"ready",data:p.data,meta:{},schemaVersion:f.version}}if(p.status==="empty"&&(p.reason==="no_data"||p.reason==="not_ready")&&typeof p.message=="string")return{status:"empty",reason:p.reason,message:p.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 p=await s(f,l),_=new AbortController,y=()=>_.abort();l.signal.addEventListener("abort",y,{once:!0}),l.signal.aborted&&y();let D=!1;const N=setTimeout(()=>{D=!0,y()},5*6e4),v={...l,signal:_.signal},I={...h,gameId:f.game,resource:d.resource};let H;try{const Y=await t.run(I,v,async()=>{const x=await t.get(I,v);if(x)return H=x,{id:x,status:await a(fl,{...await s(f,v),task_id:x},v)};const U=await a(xw,p,v);if(typeof U.task_id!="string"||!U.task_id||U.task_id.length>128)throw oe("INVALID_RESPONSE","同步任务缺失");return await t.set(I,U.task_id,v),{id:U.task_id,status:U}});let R=Y.status;for(H=Y.id;;){if(i(v),R.state==="succeeded")return await t.remove(I,H,v),{status:"succeeded"};if(R.state==="failed")throw await t.remove(I,H,v),oe(typeof R.error_code=="string"?R.error_code:"SYNC_FAILED","存档同步失败");if(R.state!=="syncing"&&R.state!=="uploading")throw oe("INVALID_RESPONSE","同步状态无效");if(await Hw(v.signal),R=await a(fl,{...await s(f,v),task_id:H},v),R.task_id!==H)throw oe("INVALID_RESPONSE","同步任务不匹配")}}catch(Y){throw H&&Le(Y)&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED"].includes(String(Y.code))&&await t.remove(I,H,v),D?oe("REQUEST_TIMEOUT","等待同步超时,后台任务可能仍在执行"):Y}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 p=async y=>{await h(y);const D=await a(Uw,{...await s(f,y),save_id:d.saveId,file_id:d.fileId},y);if(!Le(D.file)||D.file.file_id!==d.fileId)throw oe("INVALID_RESPONSE","文件标识不匹配");return await h(y),D},_=await r.download(await p(l),async y=>{await p(y)},l);try{return i(l),await h(l),i(l),n.add(_),_}catch(y){throw await u(_),y}}}}function Hw(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"],Fw=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"])}),hl=10*6e4,zw=256;function jw(e){const t=e.now??Date.now,r=e.random??Math.random,n=e.createId??qw,i=Gw(e.sampleRate),s=new Map,a=new Map,c=new Map;let u=!1,d=0,l=0,h=0,f=0;const p={get emitted(){return d},get failed(){return l},get skipped(){return h},get deduplicated(){return f}};function _(R){return`${R}${n()}`}function y(){const R=t();for(const[x,U]of s)R-U.createdAt<=hl||(s.delete(x),a.get(U.key)===x&&a.delete(U.key));for(const[x,U]of c){if(R-U<=hl&&c.size<=zw)break;c.delete(x)}}function D(R){const x=s.get(R);x!==void 0&&(s.delete(R),a.get(x.key)===R&&a.delete(x.key))}function N(R){D(R),c.delete(R),c.set(R,t())}function v(R,x){const U=Fw[R],G={};for(const[V,te]of Object.entries(x))te===void 0||!U.has(V)||(G[V]=te);return Object.freeze(G)}function I(R){const x={event_id:_("evt_"),miniProgramId:rn(()=>e.resolveMiniProgramId())??"unknown",environment:Vw(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:Yw(e)};return R.resource!==void 0&&(x.resource=R.resource),R.callId!==void 0&&(x.call_id=R.callId),R.flowId!==void 0&&(x.flow_id=R.flowId),x}function H(R,x){if(u){h+=1;return}try{if(e.sink===void 0){h+=1;return}e.sink.postEvent(R,v(R,x)),d+=1}catch{l+=1}}function Y(R,x){if(R===void 0)return!1;const U=s.get(R);return U===void 0?!1:x==="start"&&U.started||x==="shown"&&U.shown||x==="decided"&&U.decided?!0:(x==="start"&&(U.started=!0),x==="shown"&&(U.shown=!0),x==="decided"&&(U.decided=!0),!1)}return{diagnostics:p,createCallId(){return _("call_")},beginFlow(R){y();const x=`${R.resource??""}\0${R.actionType}`,U=a.get(x);if(U!==void 0&&s.has(U))return U;const G=_("flow_");return s.set(G,{key:x,createdAt:t(),started:!1,shown:!1,decided:!1}),a.set(x,G),G},permissionShow(R){if(Y(R.flowId,"shown")){f+=1;return}H("user_game_data_permission_show",{...I(R),entry:R.entry,reason:R.reason})},permissionResult(R){if(Y(R.flowId,"decided")){f+=1;return}H("user_game_data_permission_result",{...I(R),choice:R.choice,apply_result:R.applyResult})},permissionManage(R){H("user_game_data_permission_manage",{...I(R),operation:R.operation,apply_result:R.applyResult,...R.succeededCount===void 0?{}:{succeeded_count:R.succeededCount},...R.failedCount===void 0?{}:{failed_count:R.failedCount}})},action(R){if(R.stage==="start"&&Y(R.flowId,"start")){f+=1;return}if(R.stage==="finish"){if(R.flowId!==void 0&&c.has(R.flowId)){f+=1;return}R.flowId!==void 0&&N(R.flowId)}H("user_game_data_action",{...I(R),stage:R.stage,action_type:R.actionType,...R.outcome===void 0?{}:{outcome:R.outcome},...R.durationMs===void 0?{}:{duration_ms:Math.max(0,Math.round(R.durationMs))}})},access(R){if(i<=0){h+=1;return}if(i<1&&r()>=i){h+=1;return}H("user_game_data_access_result",{...I(R),api:R.api,trigger:R.trigger,status:R.status,duration_ms:Math.max(0,Math.round(R.durationMs)),sample_rate:i,...R.errorCode===void 0?{}:{error_code:R.errorCode},...R.failureStage===void 0?{}:{failure_stage:R.failureStage},...R.cacheHit===void 0?{}:{cache_hit:R.cacheHit},...R.overviewStatusCounts===void 0?{}:{overview_status_counts:R.overviewStatusCounts}})},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear())}}}function Vw(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 Gw(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 Yw(e){try{return e.resolveEgressTier()==="upload"?"upload":"no_network"}catch{return"no_network"}}function qw(){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 Qw(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,p=m=>H()[m]?.purpose??"",_=m=>{const M=xc(m);if(!M)throw T("REQUEST_UNSUPPORTED","未开放的资料资源");return M},y=m=>cf(m,_(m).disclosureRevision,jt(e.runtimePermissions),p(m)),D=()=>vw({storage:e.storage,resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,revisionOf:m=>_(m).disclosureRevision,purposeOf:p,...e.hash?{hash:e.hash}:{}});let N=D();const v=jw({resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,resolveEgressTier:()=>jt(e.runtimePermissions),...e.telemetry??{}}),I=Bw({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),M=m.valid?m.permissions.user_game_data:void 0;return M?.status==="enabled"?pi(M.config.resources):{}}function Y(m){if(t||e.operationContext.signal.aborted)throw T("RUNTIME_DESTROYED","小程序已关闭");if(m?.signal.aborted)throw T("REQUEST_CANCELLED","资料请求已取消")}function R(m){for(const[M,S]of u)S!==void 0&&(m===void 0||S===m)&&M.abort()}function x(m){for(const[M,S]of d)(m===void 0||M===m)&&(S.abort(),d.delete(M))}function U(){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 G=Ci(e.account,m=>{if(c&&a===m)return;const M=a;c=!0,a=m,M!==void 0&&(U(),N.dispose(),N=D())}),V=()=>U();e.operationContext.signal.addEventListener("abort",V,{once:!0});async function te(m,M){Y(m);const S=new AbortController,C=()=>S.abort();u.set(S,void 0),m.signal.addEventListener("abort",C,{once:!0}),m.signal.aborted&&C();const K={...e.operationContext,...m,signal:S.signal};try{const ce=await M(K);return Y(K),ce}catch(ce){throw _e(ce)&&ce.name==="AbortError"?T("REQUEST_CANCELLED","资料操作已取消"):ce}finally{m.signal.removeEventListener("abort",C),u.delete(S)}}function z(m){const M=_(m);if(!p(M.key))throw T("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明这项游戏资料",{resource:M.key});return M}async function j(m){Y(m);const M=await e.account.getCurrentUserId(m);if(Y(m),!c)c=!0,a=M;else if(a!==M){const S=a;a=M,S!==void 0&&(U(),N.dispose(),N=D(),Y(m))}return M}function ee(m,M){const S={login_required:"请先登录小黑盒",permission_required:"尚未允许读取这项资料",permission_denied:"已拒绝读取这项资料",source_not_linked:"请先在小黑盒关联对应游戏账号",source_login_required:"请先在小黑盒更新游戏来源登录"},C=M==="login_required"?{type:"user_login",label:"登录并授权"}:M==="permission_required"?{type:"permission",label:"允许读取"}:M==="permission_denied"&&e.presentation?.openDataPermissions?{type:"manage",label:"管理数据权限"}:void 0;return{status:"blocked",resource:m,reason:M,message:S[M],...C?{interaction:C}:{}}}async function J(m,M){z(m);const S=await j(M);if(!S)return ee(m,"login_required");const C=await N.evaluate(S,{resource:m,egressTier:jt(e.runtimePermissions)},M);return Y(M),C.status==="allowed"?{userId:S}:ee(m,C.status==="denied"?"permission_denied":"permission_required")}async function Q(m,M,S,C,K){if(Y(K),s!==S||await j(K)!==M||y(m)!==C)throw T("AUTHORIZATION_CONTEXT_CHANGED","账号或资料范围已变化");return J(m,K)}function P(m,M){if(!_e(m)||typeof m.resource!="string")throw T("INVALID_PARAMS","资料请求无效");if(!dr(m.resource))throw T("REQUEST_UNSUPPORTED","当前宿主尚未开放该资料资源");const S=M==="query"?["resource","operation","schemaVersion","cursor","limit"]:["resource","saveId","fileId"];if(Object.keys(m).some(K=>!S.includes(K)))throw T("INVALID_PARAMS","资料请求包含未知参数");const C=z(m.resource);if(M==="query"){if(m.operation!=="get"&&m.operation!=="list")throw T("INVALID_PARAMS","资料查询操作无效");const K=C.queries[m.operation];if(!K)throw T("REQUEST_UNSUPPORTED","资源不支持该查询");if(m.schemaVersion!==K.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(!K.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>(K.page?.maxSize??100)))throw T("INVALID_PARAMS","分页数量无效")}else if(!C.operations.includes(M))throw T("REQUEST_UNSUPPORTED","资源不支持该操作");if(M==="file"&&(typeof m.saveId!="string"||!m.saveId||typeof m.fileId!="string"||!m.fileId))throw T("INVALID_PARAMS","资料文件标识无效");return M==="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 w(m,M,S,C){const K=f(),ce=s,pe=y(M.resource);for(const ye of u.keys())ye.signal===S.signal&&u.set(ye,M.resource);try{const ye=await J(M.resource,S);if("status"in ye)return v.access({resource:M.resource,api:m,trigger:"initial",status:"blocked",durationMs:f()-K}),ye;let he;try{he=await C()}catch(Ne){const He=_e(Ne)?Ne.code:void 0;if(He==="USER_DATA_SOURCE_NOT_LINKED"||He==="USER_DATA_SOURCE_LOGIN_REQUIRED")return v.access({resource:M.resource,api:m,trigger:"initial",status:"blocked",durationMs:f()-K}),ee(M.resource,He==="USER_DATA_SOURCE_NOT_LINKED"?"source_not_linked":"source_login_required");throw Ne}const Me=await Q(M.resource,ye.userId,ce,pe,S);return"status"in Me?(v.access({resource:M.resource,api:m,trigger:"initial",status:"blocked",durationMs:f()-K}),Me):(v.access({resource:M.resource,api:m,trigger:"initial",status:_e(he)&&he.status==="empty"?"empty":m===Qn?"succeeded":"ready",durationMs:f()-K}),he)}catch(ye){throw v.access({resource:M.resource,api:m,trigger:"initial",status:"error",durationMs:f()-K,errorCode:_e(ye)?String(ye.code):"REQUEST_FAILED"}),ye}}async function B(m){const M=await j(m);if(!M)throw T("UNAUTHORIZED","请先登录小黑盒");const S=await N.read(M,m,{declared:Object.keys(H()),egressTier:jt(e.runtimePermissions)});return p(ar)?S:{...S,resources:S.resources.filter(({resource:C})=>C!==ar)}}async function O(m){const M=await m;return r?M:{...M,resources:M.resources.filter(({resource:S})=>S!==ar)}}async function W(m,M,S){const C=z(m),K=S!==void 0;if(K&&a!==S)return{status:"cancelled"};let ce=S??await j(M);if(!ce&&!K&&(await e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:M.signal}),ce=await j(M)),!ce)return{status:"cancelled"};let pe=await N.evaluate(ce,{resource:m,egressTier:jt(e.runtimePermissions)},M);if(pe.status==="allowed")return{status:"allowed"};if(pe.status==="denied"){if(K)return{status:"denied"};if(e.presentation?.openDataPermissions){const Me=s,Ne=y(m),He=await e.presentation.openDataPermissions({resource:m,miniProgramName:e.miniProgramPresentation?.name,signal:M.signal});if(!("status"in await Q(m,ce,Me,Ne,M)))return{status:"allowed"};if(!He)return{status:"cancelled"}}return pe=await N.evaluate(ce,{resource:m,egressTier:jt(e.runtimePermissions)},M),{status:pe.status==="allowed"?"allowed":"denied"}}if(!e.presentation?.confirmDataPermission)throw T("REQUEST_UNSUPPORTED","当前宿主不支持资料许可弹窗");if(m!==ar)return Z(C,ce,M);const ye=i;if(ye?.userId===ce)return Se(()=>ye.result,M.signal);const he={userId:ce,result:Z(C,ce,M)};i=he;try{return await he.result}finally{i===he&&(i=void 0)}}async function $(){if(!(!e.presentation?.confirmDataPermission||!p(ar)))try{const m=await j(e.operationContext);if(!m||n.has(m))return;await te(e.operationContext,M=>W(ar,M,m))}catch{}}async function Z(m,M,S){const C=m.key;x(C);const K=new AbortController;d.set(C,K);const ce=()=>K.abort();S.signal.addEventListener("abort",ce,{once:!0}),S.signal.aborted&&ce();const pe={...S,signal:K.signal},ye=s,he=y(C),Me=N,Ne=v.beginFlow({resource:C,actionType:"permission"});let He="error";try{const Fe=(await Me.read(M,pe,{egressTier:jt(e.runtimePermissions)})).resources.find(ct=>ct.resource===C);v.action({resource:C,flowId:Ne,stage:"start",actionType:"permission"}),v.permissionShow({resource:C,flowId:Ne,entry:"other",reason:Fe?.decision==="allow"?"scope_changed":"first"});const ze=await Se(()=>e.presentation.confirmDataPermission({miniProgramName:e.miniProgramPresentation?.name,resource:C,scopeText:`此黑盒账号关联的${m.name}${m.operations.includes("sync")?`。${J0}`:""}`,purposeText:p(C),egress:jt(e.runtimePermissions),canPersist:Me.canPersist,...C===ar&&{onShown:()=>{!K.signal.aborted&&s===ye&&n.add(M)}},signal:K.signal}),K.signal);if(Y(pe),s!==ye||await j(pe)!==M||y(C)!==he)throw T("AUTHORIZATION_CONTEXT_CHANGED","资料许可范围已变化");return ze.decision==="cancelled"?(He="cancelled",v.permissionResult({resource:C,flowId:Ne,choice:"cancel",applyResult:"cancelled"}),{status:"cancelled"}):(await Me.decide({userId:M,resource:C,decision:ze.decision==="deny"?"deny":"allow",scope:ze.decision==="session"?"session":"persistent",egressTier:jt(e.runtimePermissions),expectedRevision:Fe?.revision??0,expectedFingerprint:Fe?.scopeFingerprint},pe),ze.decision==="deny"&&R(C),He=ze.decision==="deny"?"unresolved":"resolved",v.permissionResult({resource:C,flowId:Ne,choice:ze.decision,applyResult:"applied"}),{status:ze.decision==="deny"?"denied":"allowed"})}catch($e){throw He=pe.signal.aborted?"cancelled":"error",v.permissionResult({resource:C,flowId:Ne,choice:"cancel",applyResult:pe.signal.aborted?"cancelled":"error"}),$e}finally{v.action({resource:C,flowId:Ne,stage:"finish",actionType:"permission",outcome:He}),S.signal.removeEventListener("abort",ce),d.get(C)===K&&d.delete(C)}}async function ie(m,M,S,C,K,ce){M==="allow"?z(m):_(m);const pe=await j(C);if(!pe)throw T("UNAUTHORIZED","请先登录小黑盒");try{await N.decide({userId:pe,resource:m,decision:M,scope:S,expectedRevision:K,expectedFingerprint:ce,egressTier:jt(e.runtimePermissions)},C)}catch(ye){throw _e(ye)&&ye.code==="USER_DATA_PERMISSION_SAVE_FAILED"&&R(m),ye}return x(m),M!=="allow"&&R(m),B(C)}async function me(m,M,S){try{const C=await S();return v.permissionManage({operation:m,resource:M,applyResult:"applied"}),C}catch(C){throw v.permissionManage({operation:m,resource:M,applyResult:_e(C)&&C.code==="USER_DATA_PERMISSION_SAVE_FAILED"?"save_failed":"error"}),C}}async function De(m,M){x(m),R(m);const S=await j(M);if(!S)throw T("UNAUTHORIZED","请先登录小黑盒");return me("revoke",m,async()=>(await N.revokeSession({userId:S,resource:m},M),B(M)))}function Pe(){let m;const M=S=>te(e.operationContext,async C=>{const K=await j(C);if(!K)throw T("UNAUTHORIZED","请先登录小黑盒");if(m&&(m.userId!==K||m.generation!==s))throw T("AUTHORIZATION_CONTEXT_CHANGED","管理页面所属账号已变化,请重新打开");return m??={userId:K,generation:s},S(C)});return{getSnapshot:()=>M(B),setDecision:S=>M(C=>me("modify",S.resource,()=>ie(S.resource,S.decision,S.scope,C,S.expectedRevision,S.expectedFingerprint))),revokeSession:S=>M(C=>De(S?.resource,C)),resetAll:()=>M(async S=>{x(),R();const C=await j(S);return me("reset",void 0,async()=>(await N.reset({userId:C},S),B(S)))})}}return{handlers:{[Mc]:async(m,M)=>te(M,async S=>{if(m!==void 0&&(!_e(m)||Object.keys(m).some(ce=>ce!=="game")||m.game!==void 0&&typeof m.game!="string"))throw T("INVALID_PARAMS","概览参数无效");if(_e(m)&&typeof m.game=="string"&&!yu(m.game))throw T("REQUEST_UNSUPPORTED","当前宿主尚未开放该游戏");const C=Object.keys(H()),K=_e(m)?m.game:void 0;return af.filter(ce=>K===void 0||ce===K).map(ce=>({game:ce,name:sf[ce],resources:Ji.filter(pe=>pe.game===ce&&C.includes(pe.key)).map(pe=>({resource:pe.key,name:pe.name,status:"not_checked",statusText:"尚未检查"}))})).filter(ce=>ce.resources.length>0)}),[Es]:async(m,M)=>te(M,S=>{const C=P(m,"query");return w(Es,C,S,()=>I.query(C,S))}),[Qn]:async(m,M)=>te(M,async S=>{if(!_e(m)||Object.keys(m).length!==1||typeof m.game!="string"||!yu(m.game))throw T("INVALID_PARAMS","同步需要指定已开放的游戏");const C={game:m.game};if(!Ji.some(he=>he.game===C.game&&he.sync))throw T("REQUEST_UNSUPPORTED","该游戏不支持存档同步");const K=Ji.filter(he=>he.game===C.game&&he.sync&&p(he.key));if(K.length===0)throw T("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明可同步的资料");let ce,pe;for(const he of K){const Me=await J(he.key,S);if(!("status"in Me)){ce=he.key;break}(!pe||pe.reason==="permission_denied")&&(pe=Me)}if(!ce)return pe;const ye={resource:ce};return w(Qn,ye,S,async()=>{const he=await j(S),Me=`${he}\0${ye.resource}`;let Ne=h.get(Me);if(!Ne){const He=new AbortController;u.set(He,ye.resource);const $e={controller:He,waiters:0,settled:!1,promise:Promise.resolve(void 0)};$e.promise=I.sync(ye,{...e.operationContext,signal:He.signal},{userId:he,miniProgramId:e.identity.get()?.miniProgramId??""}).finally(()=>{$e.settled=!0,u.delete(He),h.get(Me)===$e&&h.delete(Me)}),$e.promise.catch(()=>{}),h.set(Me,$e),Ne=$e}Ne.waiters++;try{return await Se(()=>Ne.promise,S.signal)}finally{Ne.waiters--,Ne.waiters===0&&!Ne.settled&&Ne.controller.abort()}})}),[gs]:async(m,M)=>te(M,async S=>{const C=P(m,"file"),K=await j(S),ce=s,pe=y(C.resource),ye=async Me=>{try{const Ne=await Q(C.resource,K,ce,pe,Me);if("status"in Ne)throw T("FILE_ACCESS_REVOKED","文件授权已撤销",{reason:Ne.reason})}catch(Ne){throw _e(Ne)&&["AUTHORIZATION_CONTEXT_CHANGED","USER_DATA_RESOURCE_NOT_DECLARED"].includes(String(Ne.code))?T("FILE_ACCESS_REVOKED","文件授权已失效",{causeCode:Ne.code}):Ne}};let he;try{const Me=await w(gs,C,S,async()=>(he=await I.file(C,S,ye),{handle:he}));if(_e(Me)&&Me.status==="blocked"){const Fe=String(Me.reason);throw T(Fe==="source_not_linked"?"USER_DATA_SOURCE_NOT_LINKED":Fe==="source_login_required"?"USER_DATA_SOURCE_LOGIN_REQUIRED":Fe==="login_required"?"UNAUTHORIZED":"PERMISSION_DENIED",String(Me.message),{reason:Fe})}const Ne=Me.handle,He={...Ne,read:async Fe=>{await ye(Fe);const ze=await Ne.read(Fe);try{return await ye(Fe),ze}catch(ct){throw ze.fill(0),ct}},stat:async Fe=>{await ye(Fe);const ze=await Ne.stat(Fe);return await ye(Fe),ze}},$e=e.fileRegistry.registerFile(He,"download","read");return"handleId"in $e.ref&&l.add($e.ref.handleId),$e}catch(Me){throw he&&await I.releaseFile(he),Me}}),[Rc]:async(m,M)=>{if(!M.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","许可操作需要点击");return te(M,S=>{if(!_e(m)||Object.keys(m).length!==1||typeof m.resource!="string"||!dr(m.resource))throw T("INVALID_PARAMS","许可资源无效");return W(m.resource,S)})},[Cc]:async(m,M)=>te(M,S=>O(B(S))),[Lc]:async(m,M)=>{if(!M.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","修改许可需要点击");if(!_e(m)||typeof m.resource!="string"||!dr(m.resource)||m.decision!=="deny"||m.scope!=="persistent"||Object.keys(m).some(S=>!["resource","decision","scope"].includes(S)))throw T("INVALID_PARAMS","允许许可只能由可信弹窗确认");return te(M,S=>O(ie(m.resource,m.decision,"persistent",S)))},[Pc]:async(m,M)=>{if(!M.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","管理资料许可需要点击");if(!e.presentation?.openDataPermissions)throw T("REQUEST_UNSUPPORTED","宿主未提供资料管理界面");if(m!==void 0&&(!_e(m)||Object.keys(m).some(S=>S!=="resource")||m.resource!==void 0&&(typeof m.resource!="string"||!dr(m.resource))))throw T("INVALID_PARAMS","管理资源无效");return te(M,async S=>(await e.presentation.openDataPermissions({resource:_e(m)?m.resource:void 0,miniProgramName:e.miniProgramPresentation?.name,signal:S.signal}),O(B(S))))},[vc]:async(m,M)=>{if(!M.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","撤销许可需要点击");if(m!==void 0&&(!_e(m)||Object.keys(m).some(S=>S!=="resource")||m.resource!==void 0&&(typeof m.resource!="string"||!dr(m.resource))))throw T("INVALID_PARAMS","撤销资源无效");return te(M,S=>O(De(_e(m)?m.resource:void 0,S)))}},promptPcHardwareOnEntry:$,get permissionBridge(){return Pe()},diagnostics:{telemetry:v.diagnostics},dispose(){t||(t=!0,U(),G(),e.operationContext.signal.removeEventListener("abort",V),N.dispose(),v.dispose())}}}function ml(e){throw{code:"INVALID_PARAMS",message:e}}function Fn(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function hm(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Wi(e,t,r){return Math.min(hm(e,t),r)}async function Ww(e){try{return hm(await e.getNavigationBarHeight(),0)}catch{return 0}}function $w(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 El(e){const t=e.getViewportMetrics(),r=Fn(t.windowWidth,0),n=Fn(t.windowHeight,0),i=await Ww(e);return{pixelRatio:Fn(t.pixelRatio,1),screenWidth:Fn(t.screenWidth,r),screenHeight:Fn(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:$w(t,r,n,i),screenTop:i}}function Kw(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;El(r.presentation).then(f=>{if(n||r.operationContext.signal.aborted||h!==i)return;const p=JSON.stringify(f);p!==s&&(s=p,r.onViewportChange?.(f))}).catch(()=>{})},u=tN({...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),El(r.presentation)),[Rs]:async h=>{if(ve(r.operationContext.signal),typeof h!="object"||h===null||Array.isArray(h))return ml("viewport.setNavigationBarStyle 参数必须是对象");const f=h.foregroundStyle;if(f!=="light"&&f!=="dark")return ml("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 Zw(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 Xw(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=Zw(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 Jw=new Map(pr.map(e=>[e.method,e]));function ho(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function eD(e){const t=Cf(e);return r=>t(r.requirement,r.method)}function tD(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 rD(e){const t=eD(e.runtimePermissions),r=ft(e.runtimePermissions);let n=0;return{async dispatch(i,s,a){const c=e.now??nD,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 已终止");wf(i,e.effectiveCapabilities);const h=Jw.get(i);if(!h)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const f=t(h),p=!f.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,s)===!0,_=!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 D=e.handlers[i];if(!D)throw new Error(`Capability method ${i} 缺少 handler`);const N=async H=>{for(const Y of e.policies??[]){const R=await Y.evaluate({method:i,payload:s,capability:h});if(e.terminalSignal.aborted||H.aborted)throw pl();if(!R.allowed)throw ho(R.code,R.message,R.data)}if(e.terminalSignal.aborted||H.aborted)throw pl()},I=await tD(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),D(s,a)},void 0,a,e.terminalSignal);return e.onTrace&&mo(e.onTrace,gl(l,i,s,d,I),c,u),I}catch(h){throw e.onTrace&&mo(e.onTrace,gl(l,i,s,d,{status:"error",error:h}),c,u),h}}}}function nD(){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 gl(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:iD(i.error)}:{},...sD(t,r,i)}}function iD(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function sD(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"&&ac(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 ac(e){return typeof e=="object"&&e!==null}function pl(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function aD(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=I_(e.requestPolicy);let n;if(e.files)try{n=l_(e.files,t)}catch{}const i=zf({store:n}),s=e.onRequestPolicyReport??(r.debugReport?oD:void 0),a=r.enabled?p_({...r.gateOptions,...s?{onReport:s}:{}}):void 0,c=new Gc(e.files,e.miniProgramDetail),u=cy({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,D,N=()=>{},v=()=>{};try{l=Kw({operationContext:t,presentation:e.hostPresentation,onDisplayChange:ee=>e.eventSink.postEvent("display_change",ee),onViewportChange:ee=>e.eventSink.postEvent("viewport_change",ee)}),f=Aw({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,steamAccount:e.runtimeFeatures?.steamAccount===!0}),N=d.onEvent((ee,J)=>e.eventSink.postEvent(ee,J)),v=e.hostCompanion?.onSessionEvent?.(ee=>{const J=ry(ee);!e.terminalSignal.aborted&&J&&e.eventSink.postEvent(J.type,J.payload)})??(()=>{}),p=CT({roomSocket:e.roomSocket,onRoomEvent:ee=>e.eventSink.postEvent("cloud_rooms_event",ee),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=Qw({...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(ee,J){e.onUserDataTelemetry?.({name:ee,payload:J})}}}}});D=H,_=VT({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=Vb({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:ee=>e.eventSink.postEvent("post_change",ee)});const Y=QN({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});h=Cy({registry:c,media:e.media,operationContext:t});const R=[{name:"post",handlers:y.handlers},{name:"gameSaves",handlers:Object.fromEntries(Object.entries(_.handlers).map(([ee,J])=>[ee,async(Q,P)=>{const w=e.verifiedSdkVersion,B=w?La(w,"0.10.0-0"):void 0;if(B===void 0||B>=0)throw T("REQUEST_UNSUPPORTED","当前 SDK 不支持旧游戏存档入口,请使用 user.games.get(...).saves");return J(Q,P)}]))},{name:"auth",handlers:eT({authorization:d})},{name:"user",handlers:{...Lw({user:f,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...i_({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:GN({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:Y.handlers},{name:"network",handlers:dN({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:Xw(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:XN({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:ay({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:rN({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:ee=>l.applyOrientation({mode:"portrait",hideCapsule:!1},ee)}:{}})},{name:"cloud",handlers:p.handlers},{name:"userGameData",handlers:D.handlers},{name:"companion",handlers:Zb({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:c})}],x=cD(R);let U=!1;const G=()=>{U||(U=!0,e.terminalSignal.removeEventListener("abort",G),l?.dispose(),h?.dispose(),p?.dispose(),_?.dispose(),y?.dispose(),D?.dispose(),N(),v(),f?.dispose(),i.dispose(),d.dispose(),a?.dispose(),c.dispose())};e.terminalSignal.aborted?G():e.terminalSignal.addEventListener("abort",G,{once:!0});const V=new Set(["file.readText","file.readBytes","file.stat"]),te=(ee,J)=>V.has(ee)&&ac(J)&&c.isCompanionAttachmentRef(J.target),z=new Set(["file.readText","file.readBytes","file.stat","file.exists"]),j=(ee,J)=>z.has(ee)&&ac(J)&&c.isUserDataDownloadRef(J.target);return{get permissionBridge(){return H.permissionBridge},modules:R,setPostVisible:y.setVisible,dismissPostEditor:y.dismissEditor,handlers:x,runDisplayRequest:l.runDisplayRequest,allowsCompanionAttachmentAccess:te,allowsGameSaveAccess:_.allowsRead,allowsUserGameDataFileAccess:j,gameSaveDiagnostics:_.diagnostics,applyOrientation:l.applyOrientation,notifyViewportChange:l.notifyChange,promptPcHardwareOnEntry:H.promptPcHardwareOnEntry,...Y.diagnostics?{storageDiagnostics:Y.diagnostics}:{},...e.files?{sandboxDiagnostics:py({registry:c,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},releaseRoomsForDocumentReload:()=>p?.releaseRoomsForDocumentReload(),dispose:G}}catch(I){throw l?.dispose(),h?.dispose(),p?.dispose(),_?.dispose(),y?.dispose(),D?.dispose(),N(),v(),f?.dispose(),i.dispose(),d.dispose(),a?.dispose(),c.dispose(),I}}function oD(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function cD(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 uD="heybox-mini-dev:";function _l(e){try{return dD(new URL(e))}catch{return!1}}function dD(e){return e.protocol===uD}function lD(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||fD(e)}function fD(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 hD=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function mD(e,t){const r=[],n=ED(e.environmentInfo,r),i=us(n?.appVersion,"host.appVersion",r),s=pD(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:gD(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 ED(e,t){if(e!=null){if(mm(e))return e;t.push("environmentInfo")}}function gD(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function pD(e,t){if(e==null)return{name:"unknown",version:null};if(!mm(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=hD.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 mm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const _D="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",TD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",AD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",ID="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function bD(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?AD:_D,f.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const p=e.createElement("div");p.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 _=e.createElement("img");_.src=c?ID:TD,_.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 D=e.createElement("div");D.textContent="小黑盒工坊小程序",D.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;`,p.append(_,y),h.append(f,p),l.append(h,D),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(),_.decode()]),n);const v=l.getBoundingClientRect();return a.style.left=`${r.left+s.scrollX+(r.width-v.width)/2}px`,a.style.width=`${v.width}px`,a.style.height=`${v.height}px`,l.style.width=`${v.width/d}px`,l.style.height=`${v.height/d}px`,l.style.maxWidth="none",await Se(()=>new Promise(I=>{let H=s.requestAnimationFrame(()=>{H=s.requestAnimationFrame(()=>{n.removeEventListener("abort",Y),I()})});const Y=()=>s.cancelAnimationFrame(H);n.addEventListener("abort",Y,{once:!0})}),n),N}catch(v){throw N(),v}}const yD=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"]),ND=new Set(["url","inline","eval","unknown"]),wD=/^\/(?:\:segment(?:\/\:segment)*)?$/,DD=/^[a-f0-9]{64}$/,SD=255,OD=160,MD=256;function RD(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!yD.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>MD||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!ND.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=CD(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>OD||!wD.test(i)))return;const s=r.sanitizedPathnameHash;if(!(s!==void 0&&(typeof s!="string"||!DD.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 CD(e){if(e!==void 0&&!(typeof e!="string"||e.length>SD))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"],LD="0.9.0",PD=Object.freeze(["android","ios","ohos","windows","macos"]),Em="该小程序暂不支持当前平台",vD="PLATFORM_UNSUPPORTED";function kD(e){return typeof e=="string"&&Va.includes(e)}function xD(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 UD(e){const t=e.manifest;if(!jD(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Al(e.sdkVersion)??Al(t.sdkVersion);return FD(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:HD()}const r=gm(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function BD(e){const t=xD(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=UD({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return a.status==="invalid"?sn("platform_declaration_invalid",{invalidReason:a.reason,platform:t}):Tl(t,a)}if(r.effectivePlatforms===void 0)return sn("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=gm(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=zD(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return Tl(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:s})}function Tl(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:Em,...t}}function HD(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:PD,platformsDeclared:!1,policy:"legacy_mobile_default"}}function gm(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(!kD(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 FD(e){if(typeof e!="string"||!e.trim())return!1;const t=La(e.trim(),LD);return t!==void 0&&t>=0}function Al(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function zD(e){return e==="explicit"||e==="legacy_mobile_default"}function jD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function VD(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:GD(i.pathname),sanitizedPathnameHash:Hc(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function GD(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}const YD=1e4,qD=3e4,QD=1e4,Eo=2e3,WD=2,$D="open-with-native-credential-policy",pm="安全提示",_m="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class KD{nonce=Hu();runtimeId=Hu();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??YD,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:(c1(),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=mp(t.runtimePermissions),this.firstParty=t.firstParty===!0,this.networkPolicy=this.firstParty?void 0:Sf(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 Kg(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=r_(t.sdkVersionPolicy),this.allowDevelopmentHttp=t.sdkVersionPolicy?.releaseChannel==="development";const n=mD(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=BD({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw l1(this.platformGateDecision);this.miniProgramDetail=f1(t);const{ports:i,primitiveAvailability:s,effectiveCapabilities:a}=Df({...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),n1(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(s1(c)),this.launchUrl=c,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const d=Of(new URL(c),this.locationBasePath);this.devDocumentDisposer=hp({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=sp(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=aD({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)=>$g(this.iframe,a,c),prepareScreenshot:(a,c,u)=>{const d=this.sdkVersionDecision?.sdkVersion;return!d||(La(d,"0.9.1")??-1)<0?Promise.resolve(()=>{}):bD(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=rD({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:p})=>{const _={type:"capability",phase:"host",runtimeId:this.runtimeId,callId:a,method:c,startedAt:u,timestamp:d,durationMs:l,outcome:h,...f?{errorCode:f}:{},...this.identity,...p?{network:p}:{}};Pt(this.options.onCapabilityTrace,_)}}:{}});this.bridgeServer=new Tp({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 r1(t)?t:Tm(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 ip(t,r,{allowPrivateNetwork:_l(r)||Il(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??o1)({message:_m,title:pm,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(zu(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!_l(r)&&!Il(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{bl(),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(()=>bl())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",ep),this.iframe.setAttribute("referrerpolicy",tp),this.iframe.setAttribute("sandbox",Mf)}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{n_(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?qD: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>=WD)){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?QD: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===k0){this.handleCspViolation(t.payload);return}if(t.method!==v0)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"||!Rf(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=RD(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=VD(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:Jg,launchUrlType:zu(t),networkPolicy:$D})}failRuntime(t){const r=ZD(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,XD(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 ZD(e){const t=Js(e);return fa(e)&&"cause"in e&&Tm(t,e.cause),t}function Tm(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function XD(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{},...e.cause!==void 0?{cause:t1(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})(),JD=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function e1(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(JD.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 t1(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=e1(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 r1(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 n1(e,t,r){try{e?.(t,r)}catch{}}function Il(e){try{const t=new URL(e);return t.protocol==="http:"&&lD(t.hostname)}catch{return!1}}function i1(e){try{return new URL(e).origin}catch{return}}function s1(e){return rp()?"*":i1(e)}function a1(e){return`${pm}
9
+
10
+ ${_m}
11
+
12
+ URL: ${e}`}function o1(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(a1(e.url))}function bl(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function c1(){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:$l,knownMethodCount:pr.length,supportsFileCreate:pr.some(i=>i.method===di),system:u1(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:d1(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function u1(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 d1(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function l1(e){return ke(vD,Em,{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 f1(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 h1(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 KD(e)}function m1(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",p),f=_=>{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",p,{once:!0}),n.signal.aborted&&p()});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 p=()=>{try{d.abort()}catch{}_(),u(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",p,{once:!0});const _=()=>n.signal.removeEventListener("abort",p);d.oncomplete=()=>{_(),c(f)},d.onabort=d.onerror=()=>{_(),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 D=s.getRandomValues(new Uint8Array(32));f=`ak_${Array.from(D,N=>N.toString(16).padStart(2,"0")).join("")}`,l.put(f,h)}}catch{d.abort()}}})}finally{a.close()}}}const E1=/^(?: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,g1=new Set(["origin","referer","user-agent"]);function p1(e,t){return wg({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const s={...n,signal:i},a=_1(r),c=await e.authenticatedRequest(a,s);return I1(c)})}).network}function _1(e){const t=T1(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function T1(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!A1(t)))}function A1(e){const t=e.trim().toLowerCase();return g1.has(t)}function I1(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:b1(e.headers)??{}}}function b1(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!y1(t)))}function y1(e){const t=e.trim().toLowerCase();return E1.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function N1(e,t,r){const n=M1(e.presentation,t);return{account:S1(e,t,r),network:p1(e,t),...e.roomSocket&&e.authorizationContext?{roomSocket:{connect:(i,s)=>e.roomSocket.connect(i,Ue(s,t.signal))}}:{},...e.storage===void 0?{}:{storage:O1(e,t)},...e.storage===void 0?{}:w1(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function w1(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 D1(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 S1(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??m1();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 O1(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 M1(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)=>Bg(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 R1(){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 C1(e){const t=R1(),r=new Set;let n=!1;const i=f=>{if(n||t.signal.aborted)return po(f),()=>{};let p=!0;const _=()=>{p&&(p=!1,r.delete(_),po(f))};return r.add(_),_},s=()=>a(e.signal.reason),a=f=>{if(!n){n=!0,e.signal.removeEventListener("abort",s),t.abort(f);for(const p of[...r])p();e.onDispose&&po(e.onDispose)}};e.signal.addEventListener("abort",s,{once:!0}),e.signal.aborted&&a(e.signal.reason);const c=N1(e,t,i);c.storage?.getRaw&&c.storage.setRaw&&(c.scopedStorage=nm({storage:c.storage,diagnostics:c.storageDiagnostics,coordinationKey:e.storage.storage,lock:im,resolveScope:async()=>rm((await h()).configuration)}));const u=Df(c,{hostCapabilities:e.hostCapabilities,hasUserDataPresentation:e.userDataPresentation!==void 0,hasUserDataSettings:e.userDataPresentation?.openDataPermissions!==void 0}),d=D1(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:L1(e.authPresentation,t)},...e.userDataPresentation===void 0?{}:{userDataPresentation:P1(e.userDataPresentation,t)},hostCapabilities:u.effectiveCapabilities,dispose:a}}function po(e){try{e()}catch{}}function L1(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 P1(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 v1(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 yl(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 yl(u,t).catch(()=>{})}}).catch(i),s.catch(()=>{}),s}async function yl(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,k1=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),x1="/__hb_sdk__/game-save-download",dt=(e,t)=>({code:e,message:t});function U1(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=v1({getRoot:t,locks:r,signal:e.signal}),s=new WeakMap,a=new WeakSet,c=_=>{_.signal.throwIfAborted(),_.lifecycle!=="cleanup"&&e.signal.throwIfAborted()},u=()=>i;function d(_){if(!/^\.hb-game-saves\/[a-zA-Z0-9_-]+\.zip$/.test(_))throw dt("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存");return _.slice(15)}async function l(_,y){c(y);const D=d(_);try{return await(await u()).getFileHandle(D)}catch(N){throw N instanceof DOMException&&N.name==="NotFoundError"?dt("FILE_NOT_FOUND","存档缓存不存在"):N}}function h(_){const y={kind:"file",mode:"readwrite",name:_.split("/").at(-1),async create(D,N){c(N);const v=d(_),I=await u();if(D.exclusive)try{throw await I.getFileHandle(v),dt("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(H){if(!(H instanceof DOMException&&H.name==="NotFoundError"))throw H}c(N),await I.getFileHandle(v,{create:!0}),c(N)},async remove(D){c(D);const N=d(_);if(i)try{await(await i).removeEntry(N)}catch(v){if(!(v instanceof DOMException&&v.name==="NotFoundError"))throw v}},async read(D){const N=await(await l(_,D)).getFile();if(N.size>_o)throw dt("FILE_TOO_LARGE","存档文件超过 8 MiB");const v=new Uint8Array(await N.arrayBuffer());try{return c(D),v}catch(I){throw v.fill(0),I}},async write(){throw dt("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(D){const N=await(await l(_,D)).getFile();return c(D),{kind:"file",size:N.size,modifiedAt:N.lastModified}}};return s.set(y,_),y}const f=async()=>{throw dt("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},p={kind:"directory",mode:"readwrite",name:"",file:h,directory(_){return{...p,name:_,async create(y,D){if(c(D),_!==".hb-game-saves")return f();await u(),c(D)}}},create:f,stat:f,list:f};return{files:{sandbox:p},transfer:{network:{async open(_,y){if(c(y),!bf(_))throw dt("METHOD_FORBIDDEN","仅支持受控存档下载");const D=await(e.fetch??fetch)(x1,{method:"POST",credentials:"same-origin",redirect:"error",headers:{"content-type":"application/json","x-hb-sdk-csrf":e.csrfToken()},body:JSON.stringify(_),signal:AbortSignal.any([y.signal,e.signal,AbortSignal.timeout(6e4)])});if(!D.ok){const N=await D.json().catch(()=>({}));throw dt(N.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return a.add(D),{status:D.status,headers:Object.fromEntries(Array.from(D.headers).filter(([N])=>k1.has(N)).map(([N,v])=>[N,[v]])),body:D}},async release(_){a.delete(_),await _.body?.cancel()}},files:{async writeResource(_,y,D,N){let v,I;try{c(N);const H=s.get(_);if(!H||!a.delete(y))throw dt("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(D.mode!=="replace-existing")throw dt("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(v=await(await l(H,N)).createWritable(),!y.body)throw dt("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");I=y.body.getReader();let R=0;for(;;){c(N);const x=await I.read().catch(U=>{throw c(N),dt(U instanceof DOMException&&U.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(c(N),x.done)break;if(R+=x.value.byteLength,R>Math.min(D.maxBytes??_o,_o))throw dt("FILE_TOO_LARGE","存档文件超过 8 MiB");await v.write(new Uint8Array(x.value)),N.onProgress(R)}if(D.expectedBytes!==void 0&&R!==D.expectedBytes)throw dt("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return c(N),await v.close(),v=void 0,{committedBytes:R}}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 v?.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 B1(e){return{declaredPermissions:e.declaredPermissions??{},platforms:[...e.platforms??[]].sort(),runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy}}function H1(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=KE(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=Af({...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 p={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:p,key:zn([u.userId,u.accountRevision,p,l.contextRevision,B1(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(D){l.throwIfAborted();const N=D&&typeof D=="object"&&"code"in D?String(D.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(N)&&Vt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(N)||D instanceof DOMException&&["AbortError","TimeoutError"].includes(D.name))throw D;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 p=f.result,_=Number(p?.expires_at)*1e3;(typeof p?.token!="string"||!p.token.trim()||!Number.isSafeInteger(p?.expires_at)||!Number.isSafeInteger(_)||_<=t()||!["legacy","local","server"].includes(String(p.user_data_mode)))&&Vt("INVALID_RESPONSE","开发运行授权响应无效");const y={token:p.token,expiresAt:Math.min(_,u.expiresAt),steamAccount:p.steam_account===!0,userDataMode:p.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 p=new AbortController,_=a(l,{...u,signal:AbortSignal.any([p.signal,e.signal])});h={promise:_,controller:p,users:0},n.set(l.key,h);const y=h;_.finally(()=>{n.get(l.key)===y&&n.delete(l.key)}).catch(()=>{})}h.users++;let f;try{const p=await Promise.race([h.promise,new Promise((_,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","账号或开发快照已变化,请重试"),p}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 Nl(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=uf(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:aE({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 F1(e){if(!Ii(e)||!wl(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!Ii(t)||!wl(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const z1={networkRequest:{status:"disabled",useOfficialDomain:!1}};function au(e){const t=ft(e.localDevGrant?Bc({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}}:j1()}function Am(e,t,r){return r?.localDevGrant?Bc({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:V1(e,t,t.networkRequest.useOfficialDomain)}function j1(){return{networkRequest:{...z1.networkRequest}}}function V1(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 wl(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function G1(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 Y1(e){return G1({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 q1(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 ou(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 _=a()===n;if(n.remove(),_){const y=a();y&&(y.inert=!1,y.removeAttribute("aria-hidden"));let D=To.get(n)??null;for(;D instanceof HTMLElement&&!D.isConnected;){const N=D.closest("[data-host-dialog]");D=N?To.get(N)??null:null}D instanceof HTMLElement&&(!y||y.contains(D))?D.focus():y?.querySelector("button")?.focus()}},d=Jm({kind:"dialog",mode:e.mode??"simulated",title:e.title,method:e.method,...e.callId?{callId:e.callId}:{},actions:s.map(_=>_.textContent?.trim()??"")},_=>{u(),c!==void 0?t(c):r(i?.reason??new DOMException(`宿主弹窗已${_}`,"AbortError"))});function l(){d.finish("cancelled")}function h(_){c=_,d.finish(_===e.cancelAction?"cancelled":"confirmed")}function f(_){if(a()!==n||(_.key==="Escape"&&e.cancelAction&&(_.preventDefault(),h(e.cancelAction)),_.key!=="Tab"||s.length===0))return;const y=s[0],D=s.at(-1);_.shiftKey&&document.activeElement===y?(_.preventDefault(),D.focus()):!_.shiftKey&&document.activeElement===D&&(_.preventDefault(),y.focus())}if(!d.active)return;if(i?.aborted){l();return}for(const _ of s)_.addEventListener("click",()=>h(_.dataset.action));n.addEventListener("click",_=>{_.target===n&&e.cancelAction&&h(e.cancelAction)}),n.dataset.interactionId=d.interactionId;const p=a();p&&(p.inert=!0,p.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 Dl="hb-sdk-action-dialog-style";async function Ga(e){await Im(e)}async function Q1(e){return await Im({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function Im(e){X1();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 ou({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 W1(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 $1(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 K1(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 Z1(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 X1(){if(document.getElementById(Dl))return;const e=document.createElement("style");e.id=Dl,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 J1={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};async function eS(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(J1[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 ou({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function tS(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:Eu,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,firstParty:e.firstParty===!0,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:Va},sdkVersion:Eu},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const Sl="hb-sdk-user-data-dialog-style",rS=new Map(Ma.map(e=>[e.key,e.name]));function nS(e){return(dr(e)?rS.get(e):void 0)??"游戏资料"}function iS(e){return e==="upload"?"可上传":"无网络权限"}async function sS(e){oS();const t=e.miniProgramName?.trim()||"当前小程序",r=nS(e.resource),n=`“${t}”想读取你的${r}`,i=iS(e.egress),s=gg[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 ou({root:c,title:n,method:"user.dataPermission.confirm",mode:"browser",signal:e.signal,...e.onShown?{onShown:e.onShown}:{},cancelAction:"cancelled"});return{decision:aS(u)}}function aS(e){return e==="deny"||e==="session"||e==="persistent"?e:"cancelled"}function oS(){if(document.getElementById(Sl))return;const e=document.createElement("style");e.id=Sl,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 cS(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},p=()=>{if(!d)for(const N of h)N()},_=async()=>{if(d||u)return;const N=t,v=f(),I=++a;if(!N||!v){r=void 0,i=void 0,p();return}try{const H=await N.getSnapshot();if(d||I!==a||t!==N||v!==f())return;r=H,n=v,i=void 0}catch(H){if(d||I!==a||t!==N||v!==f())return;r=void 0,s=v,i=H instanceof Error?H.message:"许可状态不可用"}p()},y=N=>{const v=t,I=f(),H=c;if(d||!v||!I)return Promise.resolve();const Y=++a;u++;const R=l.then(async()=>{if(!(d||c!==H||I!==f()))try{const x=await N(v);if(d||Y!==a||c!==H||I!==f())return;r=x,n=I,i=void 0}catch(x){if(d||Y!==a||c!==H||I!==f())return;r=void 0,s=I,i=x instanceof Error?x.message:"许可设置失败"}}).finally(()=>{c===H&&u--,p()});return l=R,R},D=()=>{c++,a++,u=0,l=Promise.resolve(),t=void 0,r=void 0,i=void 0};return{snapshot(){const N=f(),v=N&&N===n?r:void 0,I=e.declared?.();return{scenario:"unknown",dataScenario:"unknown",egressTier:e.egressTier(),declaredSource:I?.source??"manifest",permissionStateReady:v!==void 0,stateError:N&&N===s?i:void 0,simulatedSession:[],resources:Ma.map(H=>{const Y=v?.resources.find(x=>x.resource===H.key),R=Y?.allowed===!0;return{resource:H.key,name:H.name,declared:I?.resources.includes(H.key)??!1,decision:Y?.decision??"ask",revision:Y?.revision??0,sessionAllowed:Y?.sessionAllowed??!1,sessionSimulated:!1,licensed:R,...R?{sourceStatus:"unknown"}:{}}})}},subscribe(N){return d||h.add(N),()=>h.delete(N)},bind(N){d||(D(),t=N,_())},refresh:_,revokeSession:()=>y(N=>N.revokeSession()),resetAll:()=>y(N=>N.resetAll()),clearSession(){D(),p()},dispose(){d=!0,D(),h.clear()}}}function uS(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 dS(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:nE(r),source:"manifest"}}const lS=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"]}),fS="host.userDataTelemetry",Ol=80;function hS(e){return{method:fS,detail:{...e.payload,eventName:e.name,message:mS(e)}}}function mS(e){const t=lS[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}: ${bm(i)}`)}return[e.name,...r].join(" · ")}function bm(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=>bm(r)).join(",");else try{t=JSON.stringify(e)??""}catch{t="[无法序列化]"}return t.length>Ol?`${t.slice(0,Ol)}…`:t}const ES=44;function gS(e){const t=()=>e.isCapsuleHidden?.()?0:ES,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:i0,showLoading:n0,hideLoading:r0,vibrate:t0,openAppPage:W1,openWindow:$1,showShareMenu:K1,captureAndShare:Z1,setScreenshotChromeHidden:e0}}const Ml=["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}],Rl={"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 pS{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]:[...Ml];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:Rl[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(p=>p(l))}catch(p){u.cancelled=!0;for(const _ of u.timers)this.clearSchedule(_);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:p instanceof Error?p.message:String(p)}),u.reject(p);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(B0,{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:Rl[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(x0,{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(U0,{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(!Ml.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 _S=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 TS(e){return new pS(e)}function it(e,t){return Object.assign(new Error(t),{code:e})}function AS(e={}){const t=e.source??DS(e.document??document),r=e.readMetadata??SS,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 IS(t,d);if(qn(l.signal),d.source==="camera"&&h.length!==1)throw qe("MEDIA_PREPARE_FAILED","相机模拟必须恰好返回 1 项");const f=[];try{for(const p of h)qn(l.signal),f.push(await yS(p,d,l.signal,r,n,s,a));qn(l.signal)}catch(p){for(const _ of f)c(s.get(_.file));throw p}return f},release(d){for(const l of d)c(s.get(l.file))}}}async function IS(e,t){const r=await e.pickAlbum({accept:bS(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 bS(e){switch(e){case"image":return"image/*";case"video":return"video/*";default:return"image/*,video/*"}}async function yS(e,t,r,n,i,s,a){const c=NS(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=Cl(u.width),l=Cl(u.height);if(d===void 0||l===void 0)throw qe("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的显示尺寸`);if(c==="video"){if(Ll(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=wS(e);s.set(f,h),a.add(h);const p={type:c,mimeType:e.type,size:e.size,width:d,height:l,previewUrl:h,file:f};return c==="video"?{...p,durationMs:Ll(u.durationMs)}:p}function NS(e){if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video"}function wS(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 DS(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"?LS():CS()}}}async function SS(e){return e.type.startsWith("video/")?MS(e):OS(e)}async function OS(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 MS(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 RS(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 RS(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 CS(){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 LS(){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:PS(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 vS(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 PS(e){for(const t of["video/webm;codecs=vp8","video/webm","video/mp4"])if(e.isTypeSupported?.(t))return t;return"video/webm"}async function vS(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 Cl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:void 0}function Ll(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function kS(e){const t=ft(e.runtimePermissions),r=Bc({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=ft(e.publishedRuntimePermissions),s=ft(r.runtimePermissions);for(const a of Uc){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 Pl="__hb_sdk_mini_dev_console_installed__",xS=["log","debug","info","warn","error"];function US(e,t=console){if(t[Pl])return;let r=!1;for(const n of xS){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[Pl]=!0)}const oc=1,vl=64*1024,BS=64,HS=/^[A-Za-z0-9_-]{22}$/;class It extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function FS(e,t=!1){const r=jS(e,t);switch(cc(r,"Server message"),VS(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"),kl(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"),kl(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 zS(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 jS(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>vl)throw new It("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>vl)throw new It("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return GS(e),JSON.parse(e)}catch(r){throw r instanceof It?r:new It("INVALID_JSON","Channel frame must contain strict JSON")}}function kl(e){cc(e,"snapshot"),ri(e,["account","permissions"],"snapshot"),cc(e.account,"snapshot.account"),ri(e.account,["revision"],"snapshot.account"),Pr(e.account.revision,"snapshot.account.revision"),F1(e.permissions)||Ar("snapshot.permissions is invalid")}function VS(e){e.version!==oc&&Ar("version must be 1")}function cc(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"||!HS.test(e))&&Ar(`${t} must be a 22-character base64url value`)}function Ar(e){throw new It("INVALID_MESSAGE",e)}function GS(e){new YS(e).scan()}class YS{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>=BS)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 xl=[1e3,2e3,4e3,8e3,15e3];function qS(e){const t=new Set,r=e.webSocketFactory??(V=>new WebSocket(V)),n=e.randomValues??(V=>crypto.getRandomValues(V)),i=e.timers??{clearTimeout:V=>window.clearTimeout(V),setTimeout:(V,te)=>window.setTimeout(V,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 D=new Set,N=(V,te)=>{if(!(!e.onDiagnostic||D.has(V))){D.add(V);try{e.onDiagnostic({phase:V,...te?{code:te}:{}})}catch{}}},v=(V,te,z=!1)=>{if(l&&V.account.revision<l.account.revision)return;const j=l&&JSON.stringify(V)===JSON.stringify(l);if(l=V,!(j&&!z))for(const ee of t)ee(V,te)},I=()=>{if(h||p!==void 0||u)return;const V=xl[Math.min(f,xl.length-1)];f+=1,p=i.setTimeout(()=>{p=void 0,G()},V)},H=()=>{h||!_||u||(p!==void 0&&(i.clearTimeout(p),p=void 0),G())},Y=()=>{c()&&H()},R=()=>{a&&!a.hidden&&H()},x=()=>{y||(y=!0,s?.addEventListener("online",Y),a?.addEventListener("visibilitychange",R))},U=()=>{y&&(y=!1,s?.removeEventListener("online",Y),a?.removeEventListener("visibilitychange",R))},G=()=>{if(h||u)return;_=!0,x(),p!==void 0&&(i.clearTimeout(p),p=void 0);let V,te;try{V=r(e.url)}catch{N("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),I();return}try{te=WS(n)}catch{N("entropy","NONCE_GENERATION_FAILED");try{V?.close(1011,"channel initialization failed")}catch{}I();return}u=V;let z,j,ee;const J=()=>{V.removeEventListener("open",P),V.removeEventListener("message",w),V.removeEventListener("close",B),V.removeEventListener("error",O),d===J&&(d=void 0)},Q=()=>{if(u===V){u=void 0,J();try{V.close(1008,"invalid channel state")}catch{}I()}},P=()=>{if(!(h||u!==V))try{V.send(JSON.stringify({version:oc,type:"hello",csrfToken:e.csrfToken,clientNonce:te}))}catch{N("send","HELLO_SEND_FAILED"),Q()}},w=W=>{if(h||u!==V)return;if(typeof W.data!="string"){N("parse","TEXT_FRAME_REQUIRED"),Q();return}let $;try{$=FS(W.data)}catch(Z){N("parse",Z instanceof It?Z.code:"INVALID_MESSAGE"),Q();return}if($.type==="grant"){if(ee){N("sequence","DUPLICATE_GRANT"),Q();return}z=$.connectionEpoch,j=$.nextClientSequence,ee=zS({connectionEpoch:z,nextSequence:$.nextServerSequence}),f=0,D.clear(),v($.snapshot,{type:"grant"});return}if(!ee||!z||j===void 0){N("sequence","MESSAGE_BEFORE_GRANT"),Q();return}try{ee.accept($)}catch{N("sequence","INVALID_SEQUENCE"),Q();return}if($.type==="heartbeat"){try{V.send(JSON.stringify({version:oc,type:"heartbeat.ack",connectionEpoch:z,sequence:j}))}catch{N("send","HEARTBEAT_ACK_SEND_FAILED"),Q()}j=j===Number.MAX_SAFE_INTEGER?void 0:j+1;return}v($.snapshot,{type:"event",event:$.event},!0)},B=()=>{u===V&&(N("close","SOCKET_CLOSED"),u=void 0,J(),I())},O=()=>{N("open","SOCKET_ERROR"),Q()};V.addEventListener("open",P),V.addEventListener("message",w),V.addEventListener("close",B),V.addEventListener("error",O),d=J};return{connect:G,subscribeUpdates(V){return t.add(V),()=>t.delete(V)},dispose(){if(h)return;h=!0,_=!1,U(),p!==void 0&&i.clearTimeout(p),p=void 0;const V=u;u=void 0,d?.(),V?.close(1e3,"client disposed"),t.clear()}}}function QS(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 WS(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=QS(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let Ge=!1,ym=!1,rt;const Nm=new AbortController;try{US((e,t)=>{vr(`console.${e}`,{source:"host",message:t.map(r=>lO(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const $S="/__hb_sdk_bootstrap__",KS="/__hb_sdk__/network",ZS="/session/status",XS="/session/request",JS="/session/events",eO=1e3,tO=1e3,rO=15e3,Ul="dark",nO=["windows","macos","linux","unknown"],wm=new URL(location.href).searchParams,Dm=wm.get("mini_url"),ht=wm.get("ui_preview")==="1",iO={get device(){return BO("#device")}};if(!Dm&&!ht)throw iO.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Sm=Dm??"about:blank",je=await jm(),cu=ht?void 0:await kt.configure({csrfToken:je.csrfToken??"",diagnosticsToken:je.diagnosticsToken??"",signal:Nm.signal,query:CO,onDropped:e=>{se.diagnosticsDropped=e},onOwnershipLost:km});se.diagnosticTargetId=cu?.targetId??"";se.diagnosticOwnerId=cu?.ownerId??"";se.diagnosticTargetName=cu?.metadata.displayName??"";se.openPlatformBaseUrl=je.openPlatformBaseUrl;se.devReadiness=je.devReadiness;se.miniProgramSupportsDesktop=je.miniProgramSupportsDesktop;se.miniProgramPlatforms=je.devContext.platforms??[];se.desktopLaunch.workspaceCardsEnabled=je.workspaceCardsEnabled;zl(je.hostPlatform);jl(je.windowForm);je.lanAddresses;je.defaultLanAddressId;je.mobileLaunchRedirect;let Om=je.nativeAppLaunchUnavailableReason,ii=je.devSessionId,uc=je.miniProgramManifestAccessToken,ds=je.workspaceCardsEnabled,Mm=fu(je),Dt=je.devContext,dn=je.browserDevContext,tt=ti(dn);Ea();let In=au(tt),Ya=0;const jr=new AbortController;let uu=0,$t,dc=0,lc,fc,Ao=!1;const bn=T0({apply:A0,waitForLayout:async e=>{await ms(),await ql(e),await Ql(e)}});let du=!1;function Io(e){if(e.throwIfAborted(),Ge)throw new Mr("SESSION_CLOSED","调试台已关闭");if(se.diagnosticOwnershipLost)throw new Mr("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!du)throw new Mr("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(cn)throw new Mr("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const hc=p0({observe:()=>{const e=yi()?{width:hs.value.width,height:hs.value.height}:{width:Mo.value.screenWidth,height:Mo.value.screenHeight};return{preset:se.deviceSelectionId,orientation:yi()?e.width>=e.height?"landscape":"portrait":se.display.orientation,runtimeStatus:se.runtimeStatus,viewport:e,instanceId:rt?.mounted?rt.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:b0()}},async selectPreset(e,t){Io(t),se.deviceSelectOpen=!1;const r=se.previewMode,n=rt;I0(e),await ms(),t.throwIfAborted(),se.previewMode!==r&&await Bl(n,t)},async applyOrientation(e,t){Io(t),se.deviceSelectOpen=!1,await bn.applyDisplay({mode:e,hideCapsule:se.display.capsuleHidden},t)},async reload(e){Io(e),se.deviceSelectOpen=!1;const t=rt;Tr("runtime.restart",{boundary:uu+1}),Gr("manual restart").catch(()=>{}),await Bl(t,e)},async waitForLayout(e){await ms(),e.throwIfAborted(),await ql(e),await Ql(e)}}),ls=O0(),Rm={...hc.bridge,prepareCapture:ls.prepare,restoreCapture:ls.restore,cancel(e){hc.bridge.cancel(e),ls.cancel(e)}};window.__HB_SDK_PREVIEW__=Rm;async function Bl(e,t){for(;;){if(t.throwIfAborted(),Ge)throw new Mr("SESSION_CLOSED","调试台已关闭");if(rt!==e&&$t===void 0){const r=se.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 mc,Ec,gc,pc,_c,Tc,Hl=Date.now(),cn=!1,ln=-1,bi=!1,rr,Ac,Ic,fs,Or;const ha=new Set,Fl="hb-sdk:browser-dev-host:user-data-device";function sO(){try{const e=localStorage.getItem(Fl)?.trim();if(e)return e;const t=typeof crypto.randomUUID=="function"?crypto.randomUUID():`mock-${Date.now().toString(36)}`;return localStorage.setItem(Fl,t),t}catch{return"browser-mock-device"}}const aO=sO();function oO(){return{miniProgramId:Dt.miniProgramId?.trim().toLowerCase()||"anonymous-mini-program",userId:rr?.trim()||"anonymous-user",deviceId:aO,environment:"development"}}function Cm(){return Am(tt.runtimePermissions,In,tt)}function cO(){const e=ft(Cm());return e.valid&&e.permissions.network?.status==="enabled"?"upload":"no_network"}function uO(){return dS({declaredPermissions:tt.declaredPermissions,runtimePermissions:Cm()})}const Kt=cS({resolveScope:oO,egressTier:cO,declared:uO});function yn(){ym&&_0({...Kt.snapshot(),targetId:se.diagnosticTargetId,instanceId:rt?.instanceId})}Kt.subscribe(yn);ym=!0;yn();function bo(){const e=Kt.snapshot().stateError;if(e)throw new Error(e)}s0({async refresh(){await Kt.refresh(),bo()},async revokeSession(){await Kt.revokeSession(),bo()},async resetAll(){await Kt.resetAll(),bo()}});const bc=TS({onDiagnostic:({action:e,alias:t,detail:r})=>Tr(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Nn=Y1({applyStatus:e=>Fm(e,!0),fetchStatus:e=>Hm(hu(jr.signal,e)),getCanonicalRevision:()=>ln,onError:PO,reconcile:()=>TO(Ya)}),yc=q1({connectEvents:zm,invalidate:()=>Nn.invalidate(),isDisposed:()=>Ge,maxDelayMs:rO,minDelayMs:tO,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let yo=0,Zi="",No=!1,Nc,wc;function Lm(){ht||Ge||se.diagnosticOwnershipLost||kt.poll().finally(()=>{!Ge&&!se.diagnosticOwnershipLost&&(wc=window.setTimeout(Lm,1e3))})}Lm();await ma(!1);Vm();Ym(Gm(je));ht&&fO();Ni();ht||await vm();dO();Pm();wO();await Gr("initial");ht||(zm(),pO());du=!0;function Pm(){!ht&&!Ge&&(Nc=window.setTimeout(()=>{vm().finally(Pm)},1e3))}async function vm(){if(!(No||Ge)){No=!0;try{const e=await fetch(`${gu}?after=${yo}&limit=500`,{headers:{"x-hb-sdk-csrf":je.csrfToken??""},signal:AbortSignal.any([jr.signal,AbortSignal.timeout(5e3)])});if(!e.ok){se.diagnosticsStale=!0;return}const t=await e.json();if(Ge)return;if(Zi&&t.epoch!==Zi){yo=0,Zi=t.epoch,a0();return}Zi=t.epoch,se.uploadSessions=t.uploadSessions;const r=await fetch(`${gu}?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();se.diagnosticInstances=s.instances,se.diagnosticTargets=s.targets,se.diagnosticPrimaryTargetId=s.primaryTargetId;const a=s.targets.find(c=>c.targetId===se.diagnosticTargetId);a&&(se.diagnosticTargetName=a.metadata.displayName),a&&(a.state==="closed"||a.ownerId!==se.diagnosticOwnerId)&&km()}se.diagnosticsStale=!r.ok,se.diagnosticsGap=se.diagnosticsGap||t.gap===!0;const n=new Map(se.diagnosticTargets.map(s=>[s.targetId,s.metadata.displayName])),i=new Map(se.diagnosticInstances.map(s=>[s.instanceId,n.get(s.targetId)]));for(const s of t.items){const a=o0(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,c0(a,s.cursor))}yo=t.nextCursor}catch{se.diagnosticsStale=!0}finally{No=!1}}}function dO(){window.addEventListener("beforeunload",vO),window.addEventListener("hb-sdk:refresh-storage",Ni),mc=u0(()=>document.querySelector("#host-fullscreen-exit-mount")),Ec=Rn(()=>[si.value,Do.value,Xi.value?.state,Xi.value?.stale,Xi.value?.capabilities.storage].join("|"),()=>{se.storage=[],se.storageError="",Ni()}),gc=Rn(()=>se.devicePresetId,()=>bn.notifyViewportChange(),{flush:"post"}),pc=Rn(()=>se.previewMode,()=>{nr("preview mode changed"),Vl(!1),d0(!1),wn("preview mode changed")},{flush:"sync"}),_c=Rn(()=>hs.value,()=>bn.notifyViewportChange(),{flush:"post"}),Tc=Rn(()=>se.desktopWindow.closed,(e,t)=>{if(yi()){if(e){nr("desktop window closed"),se.runtimeStatus="closed";return}t&&se.runtimeStatus==="closed"&&wn("desktop window reopened")}},{flush:"sync"})}function lO(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:uu+1}),$t=window.setTimeout(()=>{$t=void 0,Ge||Gr(e)},0))}async function Gr(e,t=Sm,r){if(Ge||cn||se.diagnosticOwnershipLost)return;if($t!==void 0&&window.clearTimeout($t),$t=void 0,nr(e),yi()&&se.desktopWindow.closed){se.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=l0(i,u=>{ht||kt.event(i,u)}),a={instanceId:i,launchUrl:t,locationBasePath:r,interactions:s,sequence:++uu,state:"starting",iframe:n,terminal:new AbortController,permissions:Wm(In),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(a.iframe.dataset.hbSdkInstanceId=a.instanceId,rt=a,se.runtimeStatus="loading",Um(),ht||kt.send({operation:"register",instanceId:a.instanceId}),await ms(),!st(a))return;const c=Km("#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>',se.runtimeStatus="idle";return}c.replaceChildren(a.iframe),a.mounted=!0,kt.send({operation:"activate",instanceId:a.instanceId});try{const u=await C1(hO(a));if(!st(a)){u.dispose();return}a.assembly=u,u.ports.companion=bc.port,u.ports.media=AS({getMode:()=>se.mediaSimulation,signal:a.terminal.signal});const d=U1({signal:a.terminal.signal,csrfToken:()=>je.csrfToken??""}),l=H1({signal:a.terminal.signal,refreshAccount:f=>ma(!0,f),request:Bm,readState:()=>({signed:Dt,browser:tt,userId:rr,accountRevision:ln,networkEnabled:a.permissions.networkRequest.status==="enabled"})}),h=h1({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}:{},..._S},authPresentation:u.authPresentation,userDataPresentation:u.userDataPresentation,companionPresentation:bc.presentation,resolveLaunchConfiguration:async()=>l.resolveLaunchConfiguration((await u.resolveLaunch()).configuration,{signal:a.terminal.signal}),dispose:()=>Dc(a),onDevDocumentReload:(f,p)=>{st(a)&&Gr("development document reloaded",f,p)},onDevUploadSession:f=>{st(a)&&(a.uploadSessionId=f,Dn(a,{uploadSessionId:f}))},onReady:()=>{st(a)&&(a.state="ready",a.hadReady=!0,Oc.value=d?h.diagnostics.gameSaves:void 0,se.runtimeStatus="ready",Dn(a),vr("runtime.ready",{generation:a.sequence},Date.now(),void 0,a.instanceId))},onUserDataTelemetry:f=>{Kt.refresh();const p=hS(f);vr(p.method,p.detail,Date.now(),"info",a.instanceId)},onTrace:f=>gO(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(),Dc(a)}}function km(){Ge||se.diagnosticOwnershipLost||(se.diagnosticOwnershipLost=!0,nr("预览页面授权已失效"),se.runtimeStatus="closed",du=!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 xm(e,t){e.mounted&&(e.mounted=!1,kt.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function Dc(e){rt===e&&(Oc.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}:{}}),xm(e,"Runtime failed"),rt===e&&(se.runtimeStatus="error"))}function nr(e){const t=rt;t&&(rt=void 0,Oc.value=void 0,Kt.clearSession(),t.state!=="failed"&&(t.state="closed",Dn(t,{reason:e})),xm(t,e),(!si.value||si.value===se.diagnosticTargetId)&&(dc+=1,lc?.abort()),f0(),bc.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),Dc(t),bn.reset())}function fO(){const e=N0();se.diagnosticTargetId=e.targetId,se.diagnosticOwnerId=e.ownerId,se.diagnosticPrimaryTargetId=e.targetId,se.diagnosticTargetName=e.metadata.displayName,se.diagnosticTargets=[e],se.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"}};se.diagnosticTargets.push(t),se.diagnosticInstances.push({...se.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 hO(e){const t=e.terminal.signal,r=tt,n=ii,i=Am(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:Bm,storage:{area:"local",storage:uS(localStorage)},presentation:gS({close:async()=>{st(e)&&(nr("mini program closed"),Um(),se.runtimeStatus="closed",s&&Vl(!0))},reload:()=>{st(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:a=>{st(e)&&Gl(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:()=>y0}:{getDeviceMetrics:()=>Mo.value,applyDisplay:(a,c)=>bn.applyDisplay(a,c),isCapsuleHidden:()=>se.display.capsuleHidden},onViewportChange:a=>bn.onViewportChange(a)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:a=>{document.title=a}},resolveLaunch:async()=>({configuration:tS({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,firstParty:r.source==="remote"&&r.firstParty===!0,...se.miniProgram.bound&&se.miniProgram.name.trim()?{miniProgramName:se.miniProgram.name}:{},...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:s?se.hostPlatform:h0.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:a=>eS(a),confirmFollowAuthor:a=>Q1(a)},userDataPresentation:{confirmDataPermission:sS},protocol:mO(e)}}function yi(){return se.previewMode==="desktop"}function mO(e){return{async invoke(t){vr("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:EO(t)},Date.now(),void 0,e.instanceId)}}}function EO(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 Um(){document.documentElement.dataset.navigationBarStyle=Ul,Gl(Ul)}function gO(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(m0({...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 Bm(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 NO(n?KS:XS,{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 Hm(hu(jr.signal,t));return Qm(r)?Fm(n,e).status:Sc()}async function Hm(e){return await(await fetch(ZS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Fm(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<ln)return{changed:!1,status:Sc()};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!==Ac||i!==Ic;return ln=e.revision,bi=e.authenticated,rr=r,Ac=n,Ic=i,Vm(),yn(),t&&s&&ha.forEach(a=>a(rr)),{changed:s,status:Sc()}}function Sc(){return{authenticated:bi,revision:ln,...bi&&rr?{user_id:rr}:{}}}function pO(){if(!(!je.csrfToken||Ge))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Or=qS({csrfToken:je.csrfToken,onDiagnostic:t=>Tr("channel.diagnostic",t),url:e.toString()}),Or.subscribeUpdates((t,r)=>_O(t,r)),Or.connect()}catch{Or?.dispose(),Or=void 0}}function _O(e,t){Nn.invalidate(e.account.revision),UO(In,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Gr("status changed"):(In=Wm(e.permissions),AO())}function zm(){if(fs?.close(),fs=void 0,!rr||Ge)return;const e=new EventSource(JS);fs=e,e.addEventListener("account-invalidated",()=>{Nn.invalidate()}),e.addEventListener("account-revision",()=>{Nn.invalidate()}),e.onopen=()=>{yc.reset()},e.onerror=()=>{e.close(),yc.schedule()}}async function TO(e){Qm(e)&&await Gr("account revision changed")}async function AO(){Ge||await Gr("permission changed")}async function jm(e){const t=await fetch($S,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:hu(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=xO(r.mobileLaunchRedirect);if(Object.hasOwn(r,"mobileLaunchRedirect")&&r.mobileLaunchRedirect!==void 0&&!n)throw new SO;return{openPlatformBaseUrl:typeof r.openPlatformBaseUrl=="string"?r.openPlatformBaseUrl:void 0,devReadiness:yO(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:Nl(r.devContext,r.runtimePermissions),browserDevContext:Nl(r.browserDevContext??r.devContext,r.runtimePermissions),lanAddresses:Array.isArray(r.lanAddresses)?r.lanAddresses.filter(kO):[],loginAvailable:r.loginAvailable===!0,miniProgram:MO(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:bO(r.windowForm),hostPlatform:IO(r.hostPlatform)}}function IO(e){return nO.includes(e)?e:"unknown"}function bO(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 yO(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 NO(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 wO(){lu(),ht||(fc=window.setInterval(()=>{OO()},eO))}function DO(e){const t=Lr(tt),r=!!Dt.localDevLaunchToken,n=Dt.developmentSnapshotDigest;se.devReadiness=e.devReadiness,se.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,se.miniProgramPlatforms=e.devContext.platforms??[],zl(e.hostPlatform),jl(e.windowForm),ds=e.workspaceCardsEnabled,Mm=fu(e),Dt=e.devContext,dn=e.browserDevContext,tt=ti(dn),In=au(tt),Ea(),e.lanAddresses,e.defaultLanAddressId,e.mobileLaunchRedirect,Om=e.nativeAppLaunchUnavailableReason,ii=e.devSessionId,uc=e.miniProgramManifestAccessToken,Ym(Gm(e)),lu(),(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){se.localPermissions=w0(),se.devContextWarning="";return}se.localPermissions=kS(tt),se.devContextWarning=tt.source==="anonymous"?"未连接线上上下文":tt.warning?"本地上下文受限,请检查 CLI 状态":"",yn()}function lu(){let e;try{e=E0(Sm)}catch{}const t=Dt.miniProgramId?.trim().toLowerCase();let r=Om?.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="未发现可用的本机调试地址"),Yl({...e?{address:e}:{},...t?{miniProgramId:t}:{},...ds&&ii?{devSessionId:ii}:{},...uc?{miniProgramManifestToken:uc}:{},workspaceCardsEnabled:ds,ready:r==="",...r?{unavailableReason:r}:{}})}class SO extends Error{}async function OO(){if(!(Ao||Ge)){Ao=!0;try{const e=await jm();Hl=Date.now();const t=cn;cn=!1;const r=fu(e);if(!t&&r===Mm&&Lr(ti(e.browserDevContext))===Lr(tt)){dn=e.browserDevContext,tt=ti(dn),Ea();return}DO(e),t&&wn("CLI dev session reconnected")}catch{const t=ti(dn);Lr(t)!==Lr(tt)&&(tt=t,In=au(tt),Ea(),nr("local permission context expired"),wn("local permission context expired"),lu()),Date.now()-Hl>=3e4&&!cn&&(cn=!0,nr("CLI dev session disconnected"),Km("#device")?.replaceChildren(),se.runtimeStatus="closed",se.localPermissions=[],se.devContextWarning="调试会话已断开",Yl({ready:!1,unavailableReason:"调试会话已断开"}),se.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}})}finally{Ao=!1}}}function fu(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 Vm(){if(!bi){se.account={authenticated:!1,avatar:"",nickname:"未登录"};return}se.account={authenticated:!0,avatar:Ic??"",nickname:Ac||rr||"已登录"}}function Gm(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Ym(e){if(!!!e?.miniProgramId||!e){se.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试",description:"",version:""},yn();return}se.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 MO(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=++dc;lc?.abort();const t=new AbortController;lc=t;const r=si.value,n=!r||r===se.diagnosticTargetId,i=Xi.value,s=Do.value||(n?rt?.instanceId:void 0),a=()=>!Ge&&e===dc&&r===si.value&&s===(Do.value||(n?rt?.instanceId:void 0));if(!n&&(!i||!s||i.stale||i.state!=="attached"||!i.capabilities.storage)){se.storage=[],se.storageError=!i||!i.capabilities.storage?"当前设备不支持存储诊断":"当前设备未连接或没有运行实例";return}if(ht){se.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}],se.storageError="";return}if(!s){se.storage=[],se.storageError="";return}try{const c=await g0({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 诊断查询失败");se.storage=c.value,se.storageError=""}catch(c){if(!a())return;se.storage=[],se.storageError=$m(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){RO(Oo(e,t,r,n==="debug"?"log":n),i)}function RO(e,t){if(Ge)return;if(ht){So({...e,targetId:se.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 CO(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 LO(e,t){Tr("host.message",{message:e,status:t})}function PO(e){Ge||LO($m(e),"error")}function Tr(e,t){vr(e,t)}function vO(){kt.close(),Nc!==void 0&&window.clearTimeout(Nc),wc!==void 0&&window.clearTimeout(wc),!Ge&&(Ge=!0,ls.dispose(),hc.dispose(),window.__HB_SDK_PREVIEW__===Rm&&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(()=>Nm.abort(),2e3),fs?.close(),Or?.dispose(),Or=void 0,yc.dispose(),$t!==void 0&&window.clearTimeout($t),$t=void 0,fc!==void 0&&window.clearInterval(fc),ha.clear(),mc?.(),mc=void 0,Ec?.(),Ec=void 0,gc?.(),gc=void 0,pc?.(),pc=void 0,_c?.(),_c=void 0,Tc?.(),Tc=void 0)}function hu(e,t){return t?AbortSignal.any([e,t]):e}function Qm(e){return!Ge&&e===Ya}function kO(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 xO(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 Wm(e){return{networkRequest:{...e.networkRequest}}}function UO(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function $m(e){return e instanceof Error&&e.message?e.message:"操作失败"}function St(e){return Object.prototype.toString.call(e)==="[object Object]"}function BO(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function Km(e){return document.querySelector(e)??void 0}